Unnamed: 0
int64
0
16k
text_prompt
stringlengths
110
62.1k
code_prompt
stringlengths
37
152k
7,300
Given the following text description, write Python code to implement the functionality described below step by step Description: NBA Free throw analysis Now let's see some of these methods in action on real world data. I'm not a basketball guru by any means, but I thought it would be fun to see whether we can find players that perform differently in free throws when playing at home versus away. Basketballvalue.com has some nice play by play data on season and playoff data between 2007 and 2012, which we will use for this analysis. It's not perfect, for example it only records player's last names, but it will do for the purpose of demonstration. Getting data Step1: Data munging Because only last name is included, we analyze "player-team" combinations to avoid duplicates. This could mean that the same player has multiple rows if he changed teams. Step2: Overall free throw% We note that at home the ft% is slightly higher, but there is not much difference Step3: Aggregating to player level We use a pivot table to get statistics on every player. Step4: Individual tests For each player, we assume each free throw is an independent draw from a Bernoulli distribution with probability $p_{ij}$ of succeeding where $i$ denotes the player and $j={a, h}$ denoting away or home, respectively. Our null hypotheses are that there is no difference between playing at home and away, versus the alternative that there is a difference. While you could argue a one-sided test for home advantage is also appropriate, I am sticking with a two-sided test. $$\begin{aligned} H_{0, i}& Step5: Global tests We can test the global null hypothesis, that is, there is no difference in free throw % between playing at home and away for any player using both Fisher's Combination Test and the Bonferroni method. Which one is preferred in this case? I would expect to see many small difference in effects rather than a few players showing huge effects, so Fisher's Combination Test probably has much better power. Fisher's combination test We expect this test to have good power Step6: Bonferroni's method The theory would suggest this test has a lot less power, it's unlikely to have a few players where the difference is relatively huge. Step7: Conclusion Indeed, we find a small p-value for Fisher's Combination Test, while Bonferroni's method does not reject the null hypothesis. In fact, if we multiply the smallest p-value by the number of hypotheses, we get a number larger than 1, so we aren't even remotely close to any significance. Multiple tests So there definitely seems some evidence that there is a difference in performance. If you tell a sport's analyst that there is evidence that at least some players that perform differently away versus at home, their first question will be Step8: If we don't correct for multiple comparisons, there are actually 65 "significant" results (at $\alpha = 0.05$), which corresponds to about 7% of the players. We expect around 46 rejections by chance, so it's a bit more than expected, but this is a bogus method so no matter what, we should discard the results. Bonferroni correction Let's do it the proper way though, first using Bonferroni correction. Since this method is basically the same as the Bonferroni global test, we expect no rejections Step9: Indeed, no rejections. Benjamini-Hochberg Let's also try the BHq procedure, which has a bit more power than Bonferonni. Step10: Even though the BHq procedure has more power, we can't reject any of the individual hypothesis, hence we don't find sufficient evidence for any of the players that free throw performance is affected by location. Taking a step back If we take a step back and take another look at our data, we quickly find that we shouldn't be surprised with our results. In particular, our tests are clearly underpowered. That is, the probability of rejecting the null hypothesis when there is a true effect is very small given the effect sizes that are reasonable. While there are definitely sophisticated approaches to power analysis, we can use a simple tool to get a rough estimate. The free throw% is around 75% percent, and at that level it takes almost 2500 total attempts to detect a difference in ft% of 5% ($\alpha = 0.05$, power = $0.8$), and 5% is a pretty remarkable difference when only looking at home and away difference. For most players, the observed difference is not even close to 5%, and we have only 11 players in our dataset with more than 2500 free throws. To have any hope to detect effects for those few players that have plenty of data, the worst thing one can do is throw in a bunch of powerless tests. It would have been much better to restrict our analysis to players where we have a lot of data. Don't worry, I've already done that and again we cannot reject a single hypothesis. So unfortunately it seems we won't be impressing our friends with cool results, more likely we will be the annoying person pointing out the fancy stats during a game don't really mean anything. There is one cool take-away though
Python Code: from __future__ import division import pandas as pd import numpy as np import scipy as sp import scipy.stats import toyplot as tp Explanation: NBA Free throw analysis Now let's see some of these methods in action on real world data. I'm not a basketball guru by any means, but I thought it would be fun to see whether we can find players that perform differently in free throws when playing at home versus away. Basketballvalue.com has some nice play by play data on season and playoff data between 2007 and 2012, which we will use for this analysis. It's not perfect, for example it only records player's last names, but it will do for the purpose of demonstration. Getting data: Download and extract play by play data from 2007 - 2012 data from http://basketballvalue.com/downloads.php Concatenate all text files into file called raw.data Run following to extract free throw data into free_throws.csv cat raw.data | ack Free Throw | sed -E 's/[0-9]+([A-Z]{3})([A-Z]{3})[[:space:]][0-9]*[[:space:]].?[0-9]{2}:[0-9]{2}:[0-9]{2}[[:space:]]*\[([A-z]{3}).*\][[:space:]](.*)[[:space:]]Free Throw.*(d|\))/\1,\2,\3,\4,\5/ ; s/(.*)d$/\10/ ; s/(.*)\)$/\11/' &gt; free_throws.csv End of explanation df = pd.read_csv('free_throws.csv', names=["away", "home", "team", "player", "score"]) df["at_home"] = df["home"] == df["team"] df.head() Explanation: Data munging Because only last name is included, we analyze "player-team" combinations to avoid duplicates. This could mean that the same player has multiple rows if he changed teams. End of explanation df.groupby("at_home").mean() Explanation: Overall free throw% We note that at home the ft% is slightly higher, but there is not much difference End of explanation sdf = pd.pivot_table(df, index=["player", "team"], columns="at_home", values=["score"], aggfunc=[len, sum], fill_value=0).reset_index() sdf.columns = ['player', 'team', 'atm_away', 'atm_home', 'score_away', 'score_home'] sdf['atm_total'] = sdf['atm_away'] + sdf['atm_home'] sdf['score_total'] = sdf['score_away'] + sdf['score_home'] sdf.sample(10) Explanation: Aggregating to player level We use a pivot table to get statistics on every player. End of explanation data = sdf.query('atm_total > 50').copy() len(data) data['p_home'] = data['score_home'] / data['atm_home'] data['p_away'] = data['score_away'] / data['atm_away'] data['p_ovr'] = (data['score_total']) / (data['atm_total']) # two-sided data['zval'] = (data['p_home'] - data['p_away']) / np.sqrt(data['p_ovr'] * (1-data['p_ovr']) * (1/data['atm_away'] + 1/data['atm_home'])) data['pval'] = 2*(1-sp.stats.norm.cdf(np.abs(data['zval']))) # one-sided testing home advantage # data['zval'] = (data['p_home'] - data['p_away']) / np.sqrt(data['p_ovr'] * (1-data['p_ovr']) * (1/data['atm_away'] + 1/data['atm_home'])) # data['pval'] = (1-sp.stats.norm.cdf(data['zval'])) data.sample(10) canvas = tp.Canvas(800, 300) ax1 = canvas.axes(grid=(1, 2, 0), label="Histogram p-values") hist_p = ax1.bars(np.histogram(data["pval"], bins=50, normed=True), color="steelblue") hisp_p_density = ax1.plot([0, 1], [1, 1], color="red") ax2 = canvas.axes(grid=(1, 2, 1), label="Histogram z-values") hist_z = ax2.bars(np.histogram(data["zval"], bins=50, normed=True), color="orange") x = np.linspace(-3, 3, 200) hisp_z_density = ax2.plot(x, sp.stats.norm.pdf(x), color="red") Explanation: Individual tests For each player, we assume each free throw is an independent draw from a Bernoulli distribution with probability $p_{ij}$ of succeeding where $i$ denotes the player and $j={a, h}$ denoting away or home, respectively. Our null hypotheses are that there is no difference between playing at home and away, versus the alternative that there is a difference. While you could argue a one-sided test for home advantage is also appropriate, I am sticking with a two-sided test. $$\begin{aligned} H_{0, i}&: p_{i, a} = p_{i, h},\ H_{1, i}&: p_{i, a} \neq p_{i, h}. \end{aligned}$$ To get test statistics, we conduct a simple two-sample proportions test, where our test statistic is: $$Z = \frac{\hat p_h - \hat p_a}{\sqrt{\hat p (1-\hat p) (\frac{1}{n_h} + \frac{1}{n_a})}}$$ where - $n_h$ and $n_a$ are the number of attempts at home and away, respectively - $X_h$ and $X_a$ are the number of free throws made at home and away - $\hat p_h = X_h / n_h$ is the MLE for the free throw percentage at home - likewise, $\hat p_a = X_a / n_a$ for away ft% - $\hat p = \frac{X_h + X_a}{n_h + n_a}$ is the MLE for overall ft%, used for the pooled variance estimator Then we know from Stats 101 that $Z \sim N(0, 1)$ under the null hypothesis that there is no difference in free throw percentages. For a normal approximation to hold, we need $np > 5$ and $n(1-p) > 5$, since $p \approx 0.75$, let's be a little conservative and say we need at least 50 samples for a player to get a good normal approximation. This leads to data on 936 players, and for each one we compute Z, and the corresponding p-value. End of explanation T = -2 * np.sum(np.log(data["pval"])) print 'p-value for Fisher Combination Test: {:.3e}'.format(1 - sp.stats.chi2.cdf(T, 2*len(data))) Explanation: Global tests We can test the global null hypothesis, that is, there is no difference in free throw % between playing at home and away for any player using both Fisher's Combination Test and the Bonferroni method. Which one is preferred in this case? I would expect to see many small difference in effects rather than a few players showing huge effects, so Fisher's Combination Test probably has much better power. Fisher's combination test We expect this test to have good power: if there is a difference between playing at home and away we would expect to see a lot of little effects. End of explanation print '"p-value" Bonferroni: {:.3e}'.format(min(1, data["pval"].min() * len(data))) Explanation: Bonferroni's method The theory would suggest this test has a lot less power, it's unlikely to have a few players where the difference is relatively huge. End of explanation alpha = 0.05 data["reject_naive"] = 1*(data["pval"] < alpha) print 'Number of rejections: {}'.format(data["reject_naive"].sum()) Explanation: Conclusion Indeed, we find a small p-value for Fisher's Combination Test, while Bonferroni's method does not reject the null hypothesis. In fact, if we multiply the smallest p-value by the number of hypotheses, we get a number larger than 1, so we aren't even remotely close to any significance. Multiple tests So there definitely seems some evidence that there is a difference in performance. If you tell a sport's analyst that there is evidence that at least some players that perform differently away versus at home, their first question will be: "So who is?" Let's see if we can properly answer that question. Naive method Let's first test each null hypothesis ignoring the fact that we are dealing with many hypotheses. Please don't do this at home! End of explanation from statsmodels.sandbox.stats.multicomp import multipletests data["reject_bc"] = 1*(data["pval"] < alpha / len(data)) print 'Number of rejections: {}'.format(data["reject_bc"].sum()) Explanation: If we don't correct for multiple comparisons, there are actually 65 "significant" results (at $\alpha = 0.05$), which corresponds to about 7% of the players. We expect around 46 rejections by chance, so it's a bit more than expected, but this is a bogus method so no matter what, we should discard the results. Bonferroni correction Let's do it the proper way though, first using Bonferroni correction. Since this method is basically the same as the Bonferroni global test, we expect no rejections: End of explanation is_reject, corrected_pvals, _, _ = multipletests(data["pval"], alpha=0.1, method='fdr_bh') data["reject_fdr"] = 1*is_reject data["pval_fdr"] = corrected_pvals print 'Number of rejections: {}'.format(data["reject_fdr"].sum()) Explanation: Indeed, no rejections. Benjamini-Hochberg Let's also try the BHq procedure, which has a bit more power than Bonferonni. End of explanation len(data.query("atm_total > 2500")) reduced_data = data.query("atm_total > 2500").copy() is_reject2, corrected_pvals2, _, _ = multipletests(reduced_data["pval"], alpha=0.1, method='fdr_bh') reduced_data["reject_fdr2"] = 1*is_reject2 reduced_data["pval_fdr2"] = corrected_pvals2 print 'Number of rejections: {}'.format(reduced_data["reject_fdr2"].sum()) Explanation: Even though the BHq procedure has more power, we can't reject any of the individual hypothesis, hence we don't find sufficient evidence for any of the players that free throw performance is affected by location. Taking a step back If we take a step back and take another look at our data, we quickly find that we shouldn't be surprised with our results. In particular, our tests are clearly underpowered. That is, the probability of rejecting the null hypothesis when there is a true effect is very small given the effect sizes that are reasonable. While there are definitely sophisticated approaches to power analysis, we can use a simple tool to get a rough estimate. The free throw% is around 75% percent, and at that level it takes almost 2500 total attempts to detect a difference in ft% of 5% ($\alpha = 0.05$, power = $0.8$), and 5% is a pretty remarkable difference when only looking at home and away difference. For most players, the observed difference is not even close to 5%, and we have only 11 players in our dataset with more than 2500 free throws. To have any hope to detect effects for those few players that have plenty of data, the worst thing one can do is throw in a bunch of powerless tests. It would have been much better to restrict our analysis to players where we have a lot of data. Don't worry, I've already done that and again we cannot reject a single hypothesis. So unfortunately it seems we won't be impressing our friends with cool results, more likely we will be the annoying person pointing out the fancy stats during a game don't really mean anything. There is one cool take-away though: Fisher's combination test did reject the global null hypothesis even though each single test had almost no power, combined they did yield a significant result. If we aggregate the data across all players first and then conduct a single test of proportions, it turns out we cannot reject that hypothesis. End of explanation
7,301
Given the following text description, write Python code to implement the functionality described below step by step Description: Short intro to the SCT library of AutoGraph Work in progress, use with care and expect changes. The pyct module packages the source code transformation APIs used by AutoGraph. This tutorial is just a preview - there is no PIP package yet, and the API has not been finalized, although most of those shown here are quite stable. Run in Colab Requires tf-nightly Step1: Writing a custom code translator transformer.CodeGenerator is an AST visitor that outputs a string. This makes it useful in the final stage of translating Python to another language. Here's a toy C++ code generator written using a transformer.CodeGenerator, which is just a fancy subclass of ast.NodeVisitor Step2: Another helpful API is transpiler.GenericTranspiler which takes care of parsing Step3: Try it on a simple function Step4: Helpful static analysis passes The static_analysis module contains various helper passes for dataflow analyis. All these passes annotate the AST. These annotations can be extracted using anno.getanno. Most of them rely on the qual_names annotations, which just simplify the way more complex identifiers like a.b.c are accessed. The most useful is the activity analysis which just inventories symbols read, modified, etc. Step5: Another useful utility is the control flow graph builder. Of course, a CFG that fully accounts for all effects is impractical to build in a late-bound language like Python without creating an almost fully-connected graph. However, one can be reasonably built if we ignore the potential for functions to raise arbitrary exceptions. Step6: Other useful analyses include liveness analysis. Note that these make simplifying assumptions, because in general the CFG of a Python program is a graph that's almost complete. The only robust assumption is that execution can't jump backwards. Step7: Writing a custom Python-to-Python transpiler transpiler.Py2Py is a generic class for a Python source-to-source compiler. It operates on Python ASTs. Subclasses override its transform_ast method. Unlike the transformer module, which have an AST as input/output, the transpiler APIs accept and return actual Python objects, handling the tasks associated with parsing, unparsing and loading of code. Here's a transpiler that does nothing Step8: The main entry point is the transform method returns the transformed version of the input. Step9: Adding new variables to the transformed code The transformed function has the same global and local variables as the original function. You can of course generate local imports to add any new references into the generated code, but an easier method is to use the get_extra_locals method
Python Code: !pip install tf-nightly Explanation: Short intro to the SCT library of AutoGraph Work in progress, use with care and expect changes. The pyct module packages the source code transformation APIs used by AutoGraph. This tutorial is just a preview - there is no PIP package yet, and the API has not been finalized, although most of those shown here are quite stable. Run in Colab Requires tf-nightly: End of explanation import gast from tensorflow.python.autograph.pyct import transformer class BasicCppCodegen(transformer.CodeGenerator): def visit_Name(self, node): self.emit(node.id) def visit_arguments(self, node): self.visit(node.args[0]) for arg in node.args[1:]: self.emit(', ') self.visit(arg) def visit_FunctionDef(self, node): self.emit('void {}'.format(node.name)) self.emit('(') self.visit(node.args) self.emit(') {\n') self.visit_block(node.body) self.emit('\n}') def visit_Call(self, node): self.emit(node.func.id) self.emit('(') self.visit(node.args[0]) for arg in node.args[1:]: self.emit(', ') self.visit(arg) self.emit(');') Explanation: Writing a custom code translator transformer.CodeGenerator is an AST visitor that outputs a string. This makes it useful in the final stage of translating Python to another language. Here's a toy C++ code generator written using a transformer.CodeGenerator, which is just a fancy subclass of ast.NodeVisitor: End of explanation import gast from tensorflow.python.autograph.pyct import transpiler class PyToBasicCpp(transpiler.GenericTranspiler): def transform_ast(self, node, ctx): codegen = BasicCppCodegen(ctx) codegen.visit(node) return codegen.code_buffer Explanation: Another helpful API is transpiler.GenericTranspiler which takes care of parsing: End of explanation def f(x, y): print(x, y) code, _ = PyToBasicCpp().transform(f, None) print(code) Explanation: Try it on a simple function: End of explanation def get_node_and_ctx(f): node, source = parser.parse_entity(f, ()) f_info = transformer.EntityInfo( name='f', source_code=source, source_file=None, future_features=(), namespace=None) ctx = transformer.Context(f_info, None, None) return node, ctx from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import qual_names from tensorflow.python.autograph.pyct.static_analysis import annos from tensorflow.python.autograph.pyct.static_analysis import activity def f(a): b = a + 1 return b node, ctx = get_node_and_ctx(f) node = qual_names.resolve(node) node = activity.resolve(node, ctx) fn_scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE) # Note: tag will be changed soon. print('read:', fn_scope.read) print('modified:', fn_scope.modified) Explanation: Helpful static analysis passes The static_analysis module contains various helper passes for dataflow analyis. All these passes annotate the AST. These annotations can be extracted using anno.getanno. Most of them rely on the qual_names annotations, which just simplify the way more complex identifiers like a.b.c are accessed. The most useful is the activity analysis which just inventories symbols read, modified, etc.: End of explanation from tensorflow.python.autograph.pyct import cfg def f(a): if a > 0: return a b = -a node, ctx = get_node_and_ctx(f) node = qual_names.resolve(node) cfgs = cfg.build(node) cfgs[node] Explanation: Another useful utility is the control flow graph builder. Of course, a CFG that fully accounts for all effects is impractical to build in a late-bound language like Python without creating an almost fully-connected graph. However, one can be reasonably built if we ignore the potential for functions to raise arbitrary exceptions. End of explanation from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import cfg from tensorflow.python.autograph.pyct import qual_names from tensorflow.python.autograph.pyct.static_analysis import annos from tensorflow.python.autograph.pyct.static_analysis import reaching_definitions from tensorflow.python.autograph.pyct.static_analysis import reaching_fndefs from tensorflow.python.autograph.pyct.static_analysis import liveness def f(a): b = a + 1 return b node, ctx = get_node_and_ctx(f) node = qual_names.resolve(node) cfgs = cfg.build(node) node = activity.resolve(node, ctx) node = reaching_definitions.resolve(node, ctx, cfgs) node = reaching_fndefs.resolve(node, ctx, cfgs) node = liveness.resolve(node, ctx, cfgs) print('live into `b = a + 1`:', anno.getanno(node.body[0], anno.Static.LIVE_VARS_IN)) print('live into `return b`:', anno.getanno(node.body[1], anno.Static.LIVE_VARS_IN)) Explanation: Other useful analyses include liveness analysis. Note that these make simplifying assumptions, because in general the CFG of a Python program is a graph that's almost complete. The only robust assumption is that execution can't jump backwards. End of explanation from tensorflow.python.autograph.pyct import transpiler class NoopTranspiler(transpiler.PyToPy): def get_caching_key(self, ctx): # You may return different caching keys if the transformation may generate # code versions. return 0 def get_extra_locals(self): # No locals needed for now; see below. return {} def transform_ast(self, ast, transformer_context): return ast tr = NoopTranspiler() Explanation: Writing a custom Python-to-Python transpiler transpiler.Py2Py is a generic class for a Python source-to-source compiler. It operates on Python ASTs. Subclasses override its transform_ast method. Unlike the transformer module, which have an AST as input/output, the transpiler APIs accept and return actual Python objects, handling the tasks associated with parsing, unparsing and loading of code. Here's a transpiler that does nothing: End of explanation def f(x, y): return x + y new_f, module, source_map = tr.transform(f, None) new_f(1, 1) Explanation: The main entry point is the transform method returns the transformed version of the input. End of explanation from tensorflow.python.autograph.pyct import parser class HelloTranspiler(transpiler.PyToPy): def get_caching_key(self, ctx): return 0 def get_extra_locals(self): return {'name': 'you'} def transform_ast(self, ast, transformer_context): print_code = parser.parse('print("Hello", name)') ast.body = [print_code] + ast.body return ast def f(x, y): pass new_f, _, _ = HelloTranspiler().transform(f, None) _ = new_f(1, 1) import inspect print(inspect.getsource(new_f)) Explanation: Adding new variables to the transformed code The transformed function has the same global and local variables as the original function. You can of course generate local imports to add any new references into the generated code, but an easier method is to use the get_extra_locals method: End of explanation
7,302
Given the following text description, write Python code to implement the functionality described below step by step Description: Sucesión de Fibonacci La sucesión de Fibonacci se usa para modelar crecimiento de poblaciones de bichos. Por ejemplo Step1: Polinomio característico Como $\lambda$ es un valor propio de $A$ $(\lambda I-A)\overrightarrow{X}=\overrightarrow{0}$ un eigenvector que sea su solución depende de que $\det(\lambda I-A)=\det\left(\left[\begin{array}{cc} \lambda & 0\ 0 & \lambda \end{array}\right]-\left[\begin{array}{cc} 1 & 1\ 1 & 0 \end{array}\right]\right)=\overrightarrow{0}$ Luego $\det\left(\left[\begin{array}{cc} \lambda-1 & -1\ -1 & \lambda \end{array}\right]\right)=(\lambda-1)\lambda-(-1)(-1)=\lambda^{2}-\lambda-1$ Valores propios Para obtener los valores propios usamos la fórmula general para encontrar valores de $\lambda$ que satisfagan el polinomio característico $p(\lambda)=\lambda^{2}-\lambda-1$ Acá la fórmula general Step2: En pos de la "fórmula cerrada" Si $A$ es diagonalizable entonces existe $P^{-1}AP=D$ Como $PP^{-1}=I$ es la matriz identidad, y es el neutro multiplicativo. $PP^{-1}APP^{-1}=PDP^{-1}$ luego $A=PDP^{-1}$ y entonces $A^{k}=\left(PDP^{-1}\right)^{k}$ ello significa que $PDP^{-1}$ se multiplica $k$ veces $A^{k}=\left(PDP^{-1}\right)\left(PDP^{-1}\right)\left(PDP^{-1}\right)...$ cambiando la agrupación de los paréntesis se tiene $A^{k}=PDDD...DP^{-1}$ lo cuál explica la siguiente ecuación Step3: Sucesión de Lucas Esta serie es igual a la de Fibonacci pero empieza con $F_{0}=1$ y $F_{1}=2$. Step4: ¿Cómo se ven las series de Lucas y Fibonacci juntas? Step5: Fibonacci con fórmula Step8: Dificultades algorítmicas A continuación se miden los tiempos de ejecución de ambas implementaciones de la sucesión de Fibonacci. Cada una se ejecuta diezmil veces y se reporta el tiempo promedio.
Python Code: # importamos bibliotecas cómputo de matrices import numpy as np A = np.matrix([[1, 1], [1, 0]]) # para k=3 A se multiplica por sí misma tres veces: A*A*A u0 = [1, 0] # u3 np.dot(A*A*A, u0) Explanation: Sucesión de Fibonacci La sucesión de Fibonacci se usa para modelar crecimiento de poblaciones de bichos. Por ejemplo: conejitos. Se empieza con un granero vacío, en $t_{0}$, en $t_{1}$ una parejita de conejos se metió quién sabe cómo y usan ese tiempo para instalarse, en $t_{1}$ sigue la misma parejita, pero una nueva parejita ya se está gestando. En $t_{3}$ nace una segunda pareja, ahora son dos: la nueva usa ese tiempo para instalarse y la primera otra vez está gestando una nueva. Uno puede imaginarse el área que ocupa la población de conejitos viendo esta figura: <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/db/34%2A21-FibonacciBlocks.png/300px-34%2A21-FibonacciBlocks.png"> También puede usarse la serie de Fibonacci para aproximar la proporción áurea: <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/93/Fibonacci_spiral_34.svg/320px-Fibonacci_spiral_34.svg.png"> Más información en el artículo "Sucesión de Fibonacci" en la Wikipedia. La ecuación de recurrencia de segundo orden es así: $F_{k+2}=F_{k+1}+F_{k}$ <a name="eq1">.......eq1</a> Con valores iniciales $F_{0}=1, F_{1}=1$ la secuencia es: $0,1,1,2,3,5,8,13,...$ Hay dos formas de obtener el k-ésimo valor de esta serie. Usando la ecuación de recurrencia <a href="#eq1">eq1</a> o usando esta fórmula cerrada: $F_{k}=\frac{1}{\sqrt{5}}\left[\left(\frac{1+\sqrt{5}}{2}\right)^{k}-\left(\frac{1-\sqrt{5}}{2}\right)^{k}\right]$<a name="eq2">.......eq2</a> Teorema Sea $A$ una matriz cuadrada de dimensión n. Si $A$ tiene n valores propios distintos $\lambda_{1},\lambda_{2},...,\lambda_{n},$ con vectores propios correspondientes $v_{1},v_{2},...,v_{n},$ entonces $A$ es diagonalizable, o sea existen las matrices $P$ y $D$ de dimensión n tales que $D$ es una matriz diagonal y $P^{-1}AP=D$ $D=\left[\begin{array}{cccc} \lambda_{1} & 0 & \cdots\ & 0\ 0 & \lambda_{2} & \cdots\ & 0\ \vdots\ & \vdots\ & \ddots\ & \vdots\ 0 & 0 & 0 & \lambda_{n} \end{array}\right]$ $P$ es la matriz cuyas columnas son los vectores propios. $P=\left[v_{1}|v_{2}|...|v_{n}\right]$ Se generan los núneros de la sucesión de Fibonacci en las coordenadas de los vectores en $R2$ a partir de la condición inicial $u_{0}=\left[\begin{array}{c} F_{1}\ F_{0} \end{array}\right]=\left[\begin{array}{c} 1\ 0 \end{array}\right]$ Sea $A=\left[\begin{array}{cc} 1 & 1\ 1 & 0 \end{array}\right]$ <a name="eq3">.......eq3</a> entonces, si $u_{k}=A\mathbf{u}_{k-1}$ <a name="eq4">.......eq4</a> para $k=1,2,3...$ $u_{k}=\left[\begin{array}{c} F_{k+1}\ F_{k} \end{array}\right]$ $u_{k}=A^{k}\mathbf{u}_{0}$ <a name="eq5">.......eq5</a> Se usa la ecuación <a href="#eq4">eq4</a> para generar algunos $u$. $u_{0}=\left[\begin{array}{c} F_{1}\ F_{0} \end{array}\right]=\left[\begin{array}{c} 1\ 0 \end{array}\right]$ $u_{1}=\left[\begin{array}{cc} 1 & 1\ 1 & 0 \end{array}\right] \left[\begin{array}{c} 1\ 0 \end{array}\right]=\left[\begin{array}{c} 1\ 1 \end{array}\right]$ $u_{2}=\left[\begin{array}{cc} 1 & 1\ 1 & 0 \end{array}\right] \left[\begin{array}{c} 1\ 1 \end{array}\right]=\left[\begin{array}{c} 2\ 1 \end{array}\right]$ $u_{3}=\left[\begin{array}{cc} 1 & 1\ 1 & 0 \end{array}\right] \left[\begin{array}{c} 2\ 1 \end{array}\right]=\left[\begin{array}{c} 3\ 2 \end{array}\right]$ $u_{4}=\left[\begin{array}{cc} 1 & 1\ 1 & 0 \end{array}\right] \left[\begin{array}{c} 3\ 2 \end{array}\right]=\left[\begin{array}{c} 5\ 3 \end{array}\right]$ $u_{5}=\left[\begin{array}{cc} 1 & 1\ 1 & 0 \end{array}\right] \left[\begin{array}{c} 5\ 3 \end{array}\right]=\left[\begin{array}{c} 8\ 5 \end{array}\right]$ $u_{6}=\left[\begin{array}{cc} 1 & 1\ 1 & 0 \end{array}\right] \left[\begin{array}{c} 8\ 5 \end{array}\right]=\left[\begin{array}{c} 13\ 8 \end{array}\right]$ A continuación pongamos a prueba la <a href="#eq5">eq5</a>. End of explanation from math import sqrt # eigenvalores l1=(1+sqrt(5))/2.0 l2=(1-sqrt(5))/2.0 print("lambda1=%s, lambda2=%s" % (l1,l2)) # la matriz de transicion P P = np.matrix([[l1, l2], [1, 1]]) # valores como 1.66533454e-16 son como ceros! esto pasa por no hacerlo analiticamente (P**-1)*A*P Explanation: Polinomio característico Como $\lambda$ es un valor propio de $A$ $(\lambda I-A)\overrightarrow{X}=\overrightarrow{0}$ un eigenvector que sea su solución depende de que $\det(\lambda I-A)=\det\left(\left[\begin{array}{cc} \lambda & 0\ 0 & \lambda \end{array}\right]-\left[\begin{array}{cc} 1 & 1\ 1 & 0 \end{array}\right]\right)=\overrightarrow{0}$ Luego $\det\left(\left[\begin{array}{cc} \lambda-1 & -1\ -1 & \lambda \end{array}\right]\right)=(\lambda-1)\lambda-(-1)(-1)=\lambda^{2}-\lambda-1$ Valores propios Para obtener los valores propios usamos la fórmula general para encontrar valores de $\lambda$ que satisfagan el polinomio característico $p(\lambda)=\lambda^{2}-\lambda-1$ Acá la fórmula general: $x=\frac{-b\pm\sqrt{b^{2}-4ac}}{2a}$ $\lambda=\frac{1\pm\sqrt{-1^{2}-4(1)(-1)}}{2(1)}=\frac{1\pm\sqrt{1+4}}{2}$ Por eso $\begin{array}{c} \lambda_{1}=\frac{1+\sqrt{5}}{2}\ \lambda_{2}=\frac{1-\sqrt{5}}{2} \end{array}$ <a name="eq6">.......eq6</a> ## Vectores propios $\left[\begin{array}{cc} \lambda-1 & -1\ -1 & \lambda \end{array}\right]\overrightarrow{X}=\left[\begin{array}{cc} \lambda-1 & -1\ -1 & \lambda \end{array}\right]\left[\begin{array}{c}x_{1}\ x_{2}\end{array}\right]$ Equivale al sistema de ecuaciones $(\lambda-1)x_{1}-x_{2}=0$....(1) $-x_{1}+\lambda x_{2}=0$.....(2) Despejando $x_{1}$ en (2) $x_{1}=\lambda x_{2}$ que sustituyendo en (1) $(\lambda-1)\lambda x_{2}-x_{2}=0$ factorizamos $x_{2}$ $x_{2}\left[(\lambda-1)\lambda-1\right]=0$ sea $x_{2}=1$ en (2) $-x_{1}+\lambda=0$ $x_{1}=\lambda$ Por eso los vectores propios son $v_{1}=\left[\begin{array}{c} \lambda_{1}\ 1 \end{array}\right],\: v_{2}=\left[\begin{array}{c} \lambda_{2}\ 1 \end{array}\right]$ <a name="eq7">.......eq7</a> Matriz de transición P Con $v_{1}$ y $v_{2}$ formamos la matriz $P$. Para obtener la matriz invertida $P^{-1}$ Anton y Rorres muestran este teorema: Si $A=\left[\begin{array}{cc} a & b\ c & d \end{array}\right]$ entonces $A^{-1}=\frac{1}{ad-bc}\left[\begin{array}{cc} d & -b\ -c & a \end{array}\right]$ Teniendo la matriz $P=\left[\begin{array}{cc} \lambda_{1} & \lambda_{2}\ 1 & 1 \end{array}\right]$ entonces $P^{-1}=\frac{1}{\lambda_{1}-\lambda_{2}}\left[\begin{array}{cc} 1 & -\lambda_{2}\ -1 & \lambda_{1} \end{array}\right]$ Para comprobar $P^{-1}AP=\left[\begin{array}{cc} \lambda_{1} & 0\ 0 & \lambda_{2} \end{array}\right]=D$ basta con multiplicar las matrices $P^{-1}AP$. Como está laborioso hagámoslo con numpy en la siguiente celda. End of explanation def fibonacci(k): if k <= 1: return k else: return fibonacci(k-1) + fibonacci(k-2) # el indice empieza en cero for n in range(25): print("F%s=%s" % (n,fibonacci(n))) Explanation: En pos de la "fórmula cerrada" Si $A$ es diagonalizable entonces existe $P^{-1}AP=D$ Como $PP^{-1}=I$ es la matriz identidad, y es el neutro multiplicativo. $PP^{-1}APP^{-1}=PDP^{-1}$ luego $A=PDP^{-1}$ y entonces $A^{k}=\left(PDP^{-1}\right)^{k}$ ello significa que $PDP^{-1}$ se multiplica $k$ veces $A^{k}=\left(PDP^{-1}\right)\left(PDP^{-1}\right)\left(PDP^{-1}\right)...$ cambiando la agrupación de los paréntesis se tiene $A^{k}=PDDD...DP^{-1}$ lo cuál explica la siguiente ecuación: $A^{k}=PD^{k}P^{-1}$ <a name="eq8">.......eq8</a> Sustituyendo <a href="#eq8">eq8</a> en <a href="#eq4">eq4</a> tenemos que $\mathbf{u}{k}=(PD^{k}P^{-1})\mathbf{u}{0}$ no olvidar que $u_{0}=\left[\begin{array}{c} F_{1}\ F_{0} \end{array}\right]=\left[\begin{array}{c} 1\ 0 \end{array}\right]$ Luego se trata de otra larga multiplicación de matrices. $u_{k}=\left[\begin{array}{cc} \lambda_{1} & \lambda_{2}\ 1 & 1 \end{array}\right]\left[\begin{array}{cc} \lambda_{1}^{k} & 0\ 0 & \lambda_{2}^{k} \end{array}\right]\frac{1}{\lambda_{1}-\lambda_{2}}\left[\begin{array}{cc} 1 & -\lambda_{2}\ -1 & \lambda_{1} \end{array}\right]\left[\begin{array}{c} 1\ 0 \end{array}\right]$ $u_{k}=\left[\begin{array}{cc} \lambda_{1} & \lambda_{2}\ 1 & 1 \end{array}\right]\left[\begin{array}{cc} \lambda_{1}^{k} & 0\ 0 & \lambda_{2}^{k} \end{array}\right]\left[\begin{array}{c} 1\ -1 \end{array}\right]\frac{1}{\lambda_{1}-\lambda_{2}}$ $u_{k}=\left[\begin{array}{cc} \lambda_{1} & \lambda_{2}\ 1 & 1 \end{array}\right]\left[\begin{array}{c} \lambda_{1}^{k}\ -\lambda_{2}^{k} \end{array}\right]\frac{1}{\lambda_{1}-\lambda_{2}}$ y finalmente $\mathbf{u}{k}=(PD^{k}P^{-1})\mathbf{u}{0}=\frac{1}{\lambda_{1}-\lambda_{2}}\left[\begin{array}{c} \lambda_{1}^{k+1}-\lambda_{2}^{k+1}\ \lambda_{1}^{k}-\lambda_{2}^{k} \end{array}\right]$ También $u_{k}=\left[\begin{array}{c} F_{k+1}\ F_{k} \end{array}\right]$ entonces $F_{k}=\frac{1}{\lambda_{1}-\lambda_{2}}\left(\lambda_{1}^{k}-\lambda_{2}^{k}\right)$ Por otro lado $\frac{1}{\lambda_{1}-\lambda_{2}}=\frac{1}{\frac{1+\sqrt{5}}{2}-\frac{1-\sqrt{5}}{2}}=\frac{1}{\frac{(1+\sqrt{5})-(1-\sqrt{5})}{2}}=\frac{1}{\frac{1+\sqrt{5}-1+\sqrt{5})}{2}}=\frac{1}{\frac{2\sqrt{5}}{2}}=\frac{1}{\sqrt{5}}$ que si lo multiplicamos por $\left(\lambda_{1}^{k}-\lambda_{2}^{k}\right)$ equivale a la <a href="#eq2">eq2</a>: $F_{k}=\frac{1}{\sqrt{5}}\left[\left(\frac{1+\sqrt{5}}{2}\right)^{k}-\left(\frac{1-\sqrt{5}}{2}\right)^{k}\right]$ Implementación Recursiva End of explanation def lucas(k): if k == 0: return 1 elif k == 1: return 2 else: return lucas(k-1) + lucas(k-2) # el indice empieza en cero for n in range(25): print("F%s=%s" % (n,lucas(n))) Explanation: Sucesión de Lucas Esta serie es igual a la de Fibonacci pero empieza con $F_{0}=1$ y $F_{1}=2$. End of explanation # importamos bibliotecas para plotear import matplotlib import matplotlib.pyplot as plt # para desplegar los plots en el notebook %matplotlib inline p = [] for n in range(11): p.append([fibonacci(n), lucas(n)]) figura = plt.plot( p ) p Explanation: ¿Cómo se ven las series de Lucas y Fibonacci juntas? End of explanation def fibonacci_formula(k): return (1.0/sqrt(5))*(((1.0+sqrt(5))/2)**k-((1.0-sqrt(5))/2)**k) # el indice empieza en cero for n in range(25): print("F%i=%i" % (n,fibonacci_formula(n))) Explanation: Fibonacci con fórmula End of explanation import timeit # cronometro para implementacion recursiva tr = timeit.Timer(def fibonacci(k): if k <= 1: return k else: return fibonacci(k-1) + fibonacci(k-2) fibonacci(25)) # cronómetro para implementación con formula tf = timeit.Timer(from math import sqrt def fibonacci_formula(k): return (1.0/sqrt(5))*(((1.0+sqrt(5))/2)**k-((1.0-sqrt(5))/2)**k) fibonacci_formula(25)) # ejecutarlas diez mil veces, medir su tiempo tiempos=[tr.timeit(10000), tf.timeit(10000)] # armar gráfica de barras plt.bar([0,1], tiempos, align='center', alpha=0.5) plt.title('10,000 ejecuciones, k=25') plt.ylabel('milisegundos') plt.xticks([0,1],['recursivo', 'formula']) plt.show() tiempos Explanation: Dificultades algorítmicas A continuación se miden los tiempos de ejecución de ambas implementaciones de la sucesión de Fibonacci. Cada una se ejecuta diezmil veces y se reporta el tiempo promedio. End of explanation
7,303
Given the following text description, write Python code to implement the functionality described below step by step Description: Functions As in any other language Python allows for the definition of functions. Functions are a set of sequence of instructions that receive well define inputs and produce some outputs. To define a function Python uses the word def. The value that the function returns must be preceded by a return. The syntax would be Step1: Optional parameters Functions can have default parameters. These parameters are defined using the syntaxis arg=value, where arg is the argument name and value is the default value for that argument. Here are some examples
Python Code: def square(a): return a*a print(square(1), square(2), square(5)) square('a') # This should give an error def minimum(a, b): if a<b: return a elif b<a: return b else: return a minimum(4,5) minimum(4,0) Explanation: Functions As in any other language Python allows for the definition of functions. Functions are a set of sequence of instructions that receive well define inputs and produce some outputs. To define a function Python uses the word def. The value that the function returns must be preceded by a return. The syntax would be: python def FUNCTION_NAME(INPUTS): INSTRUCTIONS return OUTPUTS or python def FUNCTION_NAME(INPUTS): INSTRUCTIONS The return function is optional. Not every function should return an output. Some functions simply modify the inputs without producing any output. Important: The instructions and the return statements belonging to the fuction must be indented by 4 spaces inside the header. Indentation is the only way that Python has to group lines of code. Let's have some simple examples End of explanation def power(a, b=2): return a**b power(2) power(2, b=5) # This is the prefered way to change the default parameters power(2,5) # This works as well Explanation: Optional parameters Functions can have default parameters. These parameters are defined using the syntaxis arg=value, where arg is the argument name and value is the default value for that argument. Here are some examples End of explanation
7,304
Given the following text description, write Python code to implement the functionality described below step by step Description: Use different base estimators for optimization Sigurd Carlen, September 2019. Reformatted by Holger Nahrstaedt 2020 .. currentmodule Step1: Toy example Let assume the following noisy function $f$ Step2: GP kernel Step3: Test different kernels
Python Code: print(__doc__) import numpy as np np.random.seed(1234) import matplotlib.pyplot as plt Explanation: Use different base estimators for optimization Sigurd Carlen, September 2019. Reformatted by Holger Nahrstaedt 2020 .. currentmodule:: skopt To use different base_estimator or create a regressor with different parameters, we can create a regressor object and set it as kernel. End of explanation noise_level = 0.1 # Our 1D toy problem, this is the function we are trying to # minimize def objective(x, noise_level=noise_level): return np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2))\ + np.random.randn() * noise_level from skopt import Optimizer opt_gp = Optimizer([(-2.0, 2.0)], base_estimator="GP", n_initial_points=5, acq_optimizer="sampling", random_state=42) x = np.linspace(-2, 2, 400).reshape(-1, 1) fx = np.array([objective(x_i, noise_level=0.0) for x_i in x]) from skopt.acquisition import gaussian_ei def plot_optimizer(res, next_x, x, fx, n_iter, max_iters=5): x_gp = res.space.transform(x.tolist()) gp = res.models[-1] curr_x_iters = res.x_iters curr_func_vals = res.func_vals # Plot true function. ax = plt.subplot(max_iters, 2, 2 * n_iter + 1) plt.plot(x, fx, "r--", label="True (unknown)") plt.fill(np.concatenate([x, x[::-1]]), np.concatenate([fx - 1.9600 * noise_level, fx[::-1] + 1.9600 * noise_level]), alpha=.2, fc="r", ec="None") if n_iter < max_iters - 1: ax.get_xaxis().set_ticklabels([]) # Plot GP(x) + contours y_pred, sigma = gp.predict(x_gp, return_std=True) plt.plot(x, y_pred, "g--", label=r"$\mu_{GP}(x)$") plt.fill(np.concatenate([x, x[::-1]]), np.concatenate([y_pred - 1.9600 * sigma, (y_pred + 1.9600 * sigma)[::-1]]), alpha=.2, fc="g", ec="None") # Plot sampled points plt.plot(curr_x_iters, curr_func_vals, "r.", markersize=8, label="Observations") plt.title(r"x* = %.4f, f(x*) = %.4f" % (res.x[0], res.fun)) # Adjust plot layout plt.grid() if n_iter == 0: plt.legend(loc="best", prop={'size': 6}, numpoints=1) if n_iter != 4: plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off') # Plot EI(x) ax = plt.subplot(max_iters, 2, 2 * n_iter + 2) acq = gaussian_ei(x_gp, gp, y_opt=np.min(curr_func_vals)) plt.plot(x, acq, "b", label="EI(x)") plt.fill_between(x.ravel(), -2.0, acq.ravel(), alpha=0.3, color='blue') if n_iter < max_iters - 1: ax.get_xaxis().set_ticklabels([]) next_acq = gaussian_ei(res.space.transform([next_x]), gp, y_opt=np.min(curr_func_vals)) plt.plot(next_x, next_acq, "bo", markersize=6, label="Next query point") # Adjust plot layout plt.ylim(0, 0.07) plt.grid() if n_iter == 0: plt.legend(loc="best", prop={'size': 6}, numpoints=1) if n_iter != 4: plt.tick_params(axis='x', which='both', bottom='off', top='off', labelbottom='off') Explanation: Toy example Let assume the following noisy function $f$: End of explanation fig = plt.figure() fig.suptitle("Standard GP kernel") for i in range(10): next_x = opt_gp.ask() f_val = objective(next_x) res = opt_gp.tell(next_x, f_val) if i >= 5: plot_optimizer(res, opt_gp._next_x, x, fx, n_iter=i-5, max_iters=5) plt.tight_layout(rect=[0, 0.03, 1, 0.95]) plt.plot() Explanation: GP kernel End of explanation from skopt.learning import GaussianProcessRegressor from skopt.learning.gaussian_process.kernels import ConstantKernel, Matern # Gaussian process with Matérn kernel as surrogate model from sklearn.gaussian_process.kernels import (RBF, Matern, RationalQuadratic, ExpSineSquared, DotProduct, ConstantKernel) kernels = [1.0 * RBF(length_scale=1.0, length_scale_bounds=(1e-1, 10.0)), 1.0 * RationalQuadratic(length_scale=1.0, alpha=0.1), 1.0 * ExpSineSquared(length_scale=1.0, periodicity=3.0, length_scale_bounds=(0.1, 10.0), periodicity_bounds=(1.0, 10.0)), ConstantKernel(0.1, (0.01, 10.0)) * (DotProduct(sigma_0=1.0, sigma_0_bounds=(0.1, 10.0)) ** 2), 1.0 * Matern(length_scale=1.0, length_scale_bounds=(1e-1, 10.0), nu=2.5)] for kernel in kernels: gpr = GaussianProcessRegressor(kernel=kernel, alpha=noise_level ** 2, normalize_y=True, noise="gaussian", n_restarts_optimizer=2 ) opt = Optimizer([(-2.0, 2.0)], base_estimator=gpr, n_initial_points=5, acq_optimizer="sampling", random_state=42) fig = plt.figure() fig.suptitle(repr(kernel)) for i in range(10): next_x = opt.ask() f_val = objective(next_x) res = opt.tell(next_x, f_val) if i >= 5: plot_optimizer(res, opt._next_x, x, fx, n_iter=i - 5, max_iters=5) plt.tight_layout(rect=[0, 0.03, 1, 0.95]) plt.show() Explanation: Test different kernels End of explanation
7,305
Given the following text description, write Python code to implement the functionality described below step by step Description: 5. Model the Solution Preprocessing to get the tidy dataframe Step1: Question 3 Step2: PRINCIPLE Step3: PRINCIPLE Step4: PRINCIPLE Step5: Question 4 Step6: Now we can fit an ARIMA model on this (Explaining ARIMA is out of scope of this workshop)
Python Code: # Import the library we need, which is Pandas and Matplotlib import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Set some parameters to get good visuals - style to ggplot and size to 15,10 plt.style.use('ggplot') plt.rcParams['figure.figsize'] = (15, 10) # Read the csv file of Monthwise Quantity and Price csv file we have. df = pd.read_csv('MonthWiseMarketArrivals_clean.csv') # Changing the date column to a Time Interval columnn df.date = pd.DatetimeIndex(df.date) # Change the index to the date column df.index = pd.PeriodIndex(df.date, freq='M') # Sort the data frame by date df = df.sort_values(by = "date") df.head() Explanation: 5. Model the Solution Preprocessing to get the tidy dataframe End of explanation dfBang = df[df.city == 'BANGALORE'] dfBang.head() dfBang.plot(kind = "scatter", x = "quantity", y = "priceMod", s = 100) dfBang.plot(kind = "scatter", x = "quantity", y = "priceMod", s = 100, alpha = 0.7, xlim = [0,2000000]) Explanation: Question 3: How is Price and Quantity related for Onion in Bangalore? End of explanation dfBang.corr() pd.set_option('precision', 2) dfBang.corr() from pandas.tools.plotting import scatter_matrix scatter_matrix(dfBang, figsize=(15, 15), diagonal='kde', s = 50) Explanation: PRINCIPLE: Correlation Correlation refers to any of a broad class of statistical relationships involving dependence, though in common usage it most often refers to the extent to which two variables have a linear relationship with each other. End of explanation import statsmodels.api as sm x = dfBang.quantity y = dfBang.priceMod lm = sm.OLS(y, x).fit() lm.summary() Explanation: PRINCIPLE: Linear Regression End of explanation # Import seaborn library for more funcitionality import seaborn as sns # We can try and fit a linear line to the data to see if there is a relaltionship sns.regplot(x="quantity", y="priceMod", data=dfBang); sns.jointplot(x="quantity", y="priceMod", data=dfBang, kind="reg"); Explanation: PRINCIPLE: Visualizing linear relationships End of explanation # Set some parameters to get good visuals - style to ggplot and size to 15,10 plt.style.use('ggplot') plt.rcParams['figure.figsize'] = (15, 10) dfBang.index = pd.DatetimeIndex(dfBang.date) dfBang.head() # Let us create a time series variable for priceMin ts = dfBang.priceMin ts.plot() # We take the log transform to reduce the impact of high values ts_log = np.log(ts) ts_log.plot() # One approach to remove the trend and seasonality impact is to take the difference between each observation ts_log_diff = ts_log - ts_log.shift() ts_log_diff.plot() ts_log.plot() # For smoothing the values we can use # 12 month Moving Averages ts_log_diff_ma = pd.rolling_mean(ts_log_diff, window = 12) # Simple Exponential Smoothing ts_log_diff_exp = pd.ewma(ts_log_diff, halflife=24) ts_log_diff_ma.plot() ts_log_diff_exp.plot() ts_log_diff.plot() Explanation: Question 4: Can we forecast the price of Onion in Bangalore? TIme Series Modelling However, we have our data at constant time intervals of every month. Therefore we can analyze this data to determine the long term trend so as to forecast the future or perform some other form of analysis. Instead of using linear regression model where observations are independent, our observations are really time-dependent and we should use that. Second, we need to account for both a trend component and seasonality component in the time series data to better improve our forecast End of explanation from statsmodels.tsa.arima_model import ARIMA model = ARIMA(ts_log, order=(0, 1, 2)) results_MA = model.fit(disp=-1) plt.plot(ts_log_diff) plt.plot(results_MA.fittedvalues, color='blue') Explanation: Now we can fit an ARIMA model on this (Explaining ARIMA is out of scope of this workshop) End of explanation
7,306
Given the following text description, write Python code to implement the functionality described below step by step Description: Explore the uncertainity in the resistance of a sample circuit http Step1: For this simple circuit the questions are 1. what is the end-to-end resistance and its uncertainity? 1. What are the currents I1 and I2 and uncertaianity? For each we will assume also that the 12V is not perfect. We will try and answer these questions for the circuit as designed and also for the cuircuit as built with a few measurments of the resistors and see how that impacts the results. The results are Step2: Components Each component is assumed to be a normal distriubution of exptected value as listed and the 4, 6, 8 Ohm resistors are 1% while the 12 Ohm is a 5% resistor. Per http Step3: Explore and explain the results In the summary what is shown is the variable name ans summary information about each variable. We see that Step4: We also good visual diagnostics in terms of traceplots. The right side shows the draws, this should always look like hash, the left side is the Kernel Density Esimator of the output distribution. For this problem it should look pretty darn Normal. For both summary and traceplot, leavre off varnames to jst get them all... Step5: Now lets say that we made some measurments of R1 and we can use those to contrain things The model has to be a bit different to allow for the measurements. Also we will drop the bounded as while true it is kind of annoying to deal with, cannot observe things on a bounded distribution. Step6: Results So while not a huge difference a single measurment of R1 changed the results Step7: How about we buy a better R4? Buy a 1% not a 5% rerun first model with the better resistor (different Bayesian Prior)
Python Code: Image("res4.gif") Explanation: Explore the uncertainity in the resistance of a sample circuit http://www.electronics-tutorials.ws/resistor/res_5.html End of explanation import numpy as np import matplotlib.pyplot as plt import pymc3 as pm import pandas as pd import seaborn as sns sns.set() %matplotlib inline Explanation: For this simple circuit the questions are 1. what is the end-to-end resistance and its uncertainity? 1. What are the currents I1 and I2 and uncertaianity? For each we will assume also that the 12V is not perfect. We will try and answer these questions for the circuit as designed and also for the cuircuit as built with a few measurments of the resistors and see how that impacts the results. The results are: $R_{eff} = 6\Omega$ $I_T = 1A, I_1 = I_2 = 0.5A$ End of explanation ## setup the model # these are the values and precision of each Datasheets = {'R1':(6.0, 0.01), 'R2':(8.0, 0.01), 'R3':(4.0, 0.01), 'R4':(12.0, 0.05), 'V1':(6.0, 0.01),} # 1% on the 12V power supply with pm.Model() as model: BoundedNormal = pm.Bound(pm.Normal, lower=0.0) # http://docs.pymc.io/api/distributions/continuous.html#pymc3.distributions.continuous.Normal # in Bayes world these are considered prior distributions, they are based on previous information # that is gained in some other manner, from the datasheet in this case. R1 = BoundedNormal('R1', mu=Datasheets['R1'][0], sd=Datasheets['R1'][0]*Datasheets['R1'][1]) R2 = BoundedNormal('R2', mu=Datasheets['R2'][0], sd=Datasheets['R2'][0]*Datasheets['R2'][1]) R3 = BoundedNormal('R3', mu=Datasheets['R3'][0], sd=Datasheets['R3'][0]*Datasheets['R3'][1]) R4 = BoundedNormal('R4', mu=Datasheets['R4'][0], sd=Datasheets['R4'][0]*Datasheets['R4'][1]) # don't bound the voltage as negative is possilbe V1 = pm.Normal('V1', mu=Datasheets['V1'][0], sd=Datasheets['V1'][0]*Datasheets['V1'][1]) # Match should all be done on paper first to get the full answer, but we will do steps here because one can. # all at once would be much faster. # just add them, we will not get info on R2_3 at the output unless we wrap them in pm.Deterministic R2_3 = R2+R3 # R2_3 = pm.Deterministic('R2_3', R2+R3) # now get the resistance answer, and we want details R_eff = pm.Deterministic('R_eff', 1/(1/R2_3 + 1/R4)) # total current is then just I=V/R I_t = pm.Deterministic('I_t', V1/R_eff) # and I_1 and I_2 I_1 = pm.Deterministic('I_1', I_t*R2_3/R4) I_2 = pm.Deterministic('I_2', I_t-I_1) # makes it all a bit clearner to start in a good place start = pm.find_MAP() # run a fair number of samples, I have a 8 core machine so run 6 trace = pm.sample(5000, start=start, njobs=6) Explanation: Components Each component is assumed to be a normal distriubution of exptected value as listed and the 4, 6, 8 Ohm resistors are 1% while the 12 Ohm is a 5% resistor. Per http://docs.pymc.io/api/bounds.html we will use bounded variables because resistances that are negative are nonsensical. End of explanation I_t_perc = np.percentile(trace['I_t'], (2.5, 97.5)) I_t_mean = trace['I_t'].mean() print('I_t = {:.4} +/- {:.4}'.format(I_t_mean, I_t_perc[1]-I_t_mean)) print('I_t = {:.4} +/- {:.4}%'.format(I_t_mean, (I_t_perc[1]-I_t_mean)/I_t_mean*100)) pm.summary(trace, varnames=('R_eff', 'I_t', 'I_1', 'I_2')) Explanation: Explore and explain the results In the summary what is shown is the variable name ans summary information about each variable. We see that: $R_{eff} = 5.997 \pm 0.3$, really $R_{eff}$ is between $[5.705, 6.302]$ or $6\Omega \pm 5\%$ $I_t = 1.001 \pm 0.113$, $[0.892, 1.113]$ or $1.001 \pm 11\%$ So if one is going for a 5% accuracy on the current you cannot say that! End of explanation pm.traceplot(trace, combined=True, varnames=('R_eff', 'I_t')); Explanation: We also good visual diagnostics in terms of traceplots. The right side shows the draws, this should always look like hash, the left side is the Kernel Density Esimator of the output distribution. For this problem it should look pretty darn Normal. For both summary and traceplot, leavre off varnames to jst get them all... End of explanation # setup the model # these are the values and precision of each Datasheets = {'R1':(6.0, 0.01), 'R2':(8.0, 0.01), 'R3':(4.0, 0.01), 'R4':(12.0, 0.05), 'V1':(6.0, 0.05),} # 5% on the 12V power supply measuremnts_R1 = [5.987, 5.987] # we measured it twice with pm.Model() as model: # http://docs.pymc.io/api/distributions/continuous.html#pymc3.distributions.continuous.Normal # in Bayes world these are considered prior distributions, they are based on previous information # that is gained in some other manner, from the datasheet in this case. # R1 = pm.Normal('R1', mu=Datasheets['R1'][0], sd=Datasheets['R1'][0]*Datasheets['R1'][1]) R2 = pm.Normal('R2', mu=Datasheets['R2'][0], sd=Datasheets['R2'][0]*Datasheets['R2'][1]) R3 = pm.Normal('R3', mu=Datasheets['R3'][0], sd=Datasheets['R3'][0]*Datasheets['R3'][1]) R4 = pm.Normal('R4', mu=Datasheets['R4'][0], sd=Datasheets['R4'][0]*Datasheets['R4'][1]) # don't bound the voltage as negative is possilbe V1 = pm.Normal('V1', mu=Datasheets['V1'][0], sd=Datasheets['V1'][0]*Datasheets['V1'][1]) # so on R1 we took some measurments and so have to build it a bit differently # use the datasheet for prior R1_mean = pm.Normal('R1_mean', mu=Datasheets['R1'][0], sd=Datasheets['R1'][0]*Datasheets['R1'][1]) R1 = pm.Normal('R1', mu=R1_mean, sd=Datasheets['R1'][0]*Datasheets['R1'][1], observed=measuremnts_R1) # Match should all be done on paper first to get the full answer, but we will do steps here because one can. # all at once would be much faster. # just add them, we will not get info on R2_3 at the output unless we wrap them in pm.Deterministic R2_3 = R2+R3 # R2_3 = pm.Deterministic('R2_3', R2+R3) # now get the resistance answer, and we want details R_eff = pm.Deterministic('R_eff', 1/(1/R2_3 + 1/R4)) # total current is then just I=V/R I_t = pm.Deterministic('I_t', V1/R_eff) # and I_1 and I_2 I_1 = pm.Deterministic('I_1', I_t*R2_3/R4) I_2 = pm.Deterministic('I_2', I_t-I_1) # makes it all a bit clearner to start in a good place start = pm.find_MAP() # run a fair number of samples, I have a 8 core machine so run 6 trace = pm.sample(5000, start=start, njobs=6) pm.summary(trace, varnames=('R_eff', 'I_t', 'I_1', 'I_2')) pm.traceplot(trace, combined=True, varnames=('R_eff', 'I_t')); Explanation: Now lets say that we made some measurments of R1 and we can use those to contrain things The model has to be a bit different to allow for the measurements. Also we will drop the bounded as while true it is kind of annoying to deal with, cannot observe things on a bounded distribution. End of explanation I_t_perc = np.percentile(trace['I_t'], (2.5, 97.5)) I_t_mean = trace['I_t'].mean() print('I_t = {:.4} +/- {:.4}'.format(I_t_mean, I_t_perc[1]-I_t_mean)) print('I_t = {:.4} +/- {:.4}%'.format(I_t_mean, (I_t_perc[1]-I_t_mean)/I_t_mean*100)) Explanation: Results So while not a huge difference a single measurment of R1 changed the results: $R_{eff} = [5.705, 6.302]$ became $R_{eff} = [5.688, 6.282]$ $I_t = [0.892, 1.113]$ became $I_t = [0.891, 1.110]$ A not huge difference but a shift down. End of explanation # setup the model # these are the values and precision of each Datasheets = {'R1':(6.0, 0.01), 'R2':(8.0, 0.01), 'R3':(4.0, 0.01), 'R4':(12.0, 0.01), # better resistor 'V1':(6.0, 0.05),} # 5% on the 12V power supply with pm.Model() as model: BoundedNormal = pm.Bound(pm.Normal, lower=0.0) # http://docs.pymc.io/api/distributions/continuous.html#pymc3.distributions.continuous.Normal # in Bayes world these are considered prior distributions, they are based on previous information # that is gained in some other manner, from the datasheet in this case. R1 = BoundedNormal('R1', mu=Datasheets['R1'][0], sd=Datasheets['R1'][0]*Datasheets['R1'][1]) R2 = BoundedNormal('R2', mu=Datasheets['R2'][0], sd=Datasheets['R2'][0]*Datasheets['R2'][1]) R3 = BoundedNormal('R3', mu=Datasheets['R3'][0], sd=Datasheets['R3'][0]*Datasheets['R3'][1]) R4 = BoundedNormal('R4', mu=Datasheets['R4'][0], sd=Datasheets['R4'][0]*Datasheets['R4'][1]) # don't bound the voltage as negative is possilbe V1 = pm.Normal('V1', mu=Datasheets['V1'][0], sd=Datasheets['V1'][0]*Datasheets['V1'][1]) # Match should all be done on paper first to get the full answer, but we will do steps here because one can. # all at once would be much faster. # just add them, we will not get info on R2_3 at the output unless we wrap them in pm.Deterministic R2_3 = R2+R3 # R2_3 = pm.Deterministic('R2_3', R2+R3) # now get the resistance answer, and we want details R_eff = pm.Deterministic('R_eff', 1/(1/R2_3 + 1/R4)) # total current is then just I=V/R I_t = pm.Deterministic('I_t', V1/R_eff) # and I_1 and I_2 I_1 = pm.Deterministic('I_1', I_t*R2_3/R4) I_2 = pm.Deterministic('I_2', I_t-I_1) # makes it all a bit clearner to start in a good place start = pm.find_MAP() # run a fair number of samples, I have a 8 core machine so run 6 trace = pm.sample(5000, start=start, njobs=6) I_t_perc = np.percentile(trace['I_t'], (2.5, 97.5)) I_t_mean = trace['I_t'].mean() print('I_t = {:.4} +/- {:.4}'.format(I_t_mean, I_t_perc[1]-I_t_mean)) print('I_t = {:.4} +/- {:.4}%'.format(I_t_mean, (I_t_perc[1]-I_t_mean)/I_t_mean*100)) Explanation: How about we buy a better R4? Buy a 1% not a 5% rerun first model with the better resistor (different Bayesian Prior) End of explanation
7,307
Given the following text description, write Python code to implement the functionality described below step by step Description: LAB 3a Step1: Verify tables exist Run the following cells to verify that we previously created the dataset and data tables. If not, go back to lab 1b_prepare_data_babyweight to create them. Step2: Create the baseline model Next, we'll create a linear regression baseline model with no feature engineering. We'll use this to compare our later, more complex models against. Lab Task #1 Step3: REMINDER Step4: Lab Task #2 Step5: Resource for an explanation of the Regression Metrics. Lab Task #3
Python Code: %%bash sudo pip freeze | grep google-cloud-bigquery==1.6.1 || \ sudo pip install google-cloud-bigquery==1.6.1 Explanation: LAB 3a: BigQuery ML Model Baseline. Learning Objectives Create baseline model with BQML Evaluate baseline model Calculate RMSE of baseline model Introduction In this notebook, we will create a baseline model to predict the weight of a baby before it is born. We will use BigQuery ML to build a linear babyweight prediction model with the base features and no feature engineering, yet. We will create a baseline model with BQML, evaluate our baseline model, and calculate the its RMSE. Each learning objective will correspond to a #TODO in this student lab notebook -- try to complete this notebook first and then review the solution notebook. Load necessary libraries Check that the Google BigQuery library is installed and if not, install it. End of explanation %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_data_train LIMIT 0 %%bigquery -- LIMIT 0 is a free query; this allows us to check that the table exists. SELECT * FROM babyweight.babyweight_data_eval LIMIT 0 Explanation: Verify tables exist Run the following cells to verify that we previously created the dataset and data tables. If not, go back to lab 1b_prepare_data_babyweight to create them. End of explanation %%bigquery CREATE OR REPLACE MODEL babyweight.baseline_model OPTIONS ( MODEL_TYPE=# TODO: Add model type, INPUT_LABEL_COLS=[# TODO: label column name], DATA_SPLIT_METHOD="NO_SPLIT") AS SELECT # TODO: Add features and label FROM # TODO: Add train table Explanation: Create the baseline model Next, we'll create a linear regression baseline model with no feature engineering. We'll use this to compare our later, more complex models against. Lab Task #1: Train the "Baseline Model". When creating a BQML model, you must specify the model type (in our case linear regression) and the input label (weight_pounds). Note also that we are using the training data table as the data source and we don't need BQML to split the data because we have already split it ourselves. End of explanation %%bigquery -- Information from model training SELECT * FROM ML.TRAINING_INFO(MODEL babyweight.baseline_model) Explanation: REMINDER: The query takes several minutes to complete. After the first iteration is complete, your model (baseline_model) appears in the navigation panel of the BigQuery web UI. Because the query uses a CREATE MODEL statement to create a model, you do not see query results. You can observe the model as it's being trained by viewing the Model stats tab in the BigQuery web UI. As soon as the first iteration completes, the tab is updated. The stats continue to update as each iteration completes. Once the training is done, visit the BigQuery Cloud Console and look at the model that has been trained. Then, come back to this notebook. Evaluate the baseline model Even though BigQuery can automatically split the data it is given, and training on only a part of the data and using the rest for evaluation, to compare with our custom models later we wanted to decide the split ourselves so that it is completely reproducible. NOTE: The results are also displayed in the BigQuery Cloud Console under the Evaluation tab. End of explanation %%bigquery SELECT * FROM ML.EVALUATE(MODEL # TODO: Add model name, ( SELECT # TODO: Add features and label FROM # TODO: Add eval table )) Explanation: Lab Task #2: Get evaluation statistics for the baseline model. After creating your model, you evaluate the performance of the regressor using the ML.EVALUATE function. The ML.EVALUATE function evaluates the predicted values against the actual data. End of explanation %%bigquery SELECT # TODO: Select just the calculated RMSE FROM ML.EVALUATE(MODEL # TODO: Add model name, ( SELECT # TODO: Add features and label FROM # TODO: Add eval table )) Explanation: Resource for an explanation of the Regression Metrics. Lab Task #3: Write a SQL query to find the RMSE of the evaluation data Since this is regression, we typically use the RMSE, but natively this is not in the output of our evaluation metrics above. However, we can simply take the SQRT() of the mean squared error of our loss metric from evaluation of the baseline_model to get RMSE. End of explanation
7,308
Given the following text description, write Python code to implement the functionality described below step by step Description: Finding data story Goals Find a data story Narrow down fields of dataset to explore Imports and helper functions Step3: Current visualization ideas Show map and as user searches highlight or unhighlight dots in map Good with categorical but not continuous data private or public bin certain continuous distributions student body size Time series of different schools to show change over time Could allow people to pin certain schools By default would show the top 5, 10?, 15? schools Could show seperation between top and bottom Could show mean of the dataset at the same time Animated dot plot that shows change over time with animation Sort of double encoding that was in the IPO vis from NYTimes Currently seems like time series is the best option. Start with that and expand. Features to add or explore? Step6: Odd outliers throughout needs to be explored and cleaned more
Python Code: %matplotlib inline import matplotlib.pyplot as plt import sqlite3 import pandas as pd import seaborn as sns sns.set_style("white") conn = sqlite3.connect('../data/output/database.sqlite') c = conn.cursor() def execute(sql): ''' Executes a SQL command on the 'c' cursor and returns the results ''' c.execute(sql) return c.fetchall() def printByYear(data): ''' Given a list of tuples with (year, data), prints the data next to corresponding year ''' for datum in data: print "{0}: {1}".format(datum[0], datum[1]) years = {1996:1.46, 1997:1.43, 1998:1.4, 1999:1.38, 2000:1.33, 2001:1.3, 2002:1.28, 2003:1.25, 2004:1.22, 2005:1.18, 2006:1.14, 2007:1.11, 2008:1.07, 2009:1.07, 2010:1.05, 2011:1.02, 2012:1} def adjustForInflation(value, year): if value == None: return return value * years[year] Explanation: Finding data story Goals Find a data story Narrow down fields of dataset to explore Imports and helper functions End of explanation # Median loan debt of those who graduate programs debt = execute(SELECT year, grad_debt_mdn FROM Scorecard WHERE year%2=0 AND grad_debt_mdn IS NOT NULL) def graphDistForYears(data, year1, year2): data1 = pd.DataFrame() data2 = pd.DataFrame() # 1.4 is adjusting for inflation data1['x'] = [1.4 * row[1] for row in data if row[0]==year1 and (isinstance(row[1], float) or isinstance(row[1], int))] data2['x'] = [row[1] for row in data if row[0]==year2 and (isinstance(row[1], float) or isinstance(row[1], int))] sns.distplot(data1, kde=False) sns.distplot(data2, kde=False) # Years with meadian student debt from sets import Set years = Set() for row in debt: years.add(row[0]) print years graphDistForYears(debt, 1998, 2012) # Graph makes it look like there mgith be anomalies in the data such as negative debt, but # this is just a quirk of the regression and not an actual fact print len([row[1] for row in debt if isinstance(row[1], float) and row[1] < 0]) # Net tuition revenue per student for a institution tuitionRev = execute(SELECT year, tuitfte, instnm, ugds FROM Scorecard WHERE tuitfte IS NOT NULL and main='Main campus' and ugds>1000) graphDistForYears(tuitionRev, 1998, 2012) top10 = [[0,0,0] for i in range(0, 10)] for inst in [row for row in tuitionRev if row[0]==1998]: i = 0 done = False while i < len(top10) and not done: if (top10[i][1] < inst[1]): top10[i][0] = inst[2] top10[i][1] = inst[1] top10[i][2] = inst[3] done = True i += 1 for top in top10: print "{0} -- {1} -- {2}".format(top[0], top[1], top[2]) Explanation: Current visualization ideas Show map and as user searches highlight or unhighlight dots in map Good with categorical but not continuous data private or public bin certain continuous distributions student body size Time series of different schools to show change over time Could allow people to pin certain schools By default would show the top 5, 10?, 15? schools Could show seperation between top and bottom Could show mean of the dataset at the same time Animated dot plot that shows change over time with animation Sort of double encoding that was in the IPO vis from NYTimes Currently seems like time series is the best option. Start with that and expand. Features to add or explore?: * Money (adjust for inflation) * Institutional finances * Net tuition * Institutional expenses * Average faculty salary * Costs for students * Tuition and fees * Average net price * Cumulative median debt * Percent receiving federal loans * Admissions * Admission rate * SAT and ACT * Student outcome * Completion rate * Mean and median * Threshold earnings for private for-profit * Student body demographics * Breakdown by major * Ethnicity Explored Below: cumulative median debt net tuition expenses End of explanation expenses = execute(SELECT year, inexpfte FROM Scorecard WHERE inexpfte IS NOT NULL and main='Main campus' and ugds>1000) graphDistForYears(expenses, 1998, 2012) purdueData = execute(SELECT year, tuitfte, inexpfte, grad_debt_mdn FROM Scorecard WHERE instnm='PURDUE UNIVERSITY-MAIN CAMPUS') purdueData[:10] def graphPurdueData(index): df = pd.DataFrame() df['Dollars'] = [adjustForInflation(row[index], row[0]) for row in purdueData] df['Year'] = [row[0] for row in purdueData] graph = sns.regplot('Year', 'Dollars', data=df, fit_reg=False) graphPurdueData(1) graphPurdueData(2) graphPurdueData(3) Explanation: Odd outliers throughout needs to be explored and cleaned more End of explanation
7,309
Given the following text description, write Python code to implement the functionality described below step by step Description: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural language processing. This will come in handy when dealing with things like translations. Readings Here are the resources I used to build this notebook. I suggest reading these either beforehand or while you're working on this material. A really good conceptual overview of word2vec from Chris McCormick First word2vec paper from Mikolov et al. NIPS paper with improvements for word2vec also from Mikolov et al. An implementation of word2vec from Thushan Ganegedara TensorFlow word2vec tutorial Word embeddings When you're dealing with language and words, you end up with tens of thousands of classes to predict, one for each word. Trying to one-hot encode these words is massively inefficient, you'll have one element set to 1 and the other 50,000 set to 0. The word2vec algorithm finds much more efficient representations by finding vectors that represent the words. These vectors also contain semantic information about the words. Words that show up in similar contexts, such as "black", "white", and "red" will have vectors near each other. There are two architectures for implementing word2vec, CBOW (Continuous Bag-Of-Words) and Skip-gram. <img src="assets/word2vec_architectures.png" width="500"> In this implementation, we'll be using the skip-gram architecture because it performs better than CBOW. Here, we pass in a word and try to predict the words surrounding it in the text. In this way, we can train the network to learn representations for words that show up in similar contexts. First up, importing packages. Step1: Load the text8 dataset, a file of cleaned up Wikipedia articles from Matt Mahoney. The next cell will download the data set to the data folder. Then you can extract it and delete the archive file to save storage space. Step2: Preprocessing Here I'm fixing up the text to make training easier. This comes from the utils module I wrote. The preprocess function coverts any punctuation into tokens, so a period is changed to &lt;PERIOD&gt;. In this data set, there aren't any periods, but it will help in other NLP problems. I'm also removing all words that show up five or fewer times in the dataset. This will greatly reduce issues due to noise in the data and improve the quality of the vector representations. If you want to write your own functions for this stuff, go for it. Step3: And here I'm creating dictionaries to covert words to integers and backwards, integers to words. The integers are assigned in descending frequency order, so the most frequent word ("the") is given the integer 0 and the next most frequent is 1 and so on. The words are converted to integers and stored in the list int_words. Step4: Subsampling Words that show up often such as "the", "of", and "for" don't provide much context to the nearby words. If we discard some of them, we can remove some of the noise from our data and in return get faster training and better representations. This process is called subsampling by Mikolov. For each word $w_i$ in the training set, we'll discard it with probability given by $$ P(w_i) = 1 - \sqrt{\frac{t}{f(w_i)}} $$ where $t$ is a threshold parameter and $f(w_i)$ is the frequency of word $w_i$ in the total dataset. I'm going to leave this up to you as an exercise. This is more of a programming challenge, than about deep learning specifically. But, being able to prepare your data for your network is an important skill to have. Check out my solution to see how I did it. Exercise Step5: Making batches Now that our data is in good shape, we need to get it into the proper form to pass it into our network. With the skip-gram architecture, for each word in the text, we want to grab all the words in a window around that word, with size $C$. From Mikolov et al. Step6: Here's a function that returns batches for our network. The idea is that it grabs batch_size words from a words list. Then for each of those words, it gets the target words in the window. I haven't found a way to pass in a random number of target words and get it to work with the architecture, so I make one row per input-target pair. This is a generator function by the way, helps save memory. Step7: Building the graph From Chris McCormick's blog, we can see the general structure of our network. The input words are passed in as one-hot encoded vectors. This will go into a hidden layer of linear units, then into a softmax layer. We'll use the softmax layer to make a prediction like normal. The idea here is to train the hidden layer weight matrix to find efficient representations for our words. This weight matrix is usually called the embedding matrix or embedding look-up table. We can discard the softmax layer becuase we don't really care about making predictions with this network. We just want the embedding matrix so we can use it in other networks we build from the dataset. I'm going to have you build the graph in stages now. First off, creating the inputs and labels placeholders like normal. Exercise Step8: Embedding The embedding matrix has a size of the number of words by the number of neurons in the hidden layer. So, if you have 10,000 words and 300 hidden units, the matrix will have size $10,000 \times 300$. Remember that we're using one-hot encoded vectors for our inputs. When you do the matrix multiplication of the one-hot vector with the embedding matrix, you end up selecting only one row out of the entire matrix Step9: Negative sampling For every example we give the network, we train it using the output from the softmax layer. That means for each input, we're making very small changes to millions of weights even though we only have one true example. This makes training the network very inefficient. We can approximate the loss from the softmax layer by only updating a small subset of all the weights at once. We'll update the weights for the correct label, but only a small number of incorrect labels. This is called "negative sampling". Tensorflow has a convenient function to do this, tf.nn.sampled_softmax_loss. Exercise Step10: Validation This code is from Thushan Ganegedara's implementation. Here we're going to choose a few common words and few uncommon words. Then, we'll print out the closest words to them. It's a nice way to check that our embedding table is grouping together words with similar semantic meanings. Step11: Training Below is the code to train the network. Every 100 batches it reports the training loss. Every 1000 batches, it'll print out the validation words. Step12: Restore the trained network if you need to Step13: Visualizing the word vectors Below we'll use T-SNE to visualize how our high-dimensional word vectors cluster together. T-SNE is used to project these vectors into two dimensions while preserving local stucture. Check out this post from Christopher Olah to learn more about T-SNE and other ways to visualize high-dimensional data.
Python Code: !pip install tqdm import time import numpy as np import tensorflow as tf import utils Explanation: Skip-gram word2vec In this notebook, I'll lead you through using TensorFlow to implement the word2vec algorithm using the skip-gram architecture. By implementing this, you'll learn about embedding words for use in natural language processing. This will come in handy when dealing with things like translations. Readings Here are the resources I used to build this notebook. I suggest reading these either beforehand or while you're working on this material. A really good conceptual overview of word2vec from Chris McCormick First word2vec paper from Mikolov et al. NIPS paper with improvements for word2vec also from Mikolov et al. An implementation of word2vec from Thushan Ganegedara TensorFlow word2vec tutorial Word embeddings When you're dealing with language and words, you end up with tens of thousands of classes to predict, one for each word. Trying to one-hot encode these words is massively inefficient, you'll have one element set to 1 and the other 50,000 set to 0. The word2vec algorithm finds much more efficient representations by finding vectors that represent the words. These vectors also contain semantic information about the words. Words that show up in similar contexts, such as "black", "white", and "red" will have vectors near each other. There are two architectures for implementing word2vec, CBOW (Continuous Bag-Of-Words) and Skip-gram. <img src="assets/word2vec_architectures.png" width="500"> In this implementation, we'll be using the skip-gram architecture because it performs better than CBOW. Here, we pass in a word and try to predict the words surrounding it in the text. In this way, we can train the network to learn representations for words that show up in similar contexts. First up, importing packages. End of explanation from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm import zipfile dataset_folder_path = 'data' dataset_filename = 'text8.zip' dataset_name = 'Text8 Dataset' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile(dataset_filename): with DLProgress(unit='B', unit_scale=True, miniters=1, desc=dataset_name) as pbar: urlretrieve( 'http://mattmahoney.net/dc/text8.zip', dataset_filename, pbar.hook) if not isdir(dataset_folder_path): with zipfile.ZipFile(dataset_filename) as zip_ref: zip_ref.extractall(dataset_folder_path) with open('data/text8') as f: text = f.read() Explanation: Load the text8 dataset, a file of cleaned up Wikipedia articles from Matt Mahoney. The next cell will download the data set to the data folder. Then you can extract it and delete the archive file to save storage space. End of explanation words = utils.preprocess(text) print(words[:30]) print("Total words: {}".format(len(words))) print("Unique words: {}".format(len(set(words)))) Explanation: Preprocessing Here I'm fixing up the text to make training easier. This comes from the utils module I wrote. The preprocess function coverts any punctuation into tokens, so a period is changed to &lt;PERIOD&gt;. In this data set, there aren't any periods, but it will help in other NLP problems. I'm also removing all words that show up five or fewer times in the dataset. This will greatly reduce issues due to noise in the data and improve the quality of the vector representations. If you want to write your own functions for this stuff, go for it. End of explanation vocab_to_int, int_to_vocab = utils.create_lookup_tables(words) int_words = [vocab_to_int[word] for word in words] print(int_words[:20]) Explanation: And here I'm creating dictionaries to covert words to integers and backwards, integers to words. The integers are assigned in descending frequency order, so the most frequent word ("the") is given the integer 0 and the next most frequent is 1 and so on. The words are converted to integers and stored in the list int_words. End of explanation ## Your code here import random as r from collections import Counter words_counter = Counter(int_words) total_count = len(int_words) #print(words_counter.most_common(30)) threshold = 1e-5 freq = {word: count/total_count for word, count in words_counter.items()} p_drop = {word: 1 - np.sqrt(threshold/freq[word]) for word in words_counter} #Add the samples, with P(w) less than 0.5, to the subsampled word list train_words = [word for word in int_words if p_drop[word] < r.random()] print('The Original no. of words: {}'.format(len(int_words))) print('The final no. of words after subsampling: {}'.format(len(train_words))) Explanation: Subsampling Words that show up often such as "the", "of", and "for" don't provide much context to the nearby words. If we discard some of them, we can remove some of the noise from our data and in return get faster training and better representations. This process is called subsampling by Mikolov. For each word $w_i$ in the training set, we'll discard it with probability given by $$ P(w_i) = 1 - \sqrt{\frac{t}{f(w_i)}} $$ where $t$ is a threshold parameter and $f(w_i)$ is the frequency of word $w_i$ in the total dataset. I'm going to leave this up to you as an exercise. This is more of a programming challenge, than about deep learning specifically. But, being able to prepare your data for your network is an important skill to have. Check out my solution to see how I did it. Exercise: Implement subsampling for the words in int_words. That is, go through int_words and discard each word given the probablility $P(w_i)$ shown above. Note that $P(w_i)$ is the probability that a word is discarded. Assign the subsampled data to train_words. End of explanation def get_target(words, idx, window_size=5): ''' Get a list of words in a window around an index. ''' # Your code here R = np.random.randint(1, window_size+1) #print(R) start = idx-R if idx-R > 0 else 0 stop = idx+R target = set(words[start:idx]+words[idx+1:stop+1]) return list(target) #print(get_target(['help','today','great','health','work','now','tea'], 2)) Explanation: Making batches Now that our data is in good shape, we need to get it into the proper form to pass it into our network. With the skip-gram architecture, for each word in the text, we want to grab all the words in a window around that word, with size $C$. From Mikolov et al.: "Since the more distant words are usually less related to the current word than those close to it, we give less weight to the distant words by sampling less from those words in our training examples... If we choose $C = 5$, for each training word we will select randomly a number $R$ in range $< 1; C >$, and then use $R$ words from history and $R$ words from the future of the current word as correct labels." Exercise: Implement a function get_target that receives a list of words, an index, and a window size, then returns a list of words in the window around the index. Make sure to use the algorithm described above, where you choose a random number of words from the window. End of explanation def get_batches(words, batch_size, window_size=5): ''' Create a generator of word batches as a tuple (inputs, targets) ''' n_batches = len(words)//batch_size # only full batches words = words[:n_batches*batch_size] for idx in range(0, len(words), batch_size): x, y = [], [] batch = words[idx:idx+batch_size] for ii in range(len(batch)): batch_x = batch[ii] batch_y = get_target(batch, ii, window_size) y.extend(batch_y) x.extend([batch_x]*len(batch_y)) yield x, y Explanation: Here's a function that returns batches for our network. The idea is that it grabs batch_size words from a words list. Then for each of those words, it gets the target words in the window. I haven't found a way to pass in a random number of target words and get it to work with the architecture, so I make one row per input-target pair. This is a generator function by the way, helps save memory. End of explanation train_graph = tf.Graph() with train_graph.as_default(): inputs = tf.placeholder(tf.int32, None) labels = tf.placeholder(tf.int32, None) Explanation: Building the graph From Chris McCormick's blog, we can see the general structure of our network. The input words are passed in as one-hot encoded vectors. This will go into a hidden layer of linear units, then into a softmax layer. We'll use the softmax layer to make a prediction like normal. The idea here is to train the hidden layer weight matrix to find efficient representations for our words. This weight matrix is usually called the embedding matrix or embedding look-up table. We can discard the softmax layer becuase we don't really care about making predictions with this network. We just want the embedding matrix so we can use it in other networks we build from the dataset. I'm going to have you build the graph in stages now. First off, creating the inputs and labels placeholders like normal. Exercise: Assign inputs and labels using tf.placeholder. We're going to be passing in integers, so set the data types to tf.int32. The batches we're passing in will have varying sizes, so set the batch sizes to [None]. To make things work later, you'll need to set the second dimension of labels to None or 1. End of explanation n_vocab = len(int_to_vocab) n_embedding = 200 # Number of embedding features with train_graph.as_default(): embedding = tf.Variable(tf.random_uniform((n_vocab, n_embedding), -1.0, 1.0)) # create embedding weight matrix here embed = tf.nn.embedding_lookup(embedding, inputs)# use tf.nn.embedding_lookup to get the hidden layer output Explanation: Embedding The embedding matrix has a size of the number of words by the number of neurons in the hidden layer. So, if you have 10,000 words and 300 hidden units, the matrix will have size $10,000 \times 300$. Remember that we're using one-hot encoded vectors for our inputs. When you do the matrix multiplication of the one-hot vector with the embedding matrix, you end up selecting only one row out of the entire matrix: You don't actually need to do the matrix multiplication, you just need to select the row in the embedding matrix that corresponds to the input word. Then, the embedding matrix becomes a lookup table, you're looking up a vector the size of the hidden layer that represents the input word. <img src="assets/word2vec_weight_matrix_lookup_table.png" width=500> Exercise: Tensorflow provides a convenient function tf.nn.embedding_lookup that does this lookup for us. You pass in the embedding matrix and a tensor of integers, then it returns rows in the matrix corresponding to those integers. Below, set the number of embedding features you'll use (200 is a good start), create the embedding matrix variable, and use tf.nn.embedding_lookup to get the embedding tensors. For the embedding matrix, I suggest you initialize it with a uniform random numbers between -1 and 1 using tf.random_uniform. This TensorFlow tutorial will help if you get stuck. End of explanation # Number of negative labels to sample n_sampled = 100 with train_graph.as_default(): softmax_w = tf.Variable(tf.truncated_normal((n_vocab, n_embedding), stddev=1.0))# create softmax weight matrix here softmax_b = tf.Variable(tf.zeros(n_vocab))# create softmax biases here # Calculate the loss using negative sampling loss = tf.nn.sampled_softmax_loss(softmax_w, softmax_b, labels, embed, n_sampled, n_vocab) cost = tf.reduce_mean(loss) optimizer = tf.train.AdamOptimizer().minimize(cost) Explanation: Negative sampling For every example we give the network, we train it using the output from the softmax layer. That means for each input, we're making very small changes to millions of weights even though we only have one true example. This makes training the network very inefficient. We can approximate the loss from the softmax layer by only updating a small subset of all the weights at once. We'll update the weights for the correct label, but only a small number of incorrect labels. This is called "negative sampling". Tensorflow has a convenient function to do this, tf.nn.sampled_softmax_loss. Exercise: Below, create weights and biases for the softmax layer. Then, use tf.nn.sampled_softmax_loss to calculate the loss. Be sure to read the documentation to figure out how it works. End of explanation import random with train_graph.as_default(): ## From Thushan Ganegedara's implementation valid_size = 16 # Random set of words to evaluate similarity on. valid_window = 100 # pick 8 samples from (0,100) and (1000,1100) each ranges. lower id implies more frequent valid_examples = np.array(random.sample(range(valid_window), valid_size//2)) valid_examples = np.append(valid_examples, random.sample(range(1000,1000+valid_window), valid_size//2)) valid_dataset = tf.constant(valid_examples, dtype=tf.int32) # We use the cosine distance: norm = tf.sqrt(tf.reduce_sum(tf.square(embedding), 1, keep_dims=True)) normalized_embedding = embedding / norm valid_embedding = tf.nn.embedding_lookup(normalized_embedding, valid_dataset) similarity = tf.matmul(valid_embedding, tf.transpose(normalized_embedding)) # If the checkpoints directory doesn't exist: !mkdir checkpoints Explanation: Validation This code is from Thushan Ganegedara's implementation. Here we're going to choose a few common words and few uncommon words. Then, we'll print out the closest words to them. It's a nice way to check that our embedding table is grouping together words with similar semantic meanings. End of explanation epochs = 10 batch_size = 1000 window_size = 10 with train_graph.as_default(): saver = tf.train.Saver() with tf.Session(graph=train_graph) as sess: iteration = 1 loss = 0 sess.run(tf.global_variables_initializer()) for e in range(1, epochs+1): batches = get_batches(train_words, batch_size, window_size) start = time.time() for x, y in batches: feed = {inputs: x, labels: np.array(y)[:, None]} train_loss, _ = sess.run([cost, optimizer], feed_dict=feed) loss += train_loss if iteration % 100 == 0: end = time.time() print("Epoch {}/{}".format(e, epochs), "Iteration: {}".format(iteration), "Avg. Training loss: {:.4f}".format(loss/100), "{:.4f} sec/batch".format((end-start)/100)) loss = 0 start = time.time() if iteration % 1000 == 0: ## From Thushan Ganegedara's implementation # note that this is expensive (~20% slowdown if computed every 500 steps) sim = similarity.eval() for i in range(valid_size): valid_word = int_to_vocab[valid_examples[i]] top_k = 8 # number of nearest neighbors nearest = (-sim[i, :]).argsort()[1:top_k+1] log = 'Nearest to %s:' % valid_word for k in range(top_k): close_word = int_to_vocab[nearest[k]] log = '%s %s,' % (log, close_word) print(log) iteration += 1 save_path = saver.save(sess, "checkpoints/text8.ckpt") embed_mat = sess.run(normalized_embedding) Explanation: Training Below is the code to train the network. Every 100 batches it reports the training loss. Every 1000 batches, it'll print out the validation words. End of explanation with train_graph.as_default(): saver = tf.train.Saver() with tf.Session(graph=train_graph) as sess: saver.restore(sess, tf.train.latest_checkpoint('checkpoints')) embed_mat = sess.run(embedding) Explanation: Restore the trained network if you need to: End of explanation %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt from sklearn.manifold import TSNE viz_words = 500 tsne = TSNE() embed_tsne = tsne.fit_transform(embed_mat[:viz_words, :]) fig, ax = plt.subplots(figsize=(14, 14)) for idx in range(viz_words): plt.scatter(*embed_tsne[idx, :], color='steelblue') plt.annotate(int_to_vocab[idx], (embed_tsne[idx, 0], embed_tsne[idx, 1]), alpha=0.7) Explanation: Visualizing the word vectors Below we'll use T-SNE to visualize how our high-dimensional word vectors cluster together. T-SNE is used to project these vectors into two dimensions while preserving local stucture. Check out this post from Christopher Olah to learn more about T-SNE and other ways to visualize high-dimensional data. End of explanation
7,310
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocean MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify document publication status Step4: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Seawater Properties 3. Key Properties --&gt; Bathymetry 4. Key Properties --&gt; Nonoceanic Waters 5. Key Properties --&gt; Software Properties 6. Key Properties --&gt; Resolution 7. Key Properties --&gt; Tuning Applied 8. Key Properties --&gt; Conservation 9. Grid 10. Grid --&gt; Discretisation --&gt; Vertical 11. Grid --&gt; Discretisation --&gt; Horizontal 12. Timestepping Framework 13. Timestepping Framework --&gt; Tracers 14. Timestepping Framework --&gt; Baroclinic Dynamics 15. Timestepping Framework --&gt; Barotropic 16. Timestepping Framework --&gt; Vertical Physics 17. Advection 18. Advection --&gt; Momentum 19. Advection --&gt; Lateral Tracers 20. Advection --&gt; Vertical Tracers 21. Lateral Physics 22. Lateral Physics --&gt; Momentum --&gt; Operator 23. Lateral Physics --&gt; Momentum --&gt; Eddy Viscosity Coeff 24. Lateral Physics --&gt; Tracers 25. Lateral Physics --&gt; Tracers --&gt; Operator 26. Lateral Physics --&gt; Tracers --&gt; Eddy Diffusity Coeff 27. Lateral Physics --&gt; Tracers --&gt; Eddy Induced Velocity 28. Vertical Physics 29. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Details 30. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Tracers 31. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Momentum 32. Vertical Physics --&gt; Interior Mixing --&gt; Details 33. Vertical Physics --&gt; Interior Mixing --&gt; Tracers 34. Vertical Physics --&gt; Interior Mixing --&gt; Momentum 35. Uplow Boundaries --&gt; Free Surface 36. Uplow Boundaries --&gt; Bottom Boundary Layer 37. Boundary Forcing 38. Boundary Forcing --&gt; Momentum --&gt; Bottom Friction 39. Boundary Forcing --&gt; Momentum --&gt; Lateral Friction 40. Boundary Forcing --&gt; Tracers --&gt; Sunlight Penetration 41. Boundary Forcing --&gt; Tracers --&gt; Fresh Water Forcing 1. Key Properties Ocean key properties 1.1. Model Overview Is Required Step5: 1.2. Model Name Is Required Step6: 1.3. Model Family Is Required Step7: 1.4. Basic Approximations Is Required Step8: 1.5. Prognostic Variables Is Required Step9: 2. Key Properties --&gt; Seawater Properties Physical properties of seawater in ocean 2.1. Eos Type Is Required Step10: 2.2. Eos Functional Temp Is Required Step11: 2.3. Eos Functional Salt Is Required Step12: 2.4. Eos Functional Depth Is Required Step13: 2.5. Ocean Freezing Point Is Required Step14: 2.6. Ocean Specific Heat Is Required Step15: 2.7. Ocean Reference Density Is Required Step16: 3. Key Properties --&gt; Bathymetry Properties of bathymetry in ocean 3.1. Reference Dates Is Required Step17: 3.2. Type Is Required Step18: 3.3. Ocean Smoothing Is Required Step19: 3.4. Source Is Required Step20: 4. Key Properties --&gt; Nonoceanic Waters Non oceanic waters treatement in ocean 4.1. Isolated Seas Is Required Step21: 4.2. River Mouth Is Required Step22: 5. Key Properties --&gt; Software Properties Software properties of ocean code 5.1. Repository Is Required Step23: 5.2. Code Version Is Required Step24: 5.3. Code Languages Is Required Step25: 6. Key Properties --&gt; Resolution Resolution in the ocean grid 6.1. Name Is Required Step26: 6.2. Canonical Horizontal Resolution Is Required Step27: 6.3. Range Horizontal Resolution Is Required Step28: 6.4. Number Of Horizontal Gridpoints Is Required Step29: 6.5. Number Of Vertical Levels Is Required Step30: 6.6. Is Adaptive Grid Is Required Step31: 6.7. Thickness Level 1 Is Required Step32: 7. Key Properties --&gt; Tuning Applied Tuning methodology for ocean component 7.1. Description Is Required Step33: 7.2. Global Mean Metrics Used Is Required Step34: 7.3. Regional Metrics Used Is Required Step35: 7.4. Trend Metrics Used Is Required Step36: 8. Key Properties --&gt; Conservation Conservation in the ocean component 8.1. Description Is Required Step37: 8.2. Scheme Is Required Step38: 8.3. Consistency Properties Is Required Step39: 8.4. Corrected Conserved Prognostic Variables Is Required Step40: 8.5. Was Flux Correction Used Is Required Step41: 9. Grid Ocean grid 9.1. Overview Is Required Step42: 10. Grid --&gt; Discretisation --&gt; Vertical Properties of vertical discretisation in ocean 10.1. Coordinates Is Required Step43: 10.2. Partial Steps Is Required Step44: 11. Grid --&gt; Discretisation --&gt; Horizontal Type of horizontal discretisation scheme in ocean 11.1. Type Is Required Step45: 11.2. Staggering Is Required Step46: 11.3. Scheme Is Required Step47: 12. Timestepping Framework Ocean Timestepping Framework 12.1. Overview Is Required Step48: 12.2. Diurnal Cycle Is Required Step49: 13. Timestepping Framework --&gt; Tracers Properties of tracers time stepping in ocean 13.1. Scheme Is Required Step50: 13.2. Time Step Is Required Step51: 14. Timestepping Framework --&gt; Baroclinic Dynamics Baroclinic dynamics in ocean 14.1. Type Is Required Step52: 14.2. Scheme Is Required Step53: 14.3. Time Step Is Required Step54: 15. Timestepping Framework --&gt; Barotropic Barotropic time stepping in ocean 15.1. Splitting Is Required Step55: 15.2. Time Step Is Required Step56: 16. Timestepping Framework --&gt; Vertical Physics Vertical physics time stepping in ocean 16.1. Method Is Required Step57: 17. Advection Ocean advection 17.1. Overview Is Required Step58: 18. Advection --&gt; Momentum Properties of lateral momemtum advection scheme in ocean 18.1. Type Is Required Step59: 18.2. Scheme Name Is Required Step60: 18.3. ALE Is Required Step61: 19. Advection --&gt; Lateral Tracers Properties of lateral tracer advection scheme in ocean 19.1. Order Is Required Step62: 19.2. Flux Limiter Is Required Step63: 19.3. Effective Order Is Required Step64: 19.4. Name Is Required Step65: 19.5. Passive Tracers Is Required Step66: 19.6. Passive Tracers Advection Is Required Step67: 20. Advection --&gt; Vertical Tracers Properties of vertical tracer advection scheme in ocean 20.1. Name Is Required Step68: 20.2. Flux Limiter Is Required Step69: 21. Lateral Physics Ocean lateral physics 21.1. Overview Is Required Step70: 21.2. Scheme Is Required Step71: 22. Lateral Physics --&gt; Momentum --&gt; Operator Properties of lateral physics operator for momentum in ocean 22.1. Direction Is Required Step72: 22.2. Order Is Required Step73: 22.3. Discretisation Is Required Step74: 23. Lateral Physics --&gt; Momentum --&gt; Eddy Viscosity Coeff Properties of eddy viscosity coeff in lateral physics momemtum scheme in the ocean 23.1. Type Is Required Step75: 23.2. Constant Coefficient Is Required Step76: 23.3. Variable Coefficient Is Required Step77: 23.4. Coeff Background Is Required Step78: 23.5. Coeff Backscatter Is Required Step79: 24. Lateral Physics --&gt; Tracers Properties of lateral physics for tracers in ocean 24.1. Mesoscale Closure Is Required Step80: 24.2. Submesoscale Mixing Is Required Step81: 25. Lateral Physics --&gt; Tracers --&gt; Operator Properties of lateral physics operator for tracers in ocean 25.1. Direction Is Required Step82: 25.2. Order Is Required Step83: 25.3. Discretisation Is Required Step84: 26. Lateral Physics --&gt; Tracers --&gt; Eddy Diffusity Coeff Properties of eddy diffusity coeff in lateral physics tracers scheme in the ocean 26.1. Type Is Required Step85: 26.2. Constant Coefficient Is Required Step86: 26.3. Variable Coefficient Is Required Step87: 26.4. Coeff Background Is Required Step88: 26.5. Coeff Backscatter Is Required Step89: 27. Lateral Physics --&gt; Tracers --&gt; Eddy Induced Velocity Properties of eddy induced velocity (EIV) in lateral physics tracers scheme in the ocean 27.1. Type Is Required Step90: 27.2. Constant Val Is Required Step91: 27.3. Flux Type Is Required Step92: 27.4. Added Diffusivity Is Required Step93: 28. Vertical Physics Ocean Vertical Physics 28.1. Overview Is Required Step94: 29. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Details Properties of vertical physics in ocean 29.1. Langmuir Cells Mixing Is Required Step95: 30. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Tracers *Properties of boundary layer (BL) mixing on tracers in the ocean * 30.1. Type Is Required Step96: 30.2. Closure Order Is Required Step97: 30.3. Constant Is Required Step98: 30.4. Background Is Required Step99: 31. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Momentum *Properties of boundary layer (BL) mixing on momentum in the ocean * 31.1. Type Is Required Step100: 31.2. Closure Order Is Required Step101: 31.3. Constant Is Required Step102: 31.4. Background Is Required Step103: 32. Vertical Physics --&gt; Interior Mixing --&gt; Details *Properties of interior mixing in the ocean * 32.1. Convection Type Is Required Step104: 32.2. Tide Induced Mixing Is Required Step105: 32.3. Double Diffusion Is Required Step106: 32.4. Shear Mixing Is Required Step107: 33. Vertical Physics --&gt; Interior Mixing --&gt; Tracers *Properties of interior mixing on tracers in the ocean * 33.1. Type Is Required Step108: 33.2. Constant Is Required Step109: 33.3. Profile Is Required Step110: 33.4. Background Is Required Step111: 34. Vertical Physics --&gt; Interior Mixing --&gt; Momentum *Properties of interior mixing on momentum in the ocean * 34.1. Type Is Required Step112: 34.2. Constant Is Required Step113: 34.3. Profile Is Required Step114: 34.4. Background Is Required Step115: 35. Uplow Boundaries --&gt; Free Surface Properties of free surface in ocean 35.1. Overview Is Required Step116: 35.2. Scheme Is Required Step117: 35.3. Embeded Seaice Is Required Step118: 36. Uplow Boundaries --&gt; Bottom Boundary Layer Properties of bottom boundary layer in ocean 36.1. Overview Is Required Step119: 36.2. Type Of Bbl Is Required Step120: 36.3. Lateral Mixing Coef Is Required Step121: 36.4. Sill Overflow Is Required Step122: 37. Boundary Forcing Ocean boundary forcing 37.1. Overview Is Required Step123: 37.2. Surface Pressure Is Required Step124: 37.3. Momentum Flux Correction Is Required Step125: 37.4. Tracers Flux Correction Is Required Step126: 37.5. Wave Effects Is Required Step127: 37.6. River Runoff Budget Is Required Step128: 37.7. Geothermal Heating Is Required Step129: 38. Boundary Forcing --&gt; Momentum --&gt; Bottom Friction Properties of momentum bottom friction in ocean 38.1. Type Is Required Step130: 39. Boundary Forcing --&gt; Momentum --&gt; Lateral Friction Properties of momentum lateral friction in ocean 39.1. Type Is Required Step131: 40. Boundary Forcing --&gt; Tracers --&gt; Sunlight Penetration Properties of sunlight penetration scheme in ocean 40.1. Scheme Is Required Step132: 40.2. Ocean Colour Is Required Step133: 40.3. Extinction Depth Is Required Step134: 41. Boundary Forcing --&gt; Tracers --&gt; Fresh Water Forcing Properties of surface fresh water forcing in ocean 41.1. From Atmopshere Is Required Step135: 41.2. From Sea Ice Is Required Step136: 41.3. Forced Mode Restoring Is Required
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'snu', 'sandbox-2', 'ocean') Explanation: ES-DOC CMIP6 Model Properties - Ocean MIP Era: CMIP6 Institute: SNU Source ID: SANDBOX-2 Topic: Ocean Sub-Topics: Timestepping Framework, Advection, Lateral Physics, Vertical Physics, Uplow Boundaries, Boundary Forcing. Properties: 133 (101 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:54:38 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) Explanation: Document Authors Set document authors End of explanation # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) Explanation: Document Contributors Specify document contributors End of explanation # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) Explanation: Document Publication Specify document publication status End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Seawater Properties 3. Key Properties --&gt; Bathymetry 4. Key Properties --&gt; Nonoceanic Waters 5. Key Properties --&gt; Software Properties 6. Key Properties --&gt; Resolution 7. Key Properties --&gt; Tuning Applied 8. Key Properties --&gt; Conservation 9. Grid 10. Grid --&gt; Discretisation --&gt; Vertical 11. Grid --&gt; Discretisation --&gt; Horizontal 12. Timestepping Framework 13. Timestepping Framework --&gt; Tracers 14. Timestepping Framework --&gt; Baroclinic Dynamics 15. Timestepping Framework --&gt; Barotropic 16. Timestepping Framework --&gt; Vertical Physics 17. Advection 18. Advection --&gt; Momentum 19. Advection --&gt; Lateral Tracers 20. Advection --&gt; Vertical Tracers 21. Lateral Physics 22. Lateral Physics --&gt; Momentum --&gt; Operator 23. Lateral Physics --&gt; Momentum --&gt; Eddy Viscosity Coeff 24. Lateral Physics --&gt; Tracers 25. Lateral Physics --&gt; Tracers --&gt; Operator 26. Lateral Physics --&gt; Tracers --&gt; Eddy Diffusity Coeff 27. Lateral Physics --&gt; Tracers --&gt; Eddy Induced Velocity 28. Vertical Physics 29. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Details 30. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Tracers 31. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Momentum 32. Vertical Physics --&gt; Interior Mixing --&gt; Details 33. Vertical Physics --&gt; Interior Mixing --&gt; Tracers 34. Vertical Physics --&gt; Interior Mixing --&gt; Momentum 35. Uplow Boundaries --&gt; Free Surface 36. Uplow Boundaries --&gt; Bottom Boundary Layer 37. Boundary Forcing 38. Boundary Forcing --&gt; Momentum --&gt; Bottom Friction 39. Boundary Forcing --&gt; Momentum --&gt; Lateral Friction 40. Boundary Forcing --&gt; Tracers --&gt; Sunlight Penetration 41. Boundary Forcing --&gt; Tracers --&gt; Fresh Water Forcing 1. Key Properties Ocean key properties 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of ocean model. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of ocean model code (NEMO 3.6, MOM 5.0,...) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.model_family') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OGCM" # "slab ocean" # "mixed layer ocean" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 1.3. Model Family Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of ocean model. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.basic_approximations') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Primitive equations" # "Non-hydrostatic" # "Boussinesq" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 1.4. Basic Approximations Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Basic approximations made in the ocean. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Potential temperature" # "Conservative temperature" # "Salinity" # "U-velocity" # "V-velocity" # "W-velocity" # "SSH" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 1.5. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of prognostic variables in the ocean component. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Linear" # "Wright, 1997" # "Mc Dougall et al." # "Jackett et al. 2006" # "TEOS 2010" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 2. Key Properties --&gt; Seawater Properties Physical properties of seawater in ocean 2.1. Eos Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of EOS for sea water End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_functional_temp') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Potential temperature" # "Conservative temperature" # TODO - please enter value(s) Explanation: 2.2. Eos Functional Temp Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Temperature used in EOS for sea water End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_functional_salt') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Practical salinity Sp" # "Absolute salinity Sa" # TODO - please enter value(s) Explanation: 2.3. Eos Functional Salt Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Salinity used in EOS for sea water End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.eos_functional_depth') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Pressure (dbars)" # "Depth (meters)" # TODO - please enter value(s) Explanation: 2.4. Eos Functional Depth Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Depth or pressure used in EOS for sea water ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.ocean_freezing_point') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "TEOS 2010" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 2.5. Ocean Freezing Point Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Equation used to compute the freezing point (in deg C) of seawater, as a function of salinity and pressure End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.ocean_specific_heat') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 2.6. Ocean Specific Heat Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specific heat in ocean (cpocean) in J/(kg K) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.seawater_properties.ocean_reference_density') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 2.7. Ocean Reference Density Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Boussinesq reference density (rhozero) in kg / m3 End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.bathymetry.reference_dates') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Present day" # "21000 years BP" # "6000 years BP" # "LGM" # "Pliocene" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 3. Key Properties --&gt; Bathymetry Properties of bathymetry in ocean 3.1. Reference Dates Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Reference date of bathymetry End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.bathymetry.type') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 3.2. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the bathymetry fixed in time in the ocean ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.bathymetry.ocean_smoothing') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 3.3. Ocean Smoothing Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe any smoothing or hand editing of bathymetry in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.bathymetry.source') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 3.4. Source Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe source of bathymetry in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.nonoceanic_waters.isolated_seas') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 4. Key Properties --&gt; Nonoceanic Waters Non oceanic waters treatement in ocean 4.1. Isolated Seas Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how isolated seas is performed End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.nonoceanic_waters.river_mouth') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 4.2. River Mouth Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe if/how river mouth mixing or estuaries specific treatment is performed End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 5. Key Properties --&gt; Software Properties Software properties of ocean code 5.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 5.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 5.3. Code Languages Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Code language(s). End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6. Key Properties --&gt; Resolution Resolution in the ocean grid 6.1. Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 This is a string usually used by the modelling group to describe the resolution of this grid, e.g. ORCA025, N512L180, T512L70 etc. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.canonical_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.2. Canonical Horizontal Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Expression quoted for gross comparisons of resolution, eg. 50km or 0.1 degrees etc. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.range_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.3. Range Horizontal Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Range of horizontal resolution with spatial details, eg. 50(Equator)-100km or 0.1-0.5 degrees etc. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.number_of_horizontal_gridpoints') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 6.4. Number Of Horizontal Gridpoints Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Total number of horizontal (XY) points (or degrees of freedom) on computational grid. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.number_of_vertical_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 6.5. Number Of Vertical Levels Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of vertical levels resolved on computational grid. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.is_adaptive_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.6. Is Adaptive Grid Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Default is False. Set true if grid resolution changes during execution. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.resolution.thickness_level_1') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 6.7. Thickness Level 1 Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Thickness of first surface ocean level (in meters) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.tuning_applied.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 7. Key Properties --&gt; Tuning Applied Tuning methodology for ocean component 7.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General 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. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.tuning_applied.global_mean_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 7.2. Global Mean Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List set of metrics of the global mean state used in tuning model/component End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.tuning_applied.regional_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 7.3. Regional Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List of regional metrics of mean state (e.g THC, AABW, regional means etc) used in tuning model/component End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.tuning_applied.trend_metrics_used') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 7.4. Trend Metrics Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List observed trend metrics used in tuning model/component End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.conservation.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8. Key Properties --&gt; Conservation Conservation in the ocean component 8.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Brief description of conservation methodology End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.conservation.scheme') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Energy" # "Enstrophy" # "Salt" # "Volume of ocean" # "Momentum" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 8.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Properties conserved in the ocean by the numerical schemes End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.conservation.consistency_properties') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8.3. Consistency Properties Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Any additional consistency properties (energy conversion, pressure gradient discretisation, ...)? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.conservation.corrected_conserved_prognostic_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8.4. Corrected Conserved Prognostic Variables Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Set of variables which are conserved by more than the numerical scheme alone. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.key_properties.conservation.was_flux_correction_used') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 8.5. Was Flux Correction Used Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Does conservation involve flux correction ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9. Grid Ocean grid 9.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of grid in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.discretisation.vertical.coordinates') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Z-coordinate" # "Z*-coordinate" # "S-coordinate" # "Isopycnic - sigma 0" # "Isopycnic - sigma 2" # "Isopycnic - sigma 4" # "Isopycnic - other" # "Hybrid / Z+S" # "Hybrid / Z+isopycnic" # "Hybrid / other" # "Pressure referenced (P)" # "P*" # "Z**" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 10. Grid --&gt; Discretisation --&gt; Vertical Properties of vertical discretisation in ocean 10.1. Coordinates Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of vertical coordinates in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.discretisation.vertical.partial_steps') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 10.2. Partial Steps Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Using partial steps with Z or Z vertical coordinate in ocean ?* End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.discretisation.horizontal.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Lat-lon" # "Rotated north pole" # "Two north poles (ORCA-style)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 11. Grid --&gt; Discretisation --&gt; Horizontal Type of horizontal discretisation scheme in ocean 11.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal grid type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.discretisation.horizontal.staggering') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Arakawa B-grid" # "Arakawa C-grid" # "Arakawa E-grid" # "N/a" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 11.2. Staggering Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Horizontal grid staggering type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.grid.discretisation.horizontal.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Finite difference" # "Finite volumes" # "Finite elements" # "Unstructured grid" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 11.3. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal discretisation scheme in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 12. Timestepping Framework Ocean Timestepping Framework 12.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of time stepping in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.diurnal_cycle') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Via coupling" # "Specific treatment" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 12.2. Diurnal Cycle Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Diurnal cycle type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.tracers.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Leap-frog + Asselin filter" # "Leap-frog + Periodic Euler" # "Predictor-corrector" # "Runge-Kutta 2" # "AM3-LF" # "Forward-backward" # "Forward operator" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13. Timestepping Framework --&gt; Tracers Properties of tracers time stepping in ocean 13.1. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Tracers time stepping scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.tracers.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 13.2. Time Step Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Tracers time step (in seconds) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.baroclinic_dynamics.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Preconditioned conjugate gradient" # "Sub cyling" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 14. Timestepping Framework --&gt; Baroclinic Dynamics Baroclinic dynamics in ocean 14.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Baroclinic dynamics type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.baroclinic_dynamics.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Leap-frog + Asselin filter" # "Leap-frog + Periodic Euler" # "Predictor-corrector" # "Runge-Kutta 2" # "AM3-LF" # "Forward-backward" # "Forward operator" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 14.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Baroclinic dynamics scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.baroclinic_dynamics.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 14.3. Time Step Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Baroclinic time step (in seconds) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.barotropic.splitting') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "split explicit" # "implicit" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 15. Timestepping Framework --&gt; Barotropic Barotropic time stepping in ocean 15.1. Splitting Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time splitting method End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.barotropic.time_step') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 15.2. Time Step Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Barotropic time step (in seconds) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.timestepping_framework.vertical_physics.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 16. Timestepping Framework --&gt; Vertical Physics Vertical physics time stepping in ocean 16.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Details of vertical time stepping in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 17. Advection Ocean advection 17.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of advection in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.momentum.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Flux form" # "Vector form" # TODO - please enter value(s) Explanation: 18. Advection --&gt; Momentum Properties of lateral momemtum advection scheme in ocean 18.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of lateral momemtum advection scheme in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.momentum.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 18.2. Scheme Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of ocean momemtum advection scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.momentum.ALE') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 18.3. ALE Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Using ALE for vertical advection ? (if vertical coordinates are sigma) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 19. Advection --&gt; Lateral Tracers Properties of lateral tracer advection scheme in ocean 19.1. Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Order of lateral tracer advection scheme in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.flux_limiter') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 19.2. Flux Limiter Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Monotonic flux limiter for lateral tracer advection scheme in ocean ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.effective_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 19.3. Effective Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Effective order of limited lateral tracer advection scheme in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 19.4. Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Descriptive text for lateral tracer advection scheme in ocean (e.g. MUSCL, PPM-H5, PRATHER,...) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.passive_tracers') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Ideal age" # "CFC 11" # "CFC 12" # "SF6" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 19.5. Passive Tracers Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Passive tracers advected End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.lateral_tracers.passive_tracers_advection') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 19.6. Passive Tracers Advection Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Is advection of passive tracers different than active ? if so, describe. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.vertical_tracers.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 20. Advection --&gt; Vertical Tracers Properties of vertical tracer advection scheme in ocean 20.1. Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Descriptive text for vertical tracer advection scheme in ocean (e.g. MUSCL, PPM-H5, PRATHER,...) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.advection.vertical_tracers.flux_limiter') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 20.2. Flux Limiter Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Monotonic flux limiter for vertical tracer advection scheme in ocean ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 21. Lateral Physics Ocean lateral physics 21.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of lateral physics in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Eddy active" # "Eddy admitting" # TODO - please enter value(s) Explanation: 21.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of transient eddy representation in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.operator.direction') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Horizontal" # "Isopycnal" # "Isoneutral" # "Geopotential" # "Iso-level" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 22. Lateral Physics --&gt; Momentum --&gt; Operator Properties of lateral physics operator for momentum in ocean 22.1. Direction Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Direction of lateral physics momemtum scheme in the ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.operator.order') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Harmonic" # "Bi-harmonic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 22.2. Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Order of lateral physics momemtum scheme in the ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.operator.discretisation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Second order" # "Higher order" # "Flux limiter" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 22.3. Discretisation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Discretisation of lateral physics momemtum scheme in the ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant" # "Space varying" # "Time + space varying (Smagorinsky)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 23. Lateral Physics --&gt; Momentum --&gt; Eddy Viscosity Coeff Properties of eddy viscosity coeff in lateral physics momemtum scheme in the ocean 23.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Lateral physics momemtum eddy viscosity coeff type in the ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.constant_coefficient') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 23.2. Constant Coefficient Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant, value of eddy viscosity coeff in lateral physics momemtum scheme (in m2/s) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.variable_coefficient') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 23.3. Variable Coefficient Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If space-varying, describe variations of eddy viscosity coeff in lateral physics momemtum scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.coeff_background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 23.4. Coeff Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe background eddy viscosity coeff in lateral physics momemtum scheme (give values in m2/s) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.momentum.eddy_viscosity_coeff.coeff_backscatter') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 23.5. Coeff Backscatter Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there backscatter in eddy viscosity coeff in lateral physics momemtum scheme ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.mesoscale_closure') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 24. Lateral Physics --&gt; Tracers Properties of lateral physics for tracers in ocean 24.1. Mesoscale Closure Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there a mesoscale closure in the lateral physics tracers scheme ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.submesoscale_mixing') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 24.2. Submesoscale Mixing Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there a submesoscale mixing parameterisation (i.e Fox-Kemper) in the lateral physics tracers scheme ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.operator.direction') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Horizontal" # "Isopycnal" # "Isoneutral" # "Geopotential" # "Iso-level" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 25. Lateral Physics --&gt; Tracers --&gt; Operator Properties of lateral physics operator for tracers in ocean 25.1. Direction Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Direction of lateral physics tracers scheme in the ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.operator.order') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Harmonic" # "Bi-harmonic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 25.2. Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Order of lateral physics tracers scheme in the ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.operator.discretisation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Second order" # "Higher order" # "Flux limiter" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 25.3. Discretisation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Discretisation of lateral physics tracers scheme in the ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant" # "Space varying" # "Time + space varying (Smagorinsky)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 26. Lateral Physics --&gt; Tracers --&gt; Eddy Diffusity Coeff Properties of eddy diffusity coeff in lateral physics tracers scheme in the ocean 26.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Lateral physics tracers eddy diffusity coeff type in the ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.constant_coefficient') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 26.2. Constant Coefficient Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant, value of eddy diffusity coeff in lateral physics tracers scheme (in m2/s) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.variable_coefficient') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 26.3. Variable Coefficient Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If space-varying, describe variations of eddy diffusity coeff in lateral physics tracers scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.coeff_background') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 26.4. Coeff Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe background eddy diffusity coeff in lateral physics tracers scheme (give values in m2/s) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_diffusity_coeff.coeff_backscatter') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 26.5. Coeff Backscatter Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there backscatter in eddy diffusity coeff in lateral physics tracers scheme ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "GM" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 27. Lateral Physics --&gt; Tracers --&gt; Eddy Induced Velocity Properties of eddy induced velocity (EIV) in lateral physics tracers scheme in the ocean 27.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of EIV in lateral physics tracers in the ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.constant_val') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 27.2. Constant Val Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If EIV scheme for tracers is constant, specify coefficient value (M2/s) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.flux_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 27.3. Flux Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of EIV flux (advective or skew) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.lateral_physics.tracers.eddy_induced_velocity.added_diffusivity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 27.4. Added Diffusivity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of EIV added diffusivity (constant, flow dependent or none) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 28. Vertical Physics Ocean Vertical Physics 28.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of vertical physics in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.details.langmuir_cells_mixing') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 29. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Details Properties of vertical physics in ocean 29.1. Langmuir Cells Mixing Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there Langmuir cells mixing in upper ocean ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant value" # "Turbulent closure - TKE" # "Turbulent closure - KPP" # "Turbulent closure - Mellor-Yamada" # "Turbulent closure - Bulk Mixed Layer" # "Richardson number dependent - PP" # "Richardson number dependent - KT" # "Imbeded as isopycnic vertical coordinate" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 30. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Tracers *Properties of boundary layer (BL) mixing on tracers in the ocean * 30.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of boundary layer mixing for tracers in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.closure_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 30.2. Closure Order Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If turbulent BL mixing of tracers, specific order of closure (0, 1, 2.5, 3) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.constant') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 30.3. Constant Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant BL mixing of tracers, specific coefficient (m2/s) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.tracers.background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 30.4. Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Background BL mixing of tracers coefficient, (schema and value in m2/s - may by none) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant value" # "Turbulent closure - TKE" # "Turbulent closure - KPP" # "Turbulent closure - Mellor-Yamada" # "Turbulent closure - Bulk Mixed Layer" # "Richardson number dependent - PP" # "Richardson number dependent - KT" # "Imbeded as isopycnic vertical coordinate" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 31. Vertical Physics --&gt; Boundary Layer Mixing --&gt; Momentum *Properties of boundary layer (BL) mixing on momentum in the ocean * 31.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of boundary layer mixing for momentum in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.closure_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 31.2. Closure Order Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If turbulent BL mixing of momentum, specific order of closure (0, 1, 2.5, 3) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.constant') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 31.3. Constant Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant BL mixing of momentum, specific coefficient (m2/s) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.boundary_layer_mixing.momentum.background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 31.4. Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Background BL mixing of momentum coefficient, (schema and value in m2/s - may by none) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.convection_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Non-penetrative convective adjustment" # "Enhanced vertical diffusion" # "Included in turbulence closure" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 32. Vertical Physics --&gt; Interior Mixing --&gt; Details *Properties of interior mixing in the ocean * 32.1. Convection Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of vertical convection in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.tide_induced_mixing') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 32.2. Tide Induced Mixing Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how tide induced mixing is modelled (barotropic, baroclinic, none) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.double_diffusion') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 32.3. Double Diffusion Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there double diffusion End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.details.shear_mixing') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 32.4. Shear Mixing Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there interior shear mixing End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant value" # "Turbulent closure / TKE" # "Turbulent closure - Mellor-Yamada" # "Richardson number dependent - PP" # "Richardson number dependent - KT" # "Imbeded as isopycnic vertical coordinate" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 33. Vertical Physics --&gt; Interior Mixing --&gt; Tracers *Properties of interior mixing on tracers in the ocean * 33.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of interior mixing for tracers in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.constant') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 33.2. Constant Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant interior mixing of tracers, specific coefficient (m2/s) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.profile') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 33.3. Profile Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the background interior mixing using a vertical profile for tracers (i.e is NOT constant) ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.tracers.background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 33.4. Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Background interior mixing of tracers coefficient, (schema and value in m2/s - may by none) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant value" # "Turbulent closure / TKE" # "Turbulent closure - Mellor-Yamada" # "Richardson number dependent - PP" # "Richardson number dependent - KT" # "Imbeded as isopycnic vertical coordinate" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 34. Vertical Physics --&gt; Interior Mixing --&gt; Momentum *Properties of interior mixing on momentum in the ocean * 34.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of interior mixing for momentum in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.constant') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 34.2. Constant Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If constant interior mixing of momentum, specific coefficient (m2/s) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.profile') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 34.3. Profile Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the background interior mixing using a vertical profile for momentum (i.e is NOT constant) ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.vertical_physics.interior_mixing.momentum.background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 34.4. Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Background interior mixing of momentum coefficient, (schema and value in m2/s - may by none) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.free_surface.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 35. Uplow Boundaries --&gt; Free Surface Properties of free surface in ocean 35.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of free surface in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.free_surface.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Linear implicit" # "Linear filtered" # "Linear semi-explicit" # "Non-linear implicit" # "Non-linear filtered" # "Non-linear semi-explicit" # "Fully explicit" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 35.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Free surface scheme in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.free_surface.embeded_seaice') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 35.3. Embeded Seaice Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the sea-ice embeded in the ocean model (instead of levitating) ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 36. Uplow Boundaries --&gt; Bottom Boundary Layer Properties of bottom boundary layer in ocean 36.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of bottom boundary layer in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.type_of_bbl') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Diffusive" # "Acvective" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 36.2. Type Of Bbl Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of bottom boundary layer in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.lateral_mixing_coef') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 36.3. Lateral Mixing Coef Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If bottom BL is diffusive, specify value of lateral mixing coefficient (in m2/s) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.uplow_boundaries.bottom_boundary_layer.sill_overflow') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 36.4. Sill Overflow Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe any specific treatment of sill overflows End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 37. Boundary Forcing Ocean boundary forcing 37.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of boundary forcing in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.surface_pressure') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 37.2. Surface Pressure Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how surface pressure is transmitted to ocean (via sea-ice, nothing specific,...) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.momentum_flux_correction') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 37.3. Momentum Flux Correction Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe any type of ocean surface momentum flux correction and, if applicable, how it is applied and where. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers_flux_correction') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 37.4. Tracers Flux Correction Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe any type of ocean surface tracers flux correction and, if applicable, how it is applied and where. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.wave_effects') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 37.5. Wave Effects Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe if/how wave effects are modelled at ocean surface. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.river_runoff_budget') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 37.6. River Runoff Budget Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how river runoff from land surface is routed to ocean and any global adjustment done. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.geothermal_heating') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 37.7. Geothermal Heating Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe if/how geothermal heating is present at ocean bottom. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.momentum.bottom_friction.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Linear" # "Non-linear" # "Non-linear (drag function of speed of tides)" # "Constant drag coefficient" # "None" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 38. Boundary Forcing --&gt; Momentum --&gt; Bottom Friction Properties of momentum bottom friction in ocean 38.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of momentum bottom friction in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.momentum.lateral_friction.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Free-slip" # "No-slip" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 39. Boundary Forcing --&gt; Momentum --&gt; Lateral Friction Properties of momentum lateral friction in ocean 39.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of momentum lateral friction in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.sunlight_penetration.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "1 extinction depth" # "2 extinction depth" # "3 extinction depth" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 40. Boundary Forcing --&gt; Tracers --&gt; Sunlight Penetration Properties of sunlight penetration scheme in ocean 40.1. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of sunlight penetration scheme in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.sunlight_penetration.ocean_colour') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 40.2. Ocean Colour Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the ocean sunlight penetration scheme ocean colour dependent ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.sunlight_penetration.extinction_depth') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 40.3. Extinction Depth Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe and list extinctions depths for sunlight penetration scheme (if applicable). End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.fresh_water_forcing.from_atmopshere') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Freshwater flux" # "Virtual salt flux" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 41. Boundary Forcing --&gt; Tracers --&gt; Fresh Water Forcing Properties of surface fresh water forcing in ocean 41.1. From Atmopshere Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of surface fresh water forcing from atmos in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.fresh_water_forcing.from_sea_ice') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Freshwater flux" # "Virtual salt flux" # "Real salt flux" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 41.2. From Sea Ice Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of surface fresh water forcing from sea-ice in ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocean.boundary_forcing.tracers.fresh_water_forcing.forced_mode_restoring') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 41.3. Forced Mode Restoring Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of surface salinity restoring in forced mode (OMIP) End of explanation
7,311
Given the following text description, write Python code to implement the functionality described below step by step Description: Inheritance Inheritance means extending the properties of one class by another. Inheritance implies code reusability, because of which client classes do not need to implement everything from scratch. They can simply refer to their base classes to execute the code. Unlike Java and C#, like C++, Python allows Multiple inheritance. Name resolution is done by the order in which the base classes are specified. Syntax python class ClassName(BaseClass1[,BaseClass2,....,BaseClassN]) Step1: <div class="alert alert-info"> **Note** Base class can be referred from derived class in two ways - Base Class name - `BaseClass.function(self,args)` - using `super()` - `super(DerivedClass, self).function(args)` </div> Multiple inheritance and Order of Invocation of Methods Step2: Note how pass statement is used to leave the class body empty. Otherwise it would have raised a Syntax Error. Since Drived1 and Derived2 are empty, they would have imported the methods from their base classes Step3: Now what will be the result of invoking some_method on d1 and d2? ... Does the name clash ocuur? ... Let's see
Python Code: class Person: # Constructor def __init__(self, name, age): self.name = name self.age = age def __str__(self): return 'name = {}\nage = {}'.format(self.name,self.age) # Inherited or Sub class class Employee(Person): def __init__(self, name, age, employee_id): Person.__init__(self, name, age) # Referring Base class # Can also be done by super(Employee, self).__init__(name, age) self.employee_id = employee_id # Overriding implied code reusability def __str__(self): return Person.__str__(self) + '\nemployee id = {}'.format(self.employee_id) s = Person('Kiran',18) print(s) e = Employee('Ramesh',18,48) print(e) Explanation: Inheritance Inheritance means extending the properties of one class by another. Inheritance implies code reusability, because of which client classes do not need to implement everything from scratch. They can simply refer to their base classes to execute the code. Unlike Java and C#, like C++, Python allows Multiple inheritance. Name resolution is done by the order in which the base classes are specified. Syntax python class ClassName(BaseClass1[,BaseClass2,....,BaseClassN]): &lt;statement 0&gt; &lt;statement 1&gt; &lt;statement 2&gt; ... ... ... &lt;statement n&gt; A First Example End of explanation class Base1: def some_method(self): print('Base1') class Base2: def some_method(self): print('Base2') class Derived1(Base1,Base2): pass class Derived2(Base2,Base1): pass Explanation: <div class="alert alert-info"> **Note** Base class can be referred from derived class in two ways - Base Class name - `BaseClass.function(self,args)` - using `super()` - `super(DerivedClass, self).function(args)` </div> Multiple inheritance and Order of Invocation of Methods End of explanation d1 = Derived1() d2 = Derived2() Explanation: Note how pass statement is used to leave the class body empty. Otherwise it would have raised a Syntax Error. Since Drived1 and Derived2 are empty, they would have imported the methods from their base classes End of explanation d1.some_method() d2.some_method() Explanation: Now what will be the result of invoking some_method on d1 and d2? ... Does the name clash ocuur? ... Let's see End of explanation
7,312
Given the following text description, write Python code to implement the functionality described below step by step Description: Examples and Exercises from Think Stats, 2nd Edition http Step1: Scatter plots I'll start with the data from the BRFSS again. Step2: The following function selects a random subset of a DataFrame. Step3: I'll extract the height in cm and the weight in kg of the respondents in the sample. Step4: Here's a simple scatter plot with alpha=1, so each data point is fully saturated. Step5: The data fall in obvious columns because they were rounded off. We can reduce this visual artifact by adding some random noice to the data. NOTE Step6: Heights were probably rounded off to the nearest inch, which is 2.8 cm, so I'll add random values from -1.4 to 1.4. Step7: And here's what the jittered data look like. Step8: The columns are gone, but now we have a different problem Step9: That's better. This version of the figure shows the location and shape of the distribution most accurately. There are still some apparent columns and rows where, most likely, people reported their height and weight using rounded values. If that effect is important, this figure makes it apparent; if it is not important, we could use more aggressive jittering to minimize it. An alternative to a scatter plot is something like a HexBin plot, which breaks the plane into bins, counts the number of respondents in each bin, and colors each bin in proportion to its count. Step10: In this case the binned plot does a pretty good job of showing the location and shape of the distribution. It obscures the row and column effects, which may or may not be a good thing. Exercise Step11: Plotting percentiles Sometimes a better way to get a sense of the relationship between variables is to divide the dataset into groups using one variable, and then plot percentiles of the other variable. First I'll drop any rows that are missing height or weight. Step12: Then I'll divide the dataset into groups by height. Step13: Here are the number of respondents in each group Step14: Now we can compute the CDF of weight within each group. Step15: And then extract the 25th, 50th, and 75th percentile from each group. Step16: Exercise Step17: Correlation The following function computes the covariance of two variables using NumPy's dot function. Step18: And here's an example Step19: Covariance is useful for some calculations, but it doesn't mean much by itself. The coefficient of correlation is a standardized version of covariance that is easier to interpret. Step20: The correlation of height and weight is about 0.51, which is a moderately strong correlation. Step21: NumPy provides a function that computes correlations, too Step22: The result is a matrix with self-correlations on the diagonal (which are always 1), and cross-correlations on the off-diagonals (which are always symmetric). Pearson's correlation is not robust in the presence of outliers, and it tends to underestimate the strength of non-linear relationships. Spearman's correlation is more robust, and it can handle non-linear relationships as long as they are monotonic. Here's a function that computes Spearman's correlation Step23: For heights and weights, Spearman's correlation is a little higher Step24: A Pandas Series provides a method that computes correlations, and it offers spearman as one of the options. Step25: The result is the same as for the one we wrote. Step26: An alternative to Spearman's correlation is to transform one or both of the variables in a way that makes the relationship closer to linear, and the compute Pearson's correlation. Step27: Exercises Using data from the NSFG, make a scatter plot of birth weight versus mother’s age. Plot percentiles of birth weight versus mother’s age. Compute Pearson’s and Spearman’s correlations. How would you characterize the relationship between these variables?
Python Code: from __future__ import print_function, division %matplotlib inline import numpy as np import brfss import thinkstats2 import thinkplot Explanation: Examples and Exercises from Think Stats, 2nd Edition http://thinkstats2.com Copyright 2016 Allen B. Downey MIT License: https://opensource.org/licenses/MIT End of explanation df = brfss.ReadBrfss(nrows=None) Explanation: Scatter plots I'll start with the data from the BRFSS again. End of explanation def SampleRows(df, nrows, replace=False): indices = np.random.choice(df.index, nrows, replace=replace) sample = df.loc[indices] return sample Explanation: The following function selects a random subset of a DataFrame. End of explanation sample = SampleRows(df, 5000) heights, weights = sample.htm3, sample.wtkg2 Explanation: I'll extract the height in cm and the weight in kg of the respondents in the sample. End of explanation thinkplot.Scatter(heights, weights, alpha=1) thinkplot.Config(xlabel='Height (cm)', ylabel='Weight (kg)', axis=[140, 210, 20, 200], legend=False) Explanation: Here's a simple scatter plot with alpha=1, so each data point is fully saturated. End of explanation def Jitter(values, jitter=0.5): n = len(values) return np.random.normal(0, jitter, n) + values Explanation: The data fall in obvious columns because they were rounded off. We can reduce this visual artifact by adding some random noice to the data. NOTE: The version of Jitter in the book uses noise with a uniform distribution. Here I am using a normal distribution. The normal distribution does a better job of blurring artifacts, but the uniform distribution might be more true to the data. End of explanation heights = Jitter(heights, 1.4) weights = Jitter(weights, 0.5) Explanation: Heights were probably rounded off to the nearest inch, which is 2.8 cm, so I'll add random values from -1.4 to 1.4. End of explanation thinkplot.Scatter(heights, weights, alpha=1.0) thinkplot.Config(xlabel='Height (cm)', ylabel='Weight (kg)', axis=[140, 210, 20, 200], legend=False) Explanation: And here's what the jittered data look like. End of explanation thinkplot.Scatter(heights, weights, alpha=0.1, s=10) thinkplot.Config(xlabel='Height (cm)', ylabel='Weight (kg)', axis=[140, 210, 20, 200], legend=False) Explanation: The columns are gone, but now we have a different problem: saturation. Where there are many overlapping points, the plot is not as dark as it should be, which means that the outliers are darker than they should be, which gives the impression that the data are more scattered than they actually are. This is a surprisingly common problem, even in papers published in peer-reviewed journals. We can usually solve the saturation problem by adjusting alpha and the size of the markers, s. End of explanation thinkplot.HexBin(heights, weights) thinkplot.Config(xlabel='Height (cm)', ylabel='Weight (kg)', axis=[140, 210, 20, 200], legend=False) Explanation: That's better. This version of the figure shows the location and shape of the distribution most accurately. There are still some apparent columns and rows where, most likely, people reported their height and weight using rounded values. If that effect is important, this figure makes it apparent; if it is not important, we could use more aggressive jittering to minimize it. An alternative to a scatter plot is something like a HexBin plot, which breaks the plane into bins, counts the number of respondents in each bin, and colors each bin in proportion to its count. End of explanation # Solution goes here heights = Jitter(df.htm3, 1.4) weights = Jitter(df.wtkg2, 1) thinkplot.Scatter(heights, weights, alpha=0.05, s=2) thinkplot.Config(axis=[135, 205, 25, 210]) Explanation: In this case the binned plot does a pretty good job of showing the location and shape of the distribution. It obscures the row and column effects, which may or may not be a good thing. Exercise: So far we have been working with a subset of only 5000 respondents. When we include the entire dataset, making an effective scatterplot can be tricky. As an exercise, experiment with Scatter and HexBin to make a plot that represents the entire dataset well. End of explanation cleaned = df.dropna(subset=['htm3', 'wtkg2']) Explanation: Plotting percentiles Sometimes a better way to get a sense of the relationship between variables is to divide the dataset into groups using one variable, and then plot percentiles of the other variable. First I'll drop any rows that are missing height or weight. End of explanation bins = np.arange(135, 210, 5) indices = np.digitize(cleaned.htm3, bins) groups = cleaned.groupby(indices) Explanation: Then I'll divide the dataset into groups by height. End of explanation for i, group in groups: print(i, len(group)) Explanation: Here are the number of respondents in each group: End of explanation mean_heights = [group.htm3.mean() for i, group in groups] cdfs = [thinkstats2.Cdf(group.wtkg2) for i, group in groups] Explanation: Now we can compute the CDF of weight within each group. End of explanation for percent in [75, 50, 25]: weight_percentiles = [cdf.Percentile(percent) for cdf in cdfs] label = '%dth' % percent thinkplot.Plot(mean_heights, weight_percentiles, label=label) thinkplot.Config(xlabel='Height (cm)', ylabel='Weight (kg)', axis=[140, 210, 20, 200], legend=False) Explanation: And then extract the 25th, 50th, and 75th percentile from each group. End of explanation # Solution goes here cleaned.head() bins = np.arange(140, 210, 10) indices = np.digitize(cleaned.htm3, bins) groups = cleaned.groupby(indices) cdfs = [thinkstats2.Cdf(group.wtkg2) for i, group in groups] thinkplot.Cdfs(cdfs) thinkplot.Config(xlabel='weight', ylabel='cdf') Explanation: Exercise: Yet another option is to divide the dataset into groups and then plot the CDF for each group. As an exercise, divide the dataset into a smaller number of groups and plot the CDF for each group. End of explanation def Cov(xs, ys, meanx=None, meany=None): xs = np.asarray(xs) ys = np.asarray(ys) if meanx is None: meanx = np.mean(xs) if meany is None: meany = np.mean(ys) cov = np.dot(xs-meanx, ys-meany) / len(xs) return cov Explanation: Correlation The following function computes the covariance of two variables using NumPy's dot function. End of explanation heights, weights = cleaned.htm3, cleaned.wtkg2 Cov(heights, weights) Explanation: And here's an example: End of explanation def Corr(xs, ys): xs = np.asarray(xs) ys = np.asarray(ys) meanx, varx = thinkstats2.MeanVar(xs) meany, vary = thinkstats2.MeanVar(ys) corr = Cov(xs, ys, meanx, meany) / np.sqrt(varx * vary) return corr Explanation: Covariance is useful for some calculations, but it doesn't mean much by itself. The coefficient of correlation is a standardized version of covariance that is easier to interpret. End of explanation Corr(heights, weights) Explanation: The correlation of height and weight is about 0.51, which is a moderately strong correlation. End of explanation np.corrcoef(heights, weights) Explanation: NumPy provides a function that computes correlations, too: End of explanation import pandas as pd def SpearmanCorr(xs, ys): xranks = pd.Series(xs).rank() yranks = pd.Series(ys).rank() return Corr(xranks, yranks) Explanation: The result is a matrix with self-correlations on the diagonal (which are always 1), and cross-correlations on the off-diagonals (which are always symmetric). Pearson's correlation is not robust in the presence of outliers, and it tends to underestimate the strength of non-linear relationships. Spearman's correlation is more robust, and it can handle non-linear relationships as long as they are monotonic. Here's a function that computes Spearman's correlation: End of explanation SpearmanCorr(heights, weights) Explanation: For heights and weights, Spearman's correlation is a little higher: End of explanation def SpearmanCorr(xs, ys): xs = pd.Series(xs) ys = pd.Series(ys) return xs.corr(ys, method='spearman') Explanation: A Pandas Series provides a method that computes correlations, and it offers spearman as one of the options. End of explanation SpearmanCorr(heights, weights) Explanation: The result is the same as for the one we wrote. End of explanation Corr(cleaned.htm3, np.log(cleaned.wtkg2)) Explanation: An alternative to Spearman's correlation is to transform one or both of the variables in a way that makes the relationship closer to linear, and the compute Pearson's correlation. End of explanation import first live, firsts, others = first.MakeFrames() live = live.dropna(subset=['agepreg', 'totalwgt_lb']) # Solution goes here mom_age = live.agepreg weight = live.totalwgt_lb thinkplot.Scatter(mom_age, weight) thinkplot.Config(xlabel='mom\'s age', ylabel='birthweight') # Solution goes here print('correlation', Corr(mom_age, weight)) print('spearman', SpearmanCorr(mom_age, weight)) # Solution goes here # Solution goes here Explanation: Exercises Using data from the NSFG, make a scatter plot of birth weight versus mother’s age. Plot percentiles of birth weight versus mother’s age. Compute Pearson’s and Spearman’s correlations. How would you characterize the relationship between these variables? End of explanation
7,313
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Landice MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify document publication status Step4: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Software Properties 3. Grid 4. Glaciers 5. Ice 6. Ice --&gt; Mass Balance 7. Ice --&gt; Mass Balance --&gt; Basal 8. Ice --&gt; Mass Balance --&gt; Frontal 9. Ice --&gt; Dynamics 1. Key Properties Land ice key properties 1.1. Overview Is Required Step5: 1.2. Model Name Is Required Step6: 1.3. Ice Albedo Is Required Step7: 1.4. Atmospheric Coupling Variables Is Required Step8: 1.5. Oceanic Coupling Variables Is Required Step9: 1.6. Prognostic Variables Is Required Step10: 2. Key Properties --&gt; Software Properties Software properties of land ice code 2.1. Repository Is Required Step11: 2.2. Code Version Is Required Step12: 2.3. Code Languages Is Required Step13: 3. Grid Land ice grid 3.1. Overview Is Required Step14: 3.2. Adaptive Grid Is Required Step15: 3.3. Base Resolution Is Required Step16: 3.4. Resolution Limit Is Required Step17: 3.5. Projection Is Required Step18: 4. Glaciers Land ice glaciers 4.1. Overview Is Required Step19: 4.2. Description Is Required Step20: 4.3. Dynamic Areal Extent Is Required Step21: 5. Ice Ice sheet and ice shelf 5.1. Overview Is Required Step22: 5.2. Grounding Line Method Is Required Step23: 5.3. Ice Sheet Is Required Step24: 5.4. Ice Shelf Is Required Step25: 6. Ice --&gt; Mass Balance Description of the surface mass balance treatment 6.1. Surface Mass Balance Is Required Step26: 7. Ice --&gt; Mass Balance --&gt; Basal Description of basal melting 7.1. Bedrock Is Required Step27: 7.2. Ocean Is Required Step28: 8. Ice --&gt; Mass Balance --&gt; Frontal Description of claving/melting from the ice shelf front 8.1. Calving Is Required Step29: 8.2. Melting Is Required Step30: 9. Ice --&gt; Dynamics ** 9.1. Description Is Required Step31: 9.2. Approximation Is Required Step32: 9.3. Adaptive Timestep Is Required Step33: 9.4. Timestep Is Required
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'noaa-gfdl', 'gfdl-am4', 'landice') Explanation: ES-DOC CMIP6 Model Properties - Landice MIP Era: CMIP6 Institute: NOAA-GFDL Source ID: GFDL-AM4 Topic: Landice Sub-Topics: Glaciers, Ice. Properties: 30 (21 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-20 15:02:34 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) Explanation: Document Authors Set document authors End of explanation # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) Explanation: Document Contributors Specify document contributors End of explanation # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) Explanation: Document Publication Specify document publication status End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Software Properties 3. Grid 4. Glaciers 5. Ice 6. Ice --&gt; Mass Balance 7. Ice --&gt; Mass Balance --&gt; Basal 8. Ice --&gt; Mass Balance --&gt; Frontal 9. Ice --&gt; Dynamics 1. Key Properties Land ice key properties 1.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of land surface model. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of land surface model code End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.ice_albedo') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "prescribed" # "function of ice age" # "function of ice density" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 1.3. Ice Albedo Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Specify how ice albedo is modelled End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.atmospheric_coupling_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.4. Atmospheric Coupling Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Which variables are passed between the atmosphere and ice (e.g. orography, ice mass) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.oceanic_coupling_variables') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.5. Oceanic Coupling Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Which variables are passed between the ocean and ice End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "ice velocity" # "ice thickness" # "ice temperature" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 1.6. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Which variables are prognostically calculated in the ice model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.software_properties.repository') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 2. Key Properties --&gt; Software Properties Software properties of land ice code 2.1. Repository Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Location of code for this component. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.software_properties.code_version') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 2.2. Code Version Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Code version identifier. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.key_properties.software_properties.code_languages') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 2.3. Code Languages Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Code language(s). End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 3. Grid Land ice grid 3.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of the grid in the land ice scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.adaptive_grid') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 3.2. Adaptive Grid Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is an adative grid being used? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.base_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 3.3. Base Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The base resolution (in metres), before any adaption End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.resolution_limit') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 3.4. Resolution Limit Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If an adaptive grid is being used, what is the limit of the resolution (in metres) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.grid.projection') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 3.5. Projection Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 The projection of the land ice grid (e.g. albers_equal_area) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.glaciers.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 4. Glaciers Land ice glaciers 4.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of glaciers in the land ice scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.glaciers.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 4.2. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe the treatment of glaciers, if any End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.glaciers.dynamic_areal_extent') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 4.3. Dynamic Areal Extent Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Does the model include a dynamic glacial extent? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 5. Ice Ice sheet and ice shelf 5.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of the ice sheet and ice shelf in the land ice scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.grounding_line_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "grounding line prescribed" # "flux prescribed (Schoof)" # "fixed grid size" # "moving grid" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 5.2. Grounding Line Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Specify the technique used for modelling the grounding line in the ice sheet-ice shelf coupling End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.ice_sheet') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 5.3. Ice Sheet Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Are ice sheets simulated? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.ice_shelf') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 5.4. Ice Shelf Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Are ice shelves simulated? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.surface_mass_balance') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6. Ice --&gt; Mass Balance Description of the surface mass balance treatment 6.1. Surface Mass Balance Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how and where the surface mass balance (SMB) is calulated. Include the temporal coupling frequeny from the atmosphere, whether or not a seperate SMB model is used, and if so details of this model, such as its resolution End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.basal.bedrock') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 7. Ice --&gt; Mass Balance --&gt; Basal Description of basal melting 7.1. Bedrock Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the implementation of basal melting over bedrock End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.basal.ocean') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 7.2. Ocean Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the implementation of basal melting over the ocean End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.frontal.calving') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8. Ice --&gt; Mass Balance --&gt; Frontal Description of claving/melting from the ice shelf front 8.1. Calving Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the implementation of calving from the front of the ice shelf End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.mass_balance.frontal.melting') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8.2. Melting Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe the implementation of melting from the front of the ice shelf End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.description') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9. Ice --&gt; Dynamics ** 9.1. Description Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 General description if ice sheet and ice shelf dynamics End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.approximation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "SIA" # "SAA" # "full stokes" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 9.2. Approximation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Approximation type used in modelling ice dynamics End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.adaptive_timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 9.3. Adaptive Timestep Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there an adaptive time scheme for the ice scheme? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.landice.ice.dynamics.timestep') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 9.4. Timestep Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestep (in seconds) of the ice scheme. If the timestep is adaptive, then state a representative timestep. End of explanation
7,314
Given the following text description, write Python code to implement the functionality described below step by step Description: 4 ways to print in GAlgebra Step1: Printing in plain text Step2: Enhanced Console Printing If called Eprint() upfront, print() will do Enhanced Console Printing(colored printing with ANSI escape sequences) Step3: MathJax printing in Jupyter Notebook In a Jupyter Notebook upfront, without calling print(), it will do LaTeX printing with MathJax for Geometric Algebra expressions. code & output Step4: LaTeX printing If called Format() upfront and xpdf() eventually, print() will do LaTeX printing (internally, the standard output will be redirected to a buffer for later consumption). code
Python Code: from sympy import * from galgebra.ga import Ga from galgebra.printer import Eprint, Format, xpdf cga3d = Ga(r'e_1 e_2 e_3 e e_{0}',g='1 0 0 0 0,0 1 0 0 0,0 0 1 0 0,0 0 0 0 -1,0 0 0 -1 0') Explanation: 4 ways to print in GAlgebra End of explanation print(cga3d.I()) Explanation: Printing in plain text End of explanation !python -c "from galgebra.ga import Ga;from galgebra.printer import Eprint;Eprint();cga3d = Ga(r'e_1 e_2 e_3 e e_{0}',g='1 0 0 0 0,0 1 0 0 0,0 0 1 0 0,0 0 0 0 -1,0 0 0 -1 0');print(cga3d.I())" Explanation: Enhanced Console Printing If called Eprint() upfront, print() will do Enhanced Console Printing(colored printing with ANSI escape sequences): code: https://github.com/pygae/galgebra/blob/master/examples/Terminal/terminal_check.py output: https://nbviewer.jupyter.org/github/pygae/galgebra/blob/master/examples/ipython/Terminal.ipynb End of explanation cga3d.I() Explanation: MathJax printing in Jupyter Notebook In a Jupyter Notebook upfront, without calling print(), it will do LaTeX printing with MathJax for Geometric Algebra expressions. code & output: https://nbviewer.jupyter.org/github/pygae/galgebra/blob/master/examples/ipython/colored_christoffel_symbols.ipynb End of explanation Format() print(cga3d.I()) xpdf(filename='test_latex_output.tex',paper=(9,10),pdfprog=None) !cat test_latex_output.tex Explanation: LaTeX printing If called Format() upfront and xpdf() eventually, print() will do LaTeX printing (internally, the standard output will be redirected to a buffer for later consumption). code: https://github.com/pygae/galgebra/blob/master/examples/LaTeX/colored_christoffel_symbols.py output: https://nbviewer.jupyter.org/github/pygae/galgebra/blob/master/examples/ipython/LaTeX.ipynb End of explanation
7,315
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create Text Data Step2: Create Bag Of Words Step3: Create Target Vector Step4: Train Multinomial Naive Bayes Classifier Step5: Create Previously Unseen Observation Step6: Predict Observation's Class
Python Code: # Load libraries import numpy as np from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer Explanation: Title: Multinomial Naive Bayes Classifier Slug: multinomial_naive_bayes_classifier Summary: How to train a Multinomial naive bayes classifer in Scikit-Learn Date: 2017-09-22 12:00 Category: Machine Learning Tags: Naive Bayes Authors: Chris Albon Multinomial naive Bayes works similar to Gaussian naive Bayes, however the features are assumed to be multinomially distributed. In practice, this means that this classifier is commonly used when we have discrete data (e.g. movie ratings ranging 1 and 5). Preliminaries End of explanation # Create text text_data = np.array(['I love Brazil. Brazil!', 'Brazil is best', 'Germany beats both']) Explanation: Create Text Data End of explanation # Create bag of words count = CountVectorizer() bag_of_words = count.fit_transform(text_data) # Create feature matrix X = bag_of_words.toarray() Explanation: Create Bag Of Words End of explanation # Create target vector y = np.array([0,0,1]) Explanation: Create Target Vector End of explanation # Create multinomial naive Bayes object with prior probabilities of each class clf = MultinomialNB(class_prior=[0.25, 0.5]) # Train model model = clf.fit(X, y) Explanation: Train Multinomial Naive Bayes Classifier End of explanation # Create new observation new_observation = [[0, 0, 0, 1, 0, 1, 0]] Explanation: Create Previously Unseen Observation End of explanation # Predict new observation's class model.predict(new_observation) Explanation: Predict Observation's Class End of explanation
7,316
Given the following text description, write Python code to implement the functionality described below step by step Description: Configurar las credenciales para acceder al API de Twitter Step1: Esta es la molona librería que vamos a utilizar Step2: 1 . Recoger tweets a partir de un id Step3: 2. Recoger tweets de una usuaria Step4: 3. Recoger tweets a partir de una consulta
Python Code: config = ConfigParser() config.read(join(pardir,'src','credentials.ini')) APP_KEY = config['twitter']['app_key'] APP_SECRET = config['twitter']['app_secret'] OAUTH_TOKEN = config['twitter']['oauth_token'] OAUTH_TOKEN_SECRET = config['twitter']['oauth_token_secret'] from twitter import oauth, Twitter, TwitterHTTPError Explanation: Configurar las credenciales para acceder al API de Twitter End of explanation auth = oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET, APP_KEY, APP_SECRET) twitter_api = Twitter(auth=auth) twitter_api.retry = True Explanation: Esta es la molona librería que vamos a utilizar: https://github.com/sixohsix/twitter/tree/master End of explanation tweet = twitter_api.statuses.show(_id='628949369883000832') tweet['text'] Explanation: 1 . Recoger tweets a partir de un id End of explanation femfreq_tweet_search = twitter_api.statuses.user_timeline(screen_name="femfreq", count=100) femfreq_tweet_search[0]['user']['description'] femfreq_tweet_search[-1]['text'] Explanation: 2. Recoger tweets de una usuaria End of explanation tweets = twitter_api.search.tweets(q="#feminazi", count=100) tweets['search_metadata'] import pandas as pd text_gathered = [tweet_data['text'] for tweet_data in tweets['statuses']] num_tweets = len(text_gathered) pd_tweets = pd.DataFrame( {'tweet_text': text_gathered, 'troll_tag': [False] * num_tweets}) pd_tweets.head() pd_tweets.to_csv('maybe_troll.csv') ls Explanation: 3. Recoger tweets a partir de una consulta End of explanation
7,317
Given the following text description, write Python code to implement the functionality described below step by step Description: ANÁLISIS ESTADÍSTICO DE DATOS Step1: PARA RECORDAR Distribución binomial Se denomina proceso de Bernoulli aquel experimento que consiste en repetir n veces una prueba, cada una independiente, donde el resultado se clasifica como éxito o fracaso (excluyente). La probabilidad de éxito se denota por $p$. Se define la $\textbf{variable aleatoria binomial}$ como la función que dá el número de éxitos en un proceso de Bernoulli. La variable aleatoria $X$ tomará valores $X = {0,1,2,...,n}$ para un experimento con n pruebas. La distribución binomial (distribución de probabilidad) se representa como Step2: Usando la función binom de python podemos graficar la función de distribución binomial para este caso. Step3: $\textbf{FIGURA 1.}$ Distribución binomial para el ejemplo. Efectivamente, se obtuvo la misma probabilidad. Note que si se desconoce la probabilidad $p$ esta se puede determinar si se conoce que la distribución es binomial. Una vez se tiene la probabilidad de éxito se pueden determinar las probabilidades para cualquier cantidad de pruebas. La distribución binomial es de gran utilidad en campos científicos como el control de calidad y las aplicaciones médicas. Distribución de Poisson En un experimento aleatorio en el que se busque medir el número de sucesos o resultados de un tipo que ocurren en un intervalo continuo (número de fotones que llegan a un detector en intervalos de tiempo iguales, número de estrellas en cuadrículas idénticas en el cielo, número de fotones en un modo en un oscilador mecánico cuántico, energía total en un oscilador armónico mecánico cuántico), se le conocerá como proceso de Poisson, y deberá cumplir las siguientes reglas Step4: $\textbf{FIGURA 2.}$ Galaxias en el espacio profundo. Step5: Si decimos que la distribución que se determinó en el paso anterior es una distribución de Poisson (suposición), podemos decir cosas como Step6: Comparemos ahora la distribución obtenida con la correspondiente distribución de Poisson Step7: $\textbf{FIGURA 3.}$ Distribución de Poisson ideal con respecto a la generada por los datos. Finalmente observemos como la distribución de Poisson tiende a la forma de una distribución normal.
Python Code: dado = np.array([5, 3, 3, 2, 5, 1, 2, 3, 6, 2, 1, 3, 6, 6, 2, 2, 5, 6, 4, 2, 1, 3, 4, 2, 2, 5, 3, 3, 2, 2, 2, 1, 6, 2, 2, 6, 1, 3, 3, 3, 4, 4, 6, 6, 1, 2, 2, 6, 1, 4, 2, 5, 3, 6, 6, 3, 5, 2, 2, 4, 2, 2, 4, 4, 3, 3, 1, 2, 6, 1, 3, 3, 5, 4, 6, 6, 4, 2, 5, 6, 1, 4, 5, 4, 3, 5, 4, 1, 4, 6, 6, 6, 3, 1, 5, 6, 4, 3, 4, 6, 3, 5, 2, 6, 3, 6, 1, 4, 3, 4, 1]) suma = np.array([8, 5, 6, 5, 8, 4, 12, 4, 11, 6, 4, 6, 7, 6, 4, 3, 8, 8, 4, 6, 8, 12, 3, 8, 5, 7, 9, 9, 7, 6, 4, 8, 6, 3, 7, 6, 9, 12, 6, 11, 5, 9, 8, 5, 10, 12, 4, 11, 7, 10, 8, 8, 9, 7, 7, 5]) prob = 10./36 # probabilidad de sacar una suma inferior a 6 #prob = 6./21 # probabilidad de sacar una suma inferior a 6 #np.where(suma[0:8]<6) Explanation: ANÁLISIS ESTADÍSTICO DE DATOS: Distribuciones discretas Material en construcción, no ha sido revisado por pares. Última revisión: agosto 2016, Edgar Rueda Referencias bibliográficas García, F. J. G., López, N. C., & Calvo, J. Z. (2009). Estadística básica para estudiantes de ciencias. Squires, G. L. (2001). Practical physics. Cambridge university press. Conjunto de datos Para esta sección haremos uso de dos conjuntos de datos, el primero se obtiene a partir del lanzamiento de un dado. El segundo conjunto corresponde a la suma de los dados por cada lanzamiento (se lanzan dos dados al mismo tiempo). End of explanation mediaS = suma.size*prob # media de la distribución binomial devS = np.sqrt(suma.size*prob*(1.-prob)) # desviación estándar de la distribución binomial real = np.where(suma<6) # where entrega la info en un tuple de una posición donde está el array real = real[0] # extraemos la información del tuple en la posición uno y la guardamos en real duda = 16 # x, número de éxitos cuya probabilidad se quiere conocer Prob = 0 # probabilidad de tener un número de éxitos inferior o igual a duda for cont in range(0,duda): Prob = Prob + (math.factorial(suma.size)/(math.factorial(cont)*math.factorial(suma.size - cont))) \ *prob**cont*(1.-prob)**(suma.size-cont) print('La probabilidad de que la suma sea inferior a 6 es %.2f' % prob) print('Número total de pruebas igual a %d' % suma.size) print('Suma promedio igual a %.1f' %mediaS) print('Desviación estándar de la suma = %.1f' % devS) print('Número de veces que suma menos de 6 en la muestra es %.1f' % real.size) print('La probabilidad de que el número de éxitos en una muestra de %d sea \ inferior o igual a %d, donde el éxito es que la suma sea inferior a 6, es %.4f' %(suma.size,duda,Prob)) Explanation: PARA RECORDAR Distribución binomial Se denomina proceso de Bernoulli aquel experimento que consiste en repetir n veces una prueba, cada una independiente, donde el resultado se clasifica como éxito o fracaso (excluyente). La probabilidad de éxito se denota por $p$. Se define la $\textbf{variable aleatoria binomial}$ como la función que dá el número de éxitos en un proceso de Bernoulli. La variable aleatoria $X$ tomará valores $X = {0,1,2,...,n}$ para un experimento con n pruebas. La distribución binomial (distribución de probabilidad) se representa como: $$f(x) = P(X = x) = b(x;n,p)$$ Note que para calcular la probabilidad, debido a la independiencia de las pruebas, basta con multiplicar la probabilidad de los éxitos por la probabilidad de los fracasos, $p^x q^{n-x}$, y este valor multiplicarlo por el número posible de disposiciones en los que salgan los éxitos (permutaciones), $$b(x;n,p) = \frac{n!}{x!(n-x)!}p^x q^{n-x}$$ La probabilidad de que $X$ sea menor a un valor $x$ determinado es: $$P(X \leq x) = B(x;n,p) = \sum_{r = 0}^x b(r;n,p)$$ La media es $\mu = np$ y la desviación estándar es $\sigma = \sqrt{npq}$ donde $q = 1 - p$. Una propiedad importante de la distribución binomial es que será simétrica si $p=q$, y con asimetría a la derecha cuando $p<q$. Del conjunto de datos que se obtienen de la suma de dos dados, tenemos: End of explanation n = suma.size p = prob x = np.arange(0,30) histB = stats.binom.pmf(x, n, p) plt.figure(1) plt.rcParams['figure.figsize'] = 20, 6 # para modificar el tamaño de la figura plt.plot(x, histB, 'bo', ms=8, label='Distribucion binomial') plt.xlabel('Numero de exitos') plt.ylabel('Probabilidad') ProbB = np.sum(histB[0:duda]) print('Probabilidad de que en solo %d ocasiones la suma sea inferior a 6 es %.4f' %(duda,ProbB)) Explanation: Usando la función binom de python podemos graficar la función de distribución binomial para este caso. End of explanation Ima = misc.imread('HDF-bw.jpg') # Se lee la imagen como matriz en escala de 8 bit plt.rcParams['figure.figsize'] = 20, 6 # para modificar el tamaño de la figura Imab = Ima[100:500,100:700,1] # La imagen original tenía tres canales (RGB); se elige un canal y se recorta plt.figure(2) plt.imshow(Imab, cmap='gray') Explanation: $\textbf{FIGURA 1.}$ Distribución binomial para el ejemplo. Efectivamente, se obtuvo la misma probabilidad. Note que si se desconoce la probabilidad $p$ esta se puede determinar si se conoce que la distribución es binomial. Una vez se tiene la probabilidad de éxito se pueden determinar las probabilidades para cualquier cantidad de pruebas. La distribución binomial es de gran utilidad en campos científicos como el control de calidad y las aplicaciones médicas. Distribución de Poisson En un experimento aleatorio en el que se busque medir el número de sucesos o resultados de un tipo que ocurren en un intervalo continuo (número de fotones que llegan a un detector en intervalos de tiempo iguales, número de estrellas en cuadrículas idénticas en el cielo, número de fotones en un modo en un oscilador mecánico cuántico, energía total en un oscilador armónico mecánico cuántico), se le conocerá como proceso de Poisson, y deberá cumplir las siguientes reglas: Los resultados de cada intervalo son independientes. La probabilidad de que un resultado ocurra en un intervalo pequeño es proporcional al tamaño del intervalo. La probabilidad es constante por lo que se puede definir un valor medio de resultados por unidad de intervalo. El proceso es estable. La probabilidad de que ocurra más de un resultado en un intervalo lo suficientemente pequeño es despreciable. El intervalo es tán pequeño que a lo sumo se espera solo un suceso (resultado). La distribución de Poisson es un caso límite de la distribución binomial cuando el número de eventos $N$ tiende a infinito y la probabilidad de acierto $p$ tiende a cero (ver libro de Squire para la deducción). La $\textbf{variable aleatoria de Poisson}$ se define como el número de resultados que aparecen en un experimento que sigue el proceso de Poisson. La distribución de probabilidad asociada se denomina distribución de Poisson y depende solo del parámetro medio de resultados $\lambda$. $$X = (0,1,2,...)$$ $$f(x) = P(X=x) = p(x;\lambda)$$ La expresión para la distribución se obtiene a partir de la binomial (mirar libro de Garcia): $$p(x;\lambda) = \frac{\lambda^x}{x!} e^{- \lambda}$$ con media $\lambda$ y desviación estándar $\sqrt{\lambda}$. End of explanation plt.rcParams['figure.figsize'] = 18, 15 # para modificar el tamaño de la figura fil, col = Imab.shape # número de filas y columnas de la imagen numlado = 7 # Número de imágenes por lado contar = 1 plt.figure(5) for enfil in range(1,numlado+1): for encol in range(1,numlado+1): plt.subplot(numlado,numlado,contar) plt.imshow(Imab[(enfil-1)*np.int(fil/numlado):enfil*np.int(fil/numlado), \ (encol-1)*np.int(col/numlado):encol*np.int(col/numlado)],cmap='gray') frame1 = plt.gca() frame1.axes.get_yaxis().set_visible(False) frame1.axes.get_xaxis().set_visible(False) contar = contar + 1 # Para el caso de 7x7 imágenes en gal se presentan el número de galaxias contadas gal = np.array([2., 3., 6., 5., 4., 9., 10., \ 2., 3., 7., 1., 3., 1., 6., \ 6., 5., 4., 3., 4., 2., 4., \ 4., 6., 3., 3., 4., 3., 2., \ 5., 4., 2., 2., 6., 5., 9., \ 4., 7., 2., 3., 3., 3., 5., \ 6., 3., 4., 7., 4., 6., 7.]) la = np.mean(gal) # Valor promedio del conjunto de datos # Distribución del conjunto de datos. La primera fila es el número de galaxias, la segunda es el número de veces que # se repite dicho número de galaxias distriGal = np.array([[0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.],[0., 1., 8., 11., 10., 5., 6., 4., 0., 2., 1.]]) print('Valor promedio del conjunto de datos = %.2f' % la) plt.figure(figsize=(16,9)) plt.plot(distriGal[0,:],distriGal[1,:]/gal.size,'r*',ms=10,label='Distribución datos con promedio %.1f' % la) plt.legend() plt.xlabel('Número de galaxias en el intervalo') plt.ylabel('Rata de ocurrencia') plt.grid() Explanation: $\textbf{FIGURA 2.}$ Galaxias en el espacio profundo. End of explanation num = 2. # Número de galaxias que se espera encontrar prob = (la**num*np.exp(-la)/math.factorial(num))*100 # Probabilidad de encontrar dicho número de galaxias x = np.arange(0,20) # rango de datos: número de galaxias histP = stats.poisson.pmf(x, la) # función de probabilidad de Poisson ProbP = (np.sum(histP[0:int(num)+1]))*100 # Probabilidad acumulada print('Promedio de galaxias en el área estudiada = %.2f' % la) print('La probabilidad de que se observe en la imagen del espacio profundo %d galaxias es = %.1f%%' % (num,prob)) print('Probabilidad de observar hasta %d galaxias = %.1f%%' %(num,ProbP)) Explanation: Si decimos que la distribución que se determinó en el paso anterior es una distribución de Poisson (suposición), podemos decir cosas como: End of explanation plt.figure(figsize=(16,9)) plt.plot(x, histP, 'bo', ms=8, label='Distribución de Poisson con $\lambda=$ %.1f' % la) plt.plot(distriGal[0,:],distriGal[1,:]/gal.size,'r*',ms=10,label='Conjunto de datos con promedio %.1f' % la) plt.xlabel('Numero de galaxias (sucesos)') plt.ylabel('Rata de ocurrencia') plt.legend() plt.grid() Explanation: Comparemos ahora la distribución obtenida con la correspondiente distribución de Poisson: End of explanation plt.figure(4) plt.rcParams['figure.figsize'] = 12, 6 # para modificar el tamaño de la figura probP = np.zeros(20) for la in range(1,10,2): for num in range(0,20): probP[num] = la**num*np.exp(-la)/math.factorial(num) plt.plot(probP,marker='.',ms=15,label='$\lambda = %d$' %la) mu = la # media aritmética sigma = np.sqrt(la) # desviación estándar x = np.arange(0,20,1) f = (1./np.sqrt(2*np.pi*sigma**2))*np.exp(-(x-mu)**2/(2*sigma**2)) plt.plot(f,marker='*',ms=10,color='black',label='$ \overline{x} = %d , \ \sigma = %.1f$'%(mu,sigma)) plt.xlabel('Evento') plt.ylabel('Probabilidad') plt.legend() Explanation: $\textbf{FIGURA 3.}$ Distribución de Poisson ideal con respecto a la generada por los datos. Finalmente observemos como la distribución de Poisson tiende a la forma de una distribución normal. End of explanation
7,318
Given the following text description, write Python code to implement the functionality described below step by step Description: Groupby El metodo groupby nos permite agrupar informacion y aplicar funciones de agregacion Step1: Ahora ya podemos usar la funcion .groupby() para agrupar la informacion en base a los nombres de las columnas. Agrupemos la informacion por el nombre de la compania. Esto creara un objeto DataFrameGroupBy Step2: Este objeto lo podemos guardar como una nueva variable Step3: Y en seguida mandar llamar los metodos de agregacion Step4: Mas ejemplos de funciones
Python Code: #%% librerias import pandas as pd # Crear un dataFrame data = {'Company':['GOOG','GOOG','MSFT','MSFT','FB','FB'], 'Person':['Sam','Charlie','Amy','Vanessa','Carl','Sarah'], 'Sales':[200,120,340,124,243,350]} df = pd.DataFrame(data) df Explanation: Groupby El metodo groupby nos permite agrupar informacion y aplicar funciones de agregacion End of explanation df.groupby('Company') Explanation: Ahora ya podemos usar la funcion .groupby() para agrupar la informacion en base a los nombres de las columnas. Agrupemos la informacion por el nombre de la compania. Esto creara un objeto DataFrameGroupBy End of explanation by_comp = df.groupby("Company") Explanation: Este objeto lo podemos guardar como una nueva variable End of explanation by_comp.mean() df.groupby('Company').mean() Explanation: Y en seguida mandar llamar los metodos de agregacion End of explanation by_comp.std() by_comp.min() by_comp.max() by_comp.count() by_comp.describe() by_comp.describe().transpose() by_comp.describe().transpose()['GOOG'] Explanation: Mas ejemplos de funciones End of explanation
7,319
Given the following text description, write Python code to implement the functionality described below step by step Description: <div align="center"><img width="50%" src="https Step1: You can also run a cell with Ctrl+Enter or Shift+Enter. Experiment a bit with that. Tab Completion One of the most useful things about Jupyter Notebook is its tab completion. Try this Step2: After the first time, you should see this Step3: You should see this Step4: Writing code Writing code in the notebook is pretty normal. Step5: If you messed something up and want to revert to an older version of a code in a cell, use Ctrl+Z or to go than back Ctrl+Y. For a full list of all keyboard shortcuts, click on the small keyboard icon in the notebook header or click on Help &gt; Keyboard Shortcuts. Saving a Notebook Jupyter Notebooks autosave, so you don't have to worry about losing code too much. At the top of the page you can usually see the current save status Step6: Example 2 Let's use %%latex to render a block of latex
Python Code: import pandas as pd print("Hi! This is a cell. Click on it and press the ▶ button above to run it") Explanation: <div align="center"><img width="50%" src="https://raw.githubusercontent.com/jupyter/jupyter/master/docs/source/_static/_images/jupyter.png"></div> Jupyter Notebook This notebook was adapted from https://github.com/oesteban/biss2016 and is originally based on https://github.com/jvns/pandas-cookbook. Jupyter Notebook started as a web application, based on IPython that can run Python code directly in the webbrowser. Now, Jupyter Notebook can handle over 40 programming languages and is the interactive, open source web application to run any scientific code. You might also want to try a new Jupyter environment JupyterLab. How to run a cell First, we need to explain how to run cells. Try to run the cell below! End of explanation # NBVAL_SKIP # Use TAB completion for function info pd.read_csv( Explanation: You can also run a cell with Ctrl+Enter or Shift+Enter. Experiment a bit with that. Tab Completion One of the most useful things about Jupyter Notebook is its tab completion. Try this: click just after read_csv( in the cell below and press Shift+Tab 4 times, slowly. Note that if you're using JupyterLab you don't have an additional help box option. End of explanation # NBVAL_SKIP # Use TAB completion to see possible function names pd.r Explanation: After the first time, you should see this: After the second time: After the fourth time, a big help box should pop up at the bottom of the screen, with the full documentation for the read_csv function: I find this amazingly useful. I think of this as "the more confused I am, the more times I should press Shift+Tab". Okay, let's try tab completion for function names! End of explanation pd.read_csv? Explanation: You should see this: Get Help There's an additional way on how you can reach the help box shown above after the fourth Shift+Tab press. Instead, you can also use obj? or obj?? to get help or more help for an object. End of explanation def print_10_nums(): for i in range(10): print(i) print_10_nums() Explanation: Writing code Writing code in the notebook is pretty normal. End of explanation %time result = sum([x for x in range(10**6)]) Explanation: If you messed something up and want to revert to an older version of a code in a cell, use Ctrl+Z or to go than back Ctrl+Y. For a full list of all keyboard shortcuts, click on the small keyboard icon in the notebook header or click on Help &gt; Keyboard Shortcuts. Saving a Notebook Jupyter Notebooks autosave, so you don't have to worry about losing code too much. At the top of the page you can usually see the current save status: Last Checkpoint: 2 minutes ago (unsaved changes) Last Checkpoint: a few seconds ago (autosaved) If you want to save a notebook on purpose, either click on File &gt; Save and Checkpoint or press Ctrl+S. Magic functions IPython has all kinds of magic functions. Magic functions are prefixed by % or %%, and typically take their arguments without parentheses, quotes or even commas for convenience. Line magics take a single % and cell magics are prefixed with two %%. Some useful magic functions are: Magic Name | Effect ---------- | ------------------------------------------------------------- %env | Get, set, or list environment variables %pdb | Control the automatic calling of the pdb interactive debugger %pylab | Load numpy and matplotlib to work interactively %%debug | Activates debugging mode in cell %%html | Render the cell as a block of HTML %%latex | Render the cell as a block of latex %%sh | %%sh script magic %%time | Time execution of a Python statement or expression You can run %magic to get a list of magic functions or %quickref for a reference sheet. Example 1 Let's see how long a specific command takes with %time or %%time: End of explanation %%latex $$F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} \mathrm{d} x$$ Explanation: Example 2 Let's use %%latex to render a block of latex End of explanation
7,320
Given the following text description, write Python code to implement the functionality described below step by step Description: State Space Discretization From the previous notebook you probably end up thinking about the fact that the states and action we were dealing with on the Frozen Lake environment were discrete. It should upset you a bit, there is really not much we can do with that? But worry-not! This notebook will relax that constraint. We will look at what to do when the state space is continuous. We will keep actions discrete, but that's OK. For now, we'll look at a very simple way of dealing with continuous states. Step1: Q-Learning In the world we will be looking into this time, the Cart Pole example, we have 4 continous values to represent a state. An X position, change in X, acceleration and change in acceleration. Let's take a peek at a single observation Step2: Just as expected, a combination of 4 continuous variables make a state, and 2 discrete actions. Hmm, what to do? The actions are sort of the same as before, but the states are definitely different. We can't just create a Q table anymore... Let's look a little more into the the possible values these variables can take. We will explore for 100 episodes just to collect some sample data. You can see I force the algorithm to take the action 1 and action 0 for several consecutive timesteps. This is to make sure we explore the entire space and not just random. If we do random actions the cart would just jitter on the same place and the x axis would not get explored much. Stay with me, I'll show you. Step3: Let's visualize the values that each of the variables can take Step4: See? The x values seem to go from -1 to 1, changes in x from -2 to 2, etc. In fact, we can get the exact values from the env, although you could just sample a bunch of episodes and find out the limits yourself. Let's use the environments to keep focus. Step5: Not exactly the same as we thought. Can you think why? And, how to explore the state space throughout? Regardless, I will move forward trying to solve this environment. What we have above is good enough because it gives us the most commonly sampled observations for each of the variables. Cutting through these and boxing them is a process called discretization. It is basically a way to convert from continuous states to discrete. This would let us deal with the continous states nicely. Let's try it. Step6: I'm creating 4 states, anything left/right of each of the dots represent a unique state. Let's do the same for the variable 'change in x' or xd Step7: And for the acceleration variable Step8: Finally, the 'change in acceleration' Step9: Now, we use a function called 'digitize' which basically creates the buckets as mentioned above. Step10: For example, look at the acceleration variable. We go from -0.16 to 0.16 with equally spaced chunks. What would you expect a value of -0.99 fall into? Which bucket? Step11: Right. Bucket 0. How about a value of 0. If -0.99, which is less than -0.16 (the first bucket) falls into the first bucket, what do you think 0 would fall into? Step12: That was actually a tricky question. Digitize default to the 'left' if the value is equal to any of the buckets. How about a value slightly less than zero then? What bucket do you call? Step13: Right, 4 it is, how about a number slightly more than zero? Step14: Back to 5. Cool!! Let's look at the buckets next to each of the variables. Step15: Nice, how about we add the lower and upper boundaries we got before? Step16: Nice, you might not agree with the buckets I selected. That is OK, in fact I hope you don't, there seems to be a better way of manually selecting these buckets. You will get a chance at improving on this later. Let me give you a couple of functions that would make our algorithm work. Step17: Learning schedule is similar to what action_selection did for our previous notebooks. This time we are doing it with the alpha which is the learning rate and determines the importance and weight we give to newly calculated values in comparison with values we calculated in ealier iterations. Think about it like how much you trust your past knowledge. Intuitively, early in the exploration phase we don't know much of the environment, so perhaps that is an indication that we should rely on our previous calculation that much. But the more experience, the more should hold onto your knowledge. Now, remember this is also a 'dilemma' meaning there is a tradeoff and there is not a clear cut answer. Let's continue. We define action_selection just as before Step18: And this function, observation_to_state will take care of the discretazition. It will input a tuple of continuous values and give us an integer. Let's take a look Step19: Cool, right? Alright, I'll give you the new q_learning algorithm. Step20: You can see it, just like we did before, only differences are the use of the functions defined above and the collection of the alphas, epsilons, etc. This latter one is just to show you some stats and graphs, you could remove them and it would do just as well. Let's run this algorithm?! Shall we? Step22: Now, let's take a look at some of the episodes Step23: Interesting right? The last episode should show how the agent 'knows' what the goal of the environment, but perhaps not an impressive performance. Let's look into the value function and policy Step24: So, policy looks pretty much the same they looked before. This is because we "made" this environment discrete. Hold your thoughts... Let's close this environment and see how the agent did per OpenAI Gym. Step25: Not thaaaat well. The agent should have shown learning, but very likely it did not pass the environment. In other words, it learned, but definitely not a solid enough policy. Let's look at some of the things collected. Step26: See the learning rate goes from 0.8 to 0? Alright. Step27: Interesting exploration style. We force 100% exploration for few episodes, then to ~30% and then become greedy at about 150,000 episodes. Not bad. Could we do better? Step28: See some states not visited? That's a by product of the way we discretized the state space, it should not be a problem unless we have a very very large state space after discretization. Then, it might be beneficial tighting things up. How about the actions? Step30: Expected, I would say. If you want to balance a pole you will have to go left and right to keep the pole in place. Ok, so from these figures you should think about ways to make this algorithm work. Why things didn't work?? How can we make it learn more or better? I'll let you explore from now on... Your turn
Python Code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import tempfile import base64 import pprint import json import sys import gym import io from gym import wrappers from subprocess import check_output from IPython.display import HTML Explanation: State Space Discretization From the previous notebook you probably end up thinking about the fact that the states and action we were dealing with on the Frozen Lake environment were discrete. It should upset you a bit, there is really not much we can do with that? But worry-not! This notebook will relax that constraint. We will look at what to do when the state space is continuous. We will keep actions discrete, but that's OK. For now, we'll look at a very simple way of dealing with continuous states. End of explanation env = gym.make('CartPole-v0') observation = env.reset() actions = env.action_space env.close() print(observation) print(actions) Explanation: Q-Learning In the world we will be looking into this time, the Cart Pole example, we have 4 continous values to represent a state. An X position, change in X, acceleration and change in acceleration. Let's take a peek at a single observation: End of explanation observations = [] for episode in range(1000): observation = env.reset() for t in range(100): env.render() observations.append(observation) action = env.action_space.sample() if episode < 25: action = 1 elif episode < 50: action = 0 observation, reward, done, info = env.step(action) if done: print("Episode finished after {} timesteps".format(t+1)) break env.close() x_vals = np.array(observations)[:,0] xd_vals = np.array(observations)[:,1] a_vals = np.array(observations)[:,2] ad_vals = np.array(observations)[:,3] y = np.zeros_like(x_vals) Explanation: Just as expected, a combination of 4 continuous variables make a state, and 2 discrete actions. Hmm, what to do? The actions are sort of the same as before, but the states are definitely different. We can't just create a Q table anymore... Let's look a little more into the the possible values these variables can take. We will explore for 100 episodes just to collect some sample data. You can see I force the algorithm to take the action 1 and action 0 for several consecutive timesteps. This is to make sure we explore the entire space and not just random. If we do random actions the cart would just jitter on the same place and the x axis would not get explored much. Stay with me, I'll show you. End of explanation plt.plot(x_vals, y + 0.10, '.') plt.plot(xd_vals, y + 0.05, '.') plt.plot(a_vals, y - 0.05, '.') plt.plot(ad_vals, y - 0.10, '.') plt.ylim([-0.15, 0.15]) Explanation: Let's visualize the values that each of the variables can take: End of explanation x_thres = ((env.env.observation_space.low/2)[0], (env.env.observation_space.high/2)[0]) a_thres = ((env.env.observation_space.low/2)[2], (env.env.observation_space.high/2)[2]) print(x_thres, a_thres) Explanation: See? The x values seem to go from -1 to 1, changes in x from -2 to 2, etc. In fact, we can get the exact values from the env, although you could just sample a bunch of episodes and find out the limits yourself. Let's use the environments to keep focus. End of explanation x1 = np.linspace(x_thres[0] + .5, x_thres[1] - .5, 4, endpoint=False)[1:] y1 = np.zeros(len(x1)) + 0.05 plt.ylim([-0.075, 0.075]) plt.plot(x1, y1, 'o') plt.plot(x_vals, y, '.') Explanation: Not exactly the same as we thought. Can you think why? And, how to explore the state space throughout? Regardless, I will move forward trying to solve this environment. What we have above is good enough because it gives us the most commonly sampled observations for each of the variables. Cutting through these and boxing them is a process called discretization. It is basically a way to convert from continuous states to discrete. This would let us deal with the continous states nicely. Let's try it. End of explanation xd1 = np.sort(np.append(np.linspace(-1.5, 1.5, 4, endpoint=True), 0)) y1 = np.zeros(len(xd1)) + 0.05 plt.ylim([-0.075, 0.075]) plt.plot(xd1, y1, 'o') plt.plot(xd_vals, y, '.') Explanation: I'm creating 4 states, anything left/right of each of the dots represent a unique state. Let's do the same for the variable 'change in x' or xd: End of explanation a1 = np.sort(np.linspace(a_thres[0], a_thres[1], 10, endpoint=False)[1:]) y1 = np.zeros(len(a1)) + 0.05 plt.ylim([-0.1, 0.1]) plt.plot(a1, y1, 'o') plt.plot(a_vals, y, '.') Explanation: And for the acceleration variable: End of explanation all_vals = np.sort(np.append( (np.logspace(-7, 4, 6, endpoint=False, base=2)[1:], -np.logspace(-7, 4, 6, endpoint=False, base=2)[1:]), 0)) idxs = np.where(np.abs(all_vals) < 2) ad1 = all_vals[idxs] y1 = np.zeros(len(ad1)) + 0.05 plt.ylim([-0.075, 0.075]) plt.plot(ad1, y1, 'o') plt.plot(ad_vals, y, '.') Explanation: Finally, the 'change in acceleration': End of explanation a1 Explanation: Now, we use a function called 'digitize' which basically creates the buckets as mentioned above. End of explanation np.digitize(-0.99, a1) Explanation: For example, look at the acceleration variable. We go from -0.16 to 0.16 with equally spaced chunks. What would you expect a value of -0.99 fall into? Which bucket? End of explanation np.digitize(0, a1) Explanation: Right. Bucket 0. How about a value of 0. If -0.99, which is less than -0.16 (the first bucket) falls into the first bucket, what do you think 0 would fall into? End of explanation np.digitize(-0.0001, a1) Explanation: That was actually a tricky question. Digitize default to the 'left' if the value is equal to any of the buckets. How about a value slightly less than zero then? What bucket do you call? End of explanation np.digitize(0.0001, a1) Explanation: Right, 4 it is, how about a number slightly more than zero? End of explanation yx1 = np.zeros_like(x1) + 0.25 yx = np.zeros_like(x_vals) + 0.20 yxd1 = np.zeros_like(xd1) + 0.10 yxd = np.zeros_like(xd_vals) + 0.05 ya1 = np.zeros_like(a1) - 0.05 ya = np.zeros_like(a_vals) - 0.10 yad1 = np.zeros_like(ad1) - 0.20 yad = np.zeros_like(ad_vals) - 0.25 plt.ylim([-0.3, 0.3]) plt.plot(x1, yx1, '|') plt.plot(xd1, yxd1, '|') plt.plot(a1, ya1, '|') plt.plot(ad1, yad1, '|') plt.plot(x_vals, yx, '.') plt.plot(xd_vals, yxd, '.') plt.plot(a_vals, ya, '.') plt.plot(ad_vals, yad, '.') Explanation: Back to 5. Cool!! Let's look at the buckets next to each of the variables. End of explanation yx1 = np.zeros_like(x1) + 0.25 yx = np.zeros_like(x_vals) + 0.20 yxd1 = np.zeros_like(xd1) + 0.10 yxd = np.zeros_like(xd_vals) + 0.05 ya1 = np.zeros_like(a1) - 0.05 ya = np.zeros_like(a_vals) - 0.10 yad1 = np.zeros_like(ad1) - 0.20 yad = np.zeros_like(ad_vals) - 0.25 plt.plot(x1, yx1, '|') plt.plot(xd1, yxd1, '|') plt.plot(a1, ya1, '|') plt.plot(ad1, yad1, '|') plt.plot(x_vals, yx, '.') plt.plot(xd_vals, yxd, '.') plt.plot(a_vals, ya, '.') plt.plot(ad_vals, yad, '.') plt.ylim([-0.3, 0.3]) plt.plot((x_thres[0], x_thres[0]), (0.15, 0.25), 'k-', color='red') plt.plot((x_thres[1], x_thres[1]), (0.15, 0.25), 'k-', color='red') plt.plot((a_thres[0], a_thres[0]), (-0.05, -0.15), 'k-', color='red') plt.plot((a_thres[1], a_thres[1]), (-0.05, -0.15), 'k-', color='red') Explanation: Nice, how about we add the lower and upper boundaries we got before? End of explanation def learning_schedule(episode, n_episodes): return max(0., min(0.8, 1 - episode/n_episodes)) Explanation: Nice, you might not agree with the buckets I selected. That is OK, in fact I hope you don't, there seems to be a better way of manually selecting these buckets. You will get a chance at improving on this later. Let me give you a couple of functions that would make our algorithm work. End of explanation def action_selection(state, Q, episode, n_episodes): epsilon = 0.99 if episode < n_episodes//4 else 0.33 if episode < n_episodes//2 else 0. if np.random.random() < epsilon: action = np.random.randint(Q.shape[1]) else: action = np.argmax(Q[state]) return action, epsilon Explanation: Learning schedule is similar to what action_selection did for our previous notebooks. This time we are doing it with the alpha which is the learning rate and determines the importance and weight we give to newly calculated values in comparison with values we calculated in ealier iterations. Think about it like how much you trust your past knowledge. Intuitively, early in the exploration phase we don't know much of the environment, so perhaps that is an indication that we should rely on our previous calculation that much. But the more experience, the more should hold onto your knowledge. Now, remember this is also a 'dilemma' meaning there is a tradeoff and there is not a clear cut answer. Let's continue. We define action_selection just as before: End of explanation def observation_to_state(observation, bins): ss = [] for i in range(len(observation)): ss.append(int(np.digitize(observation[i], bins=bins[i]))) state = int("".join(map(lambda feature: str(int(feature)), ss))) return state sample_states = [[0.33, 0.2, 0.1, 0.], [-0.33, 0.2, 0.1, 0.], [0.33, -0.2, 0.1, 0.], [0.33, 0.2, -0.1, 0.], [0.33, 0.2, 0.1, .99]] for sample_state in sample_states: print(observation_to_state(sample_state, (x1, xd1, a1, ad1))) Explanation: And this function, observation_to_state will take care of the discretazition. It will input a tuple of continuous values and give us an integer. Let's take a look: End of explanation def q_learning(env, bins, gamma = 0.99): nS = 10 * 10 * 10 * 10 nA = env.env.action_space.n Q = np.random.random((nS, nA)) - 0.5 n_episodes = 5000 alphas = [] epsilons = [] states = [] actions = [] for episode in range(n_episodes): observation = env.reset() state = observation_to_state(observation, bins) done = False while not done: states.append(state) action, epsilon = action_selection(state, Q, episode, n_episodes) epsilons.append(epsilon) actions.append(action) observation, reward, done, info = env.step(action) nstate = observation_to_state(observation, bins) alpha = learning_schedule(episode, n_episodes) alphas.append(alpha) Q[state][action] += alpha * (reward + gamma * Q[nstate].max() * (not done) - Q[state][action]) state = nstate return Q, (alphas, epsilons, states, actions) Explanation: Cool, right? Alright, I'll give you the new q_learning algorithm. End of explanation mdir = tempfile.mkdtemp() env = gym.make('CartPole-v0') env = wrappers.Monitor(env, mdir, force=True) Q, stats = q_learning(env, (x1, xd1, a1, ad1)) Explanation: You can see it, just like we did before, only differences are the use of the functions defined above and the collection of the alphas, epsilons, etc. This latter one is just to show you some stats and graphs, you could remove them and it would do just as well. Let's run this algorithm?! Shall we? End of explanation videos = np.array(env.videos) n_videos = 3 idxs = np.linspace(0, len(videos) - 1, n_videos).astype(int) videos = videos[idxs,:] strm = '' for video_path, meta_path in videos: video = io.open(video_path, 'r+b').read() encoded = base64.b64encode(video) with open(meta_path) as data_file: meta = json.load(data_file) html_tag = <h2>{0}<h2/> <video width="960" height="540" controls> <source src="data:video/mp4;base64,{1}" type="video/mp4" /> </video> strm += html_tag.format('Episode ' + str(meta['episode_id']), encoded.decode('ascii')) HTML(data=strm) Explanation: Now, let's take a look at some of the episodes: End of explanation V = np.max(Q, axis=1) V V.max() pi = np.argmax(Q, axis=1) pi Explanation: Interesting right? The last episode should show how the agent 'knows' what the goal of the environment, but perhaps not an impressive performance. Let's look into the value function and policy: End of explanation env.close() gym.upload(mdir, api_key='<YOUR API KEY>') Explanation: So, policy looks pretty much the same they looked before. This is because we "made" this environment discrete. Hold your thoughts... Let's close this environment and see how the agent did per OpenAI Gym. End of explanation alphas, epsilons, states, actions = stats plt.plot(np.arange(len(alphas)), alphas, '.') plt.title('Alphas') plt.xlabel('Episode') plt.ylabel('Percentage') Explanation: Not thaaaat well. The agent should have shown learning, but very likely it did not pass the environment. In other words, it learned, but definitely not a solid enough policy. Let's look at some of the things collected. End of explanation plt.plot(np.arange(len(epsilons)), epsilons, '.') plt.title('Epsilon') plt.xlabel('Episode') plt.ylabel('Percentage') Explanation: See the learning rate goes from 0.8 to 0? Alright. End of explanation hist, bins = np.histogram(states, bins=50) width = 0.7 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 plt.bar(center, hist, align='center', width=width) plt.title('States Visited') plt.xlabel('State') plt.ylabel('Count') Explanation: Interesting exploration style. We force 100% exploration for few episodes, then to ~30% and then become greedy at about 150,000 episodes. Not bad. Could we do better? End of explanation hist, bins = np.histogram(actions, bins=3) width = 0.7 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 plt.bar(center, hist, align='center', width=width) plt.title('Actions Selected') plt.xlabel('Action') plt.ylabel('Count') Explanation: See some states not visited? That's a by product of the way we discretized the state space, it should not be a problem unless we have a very very large state space after discretization. Then, it might be beneficial tighting things up. How about the actions? End of explanation plt.plot(x_vals, y + 0.10, '.') plt.plot(xd_vals, y + 0.05, '.') plt.plot(a_vals, y - 0.05, '.') plt.plot(ad_vals, y - 0.10, '.') plt.ylim([-0.15, 0.15]) x1 = np.linspace(x_thres[0] + .5, x_thres[1] - .5, 2, endpoint=False)[1:] y1 = np.zeros(len(x1)) + 0.05 plt.ylim([-0.075, 0.075]) plt.plot(x1, y1, 'o') plt.plot(x_vals, y, '.') all_vals = np.sort(np.append( (np.logspace(-5, 4, 5, endpoint=False, base=2)[1:], -np.logspace(-5, 4, 5, endpoint=False, base=2)[1:]), 0)) idxs = np.where(np.abs(all_vals) < 2) xd1 = all_vals[idxs] y1 = np.zeros(len(xd1)) + 0.05 plt.ylim([-0.075, 0.075]) plt.plot(xd1, y1, 'o') plt.plot(xd_vals, y, '.') all_vals = np.sort(np.append( (np.logspace(-6, 0.01, 4, endpoint=False, base=2)[1:], -np.logspace(-6, 0.01, 4, endpoint=False, base=2)[1:]), 0)) idxs = np.where(np.abs(all_vals) < a_thres[1] - 0.1) a1 = all_vals[idxs] y1 = np.zeros(len(a1)) + 0.05 plt.ylim([-0.1, 0.1]) plt.plot(a1, y1, 'o') plt.plot(a_vals, y, '.') all_vals = np.sort(np.append( (np.logspace(-7, 4, 6, endpoint=False, base=2)[1:], -np.logspace(-7, 4, 6, endpoint=False, base=2)[1:]), 0)) idxs = np.where(np.abs(all_vals) < 2) ad1 = all_vals[idxs] y1 = np.zeros(len(ad1)) + 0.05 plt.ylim([-0.075, 0.075]) plt.plot(ad1, y1, 'o') plt.plot(ad_vals, y, '.') yx1 = np.zeros_like(x1) + 0.25 yx = np.zeros_like(x_vals) + 0.20 yxd1 = np.zeros_like(xd1) + 0.10 yxd = np.zeros_like(xd_vals) + 0.05 ya1 = np.zeros_like(a1) - 0.05 ya = np.zeros_like(a_vals) - 0.10 yad1 = np.zeros_like(ad1) - 0.20 yad = np.zeros_like(ad_vals) - 0.25 plt.ylim([-0.3, 0.3]) plt.plot(x1, yx1, '|') plt.plot(xd1, yxd1, '|') plt.plot(a1, ya1, '|') plt.plot(ad1, yad1, '|') plt.plot(x_vals, yx, '.') plt.plot(xd_vals, yxd, '.') plt.plot(a_vals, ya, '.') plt.plot(ad_vals, yad, '.') yx1 = np.zeros_like(x1) + 0.25 yx = np.zeros_like(x_vals) + 0.20 yxd1 = np.zeros_like(xd1) + 0.10 yxd = np.zeros_like(xd_vals) + 0.05 ya1 = np.zeros_like(a1) - 0.05 ya = np.zeros_like(a_vals) - 0.10 yad1 = np.zeros_like(ad1) - 0.20 yad = np.zeros_like(ad_vals) - 0.25 plt.plot(x1, yx1, '|') plt.plot(xd1, yxd1, '|') plt.plot(a1, ya1, '|') plt.plot(ad1, yad1, '|') plt.plot(x_vals, yx, '.') plt.plot(xd_vals, yxd, '.') plt.plot(a_vals, ya, '.') plt.plot(ad_vals, yad, '.') plt.ylim([-0.3, 0.3]) plt.plot((x_thres[0], x_thres[0]), (0.15, 0.25), 'k-', color='red') plt.plot((x_thres[1], x_thres[1]), (0.15, 0.25), 'k-', color='red') plt.plot((a_thres[0], a_thres[0]), (-0.05, -0.15), 'k-', color='red') plt.plot((a_thres[1], a_thres[1]), (-0.05, -0.15), 'k-', color='red') def learning_schedule(episode, n_episodes): return max(0., min(0.8, 1 - episode/n_episodes)) def action_selection(state, Q, episode, n_episodes): epsilon = 0.99 if episode < n_episodes//4 else 0.33 if episode < n_episodes//2 else 0. if np.random.random() < epsilon: action = np.random.randint(Q.shape[1]) else: action = np.argmax(Q[state]) return action, epsilon def observation_to_state(observation, bins): ss = [] for i in range(len(observation)): ss.append(int(np.digitize(observation[i], bins=bins[i]))) state = int("".join(map(lambda feature: str(int(feature)), ss))) return state def q_learning(env, bins, gamma = 0.99): nS = 10 * 10 * 10 * 10 nA = env.env.action_space.n Q = np.random.random((nS, nA)) - 0.5 n_episodes = 5000 alphas = [] epsilons = [] states = [] actions = [] for episode in range(n_episodes): observation = env.reset() state = observation_to_state(observation, bins) done = False while not done: states.append(state) action, epsilon = action_selection(state, Q, episode, n_episodes) epsilons.append(epsilon) actions.append(action) observation, reward, done, info = env.step(action) nstate = observation_to_state(observation, bins) alpha = learning_schedule(episode, n_episodes) alphas.append(alpha) Q[state][action] += alpha * (reward + gamma * Q[nstate].max() * (not done) - Q[state][action]) state = nstate return Q, (alphas, epsilons, states, actions) mdir = tempfile.mkdtemp() env = gym.make('CartPole-v0') env = wrappers.Monitor(env, mdir, force=True) Q, stats = q_learning(env, (x1, xd1, a1, ad1)) videos = np.array(env.videos) n_videos = 3 idxs = np.linspace(0, len(videos) - 1, n_videos).astype(int) videos = videos[idxs,:] strm = '' for video_path, meta_path in videos: video = io.open(video_path, 'r+b').read() encoded = base64.b64encode(video) with open(meta_path) as data_file: meta = json.load(data_file) html_tag = <h2>{0}<h2/> <video width="960" height="540" controls> <source src="data:video/mp4;base64,{1}" type="video/mp4" /> </video> strm += html_tag.format('Episode ' + str(meta['episode_id']), encoded.decode('ascii')) HTML(data=strm) V = np.max(Q, axis=1) V V.max() pi = np.argmax(Q, axis=1) pi env.close() gym.upload(mdir, api_key='<YOUR API KEY>') alphas, epsilons, states, actions = stats plt.plot(np.arange(len(alphas)), alphas, '.') plt.plot(np.arange(len(epsilons)), epsilons, '.') hist, bins = np.histogram(states, bins=50) width = 0.7 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 plt.bar(center, hist, align='center', width=width) plt.show() hist, bins = np.histogram(actions, bins=3) width = 0.7 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 plt.bar(center, hist, align='center', width=width) plt.show() Explanation: Expected, I would say. If you want to balance a pole you will have to go left and right to keep the pole in place. Ok, so from these figures you should think about ways to make this algorithm work. Why things didn't work?? How can we make it learn more or better? I'll let you explore from now on... Your turn End of explanation
7,321
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2019 The TensorFlow Authors. Step1: Dogs vs Cats Image Classification Without Image Augmentation <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Data Loading To build our image classifier, we begin by downloading the dataset. The dataset we are using is a filtered version of <a href="https Step3: The dataset we have downloaded has the following directory structure. <pre style="font-size Step4: We'll now assign variables with the proper file path for the training and validation sets. Step5: Understanding our data Let's look at how many cats and dogs images we have in our training and validation directory Step6: Setting Model Parameters For convenience, we'll set up variables that will be used later while pre-processing our dataset and training our network. Step7: Data Preparation Images must be formatted into appropriately pre-processed floating point tensors before being fed into the network. The steps involved in preparing these images are Step8: After defining our generators for training and validation images, flow_from_directory method will load images from the disk, apply rescaling, and resize them using single line of code. Step9: Visualizing Training images We can visualize our training images by getting a batch of images from the training generator, and then plotting a few of them using matplotlib. Step10: The next function returns a batch from the dataset. One batch is a tuple of (many images, many labels). For right now, we're discarding the labels because we just want to look at the images. Step11: Model Creation Define the model The model consists of four convolution blocks with a max pool layer in each of them. Then we have a fully connected layer with 512 units, with a relu activation function. The model will output class probabilities for two classes — dogs and cats — using softmax. Step12: Compile the model As usual, we will use the adam optimizer. Since we output a softmax categorization, we'll use sparse_categorical_crossentropy as the loss function. We would also like to look at training and validation accuracy on each epoch as we train our network, so we are passing in the metrics argument. Step13: Model Summary Let's look at all the layers of our network using summary method. Step14: Train the model It's time we train our network. Since our batches are coming from a generator (ImageDataGenerator), we'll use fit_generator instead of fit. Step15: Visualizing results of the training We'll now visualize the results we get after training our network.
Python Code: #@title 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 # # https://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. Explanation: Copyright 2019 The TensorFlow Authors. End of explanation import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator import os import matplotlib.pyplot as plt import numpy as np import logging logger = tf.get_logger() logger.setLevel(logging.ERROR) Explanation: Dogs vs Cats Image Classification Without Image Augmentation <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l05c01_dogs_vs_cats_without_augmentation.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l05c01_dogs_vs_cats_without_augmentation.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> In this tutorial, we will discuss how to classify images into pictures of cats or pictures of dogs. We'll build an image classifier using tf.keras.Sequential model and load data using tf.keras.preprocessing.image.ImageDataGenerator. Specific concepts that will be covered: In the process, we will build practical experience and develop intuition around the following concepts Building data input pipelines using the tf.keras.preprocessing.image.ImageDataGenerator class — How can we efficiently work with data on disk to interface with our model? Overfitting - what is it, how to identify it? <hr> Before you begin Before running the code in this notebook, reset the runtime by going to Runtime -> Reset all runtimes in the menu above. If you have been working through several notebooks, this will help you avoid reaching Colab's memory limits. Importing packages Let's start by importing required packages: os — to read files and directory structure numpy — for some matrix math outside of TensorFlow matplotlib.pyplot — to plot the graph and display images in our training and validation data End of explanation _URL = 'https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip' zip_dir = tf.keras.utils.get_file('cats_and_dogs_filterted.zip', origin=_URL, extract=True) Explanation: Data Loading To build our image classifier, we begin by downloading the dataset. The dataset we are using is a filtered version of <a href="https://www.kaggle.com/c/dogs-vs-cats/data" target="_blank">Dogs vs. Cats</a> dataset from Kaggle (ultimately, this dataset is provided by Microsoft Research). In previous Colabs, we've used <a href="https://www.tensorflow.org/datasets" target="_blank">TensorFlow Datasets</a>, which is a very easy and convenient way to use datasets. In this Colab however, we will make use of the class tf.keras.preprocessing.image.ImageDataGenerator which will read data from disk. We therefore need to directly download Dogs vs. Cats from a URL and unzip it to the Colab filesystem. End of explanation zip_dir_base = os.path.dirname(zip_dir) !find $zip_dir_base -type d -print Explanation: The dataset we have downloaded has the following directory structure. <pre style="font-size: 10.0pt; font-family: Arial; line-height: 2; letter-spacing: 1.0pt;" > <b>cats_and_dogs_filtered</b> |__ <b>train</b> |______ <b>cats</b>: [cat.0.jpg, cat.1.jpg, cat.2.jpg ...] |______ <b>dogs</b>: [dog.0.jpg, dog.1.jpg, dog.2.jpg ...] |__ <b>validation</b> |______ <b>cats</b>: [cat.2000.jpg, cat.2001.jpg, cat.2002.jpg ...] |______ <b>dogs</b>: [dog.2000.jpg, dog.2001.jpg, dog.2002.jpg ...] </pre> We can list the directories with the following terminal command: End of explanation base_dir = os.path.join(os.path.dirname(zip_dir), 'cats_and_dogs_filtered') train_dir = os.path.join(base_dir, 'train') validation_dir = os.path.join(base_dir, 'validation') train_cats_dir = os.path.join(train_dir, 'cats') # directory with our training cat pictures train_dogs_dir = os.path.join(train_dir, 'dogs') # directory with our training dog pictures validation_cats_dir = os.path.join(validation_dir, 'cats') # directory with our validation cat pictures validation_dogs_dir = os.path.join(validation_dir, 'dogs') # directory with our validation dog pictures Explanation: We'll now assign variables with the proper file path for the training and validation sets. End of explanation num_cats_tr = len(os.listdir(train_cats_dir)) num_dogs_tr = len(os.listdir(train_dogs_dir)) num_cats_val = len(os.listdir(validation_cats_dir)) num_dogs_val = len(os.listdir(validation_dogs_dir)) total_train = num_cats_tr + num_dogs_tr total_val = num_cats_val + num_dogs_val print('total training cat images:', num_cats_tr) print('total training dog images:', num_dogs_tr) print('total validation cat images:', num_cats_val) print('total validation dog images:', num_dogs_val) print("--") print("Total training images:", total_train) print("Total validation images:", total_val) Explanation: Understanding our data Let's look at how many cats and dogs images we have in our training and validation directory End of explanation BATCH_SIZE = 100 # Number of training examples to process before updating our models variables IMG_SHAPE = 150 # Our training data consists of images with width of 150 pixels and height of 150 pixels Explanation: Setting Model Parameters For convenience, we'll set up variables that will be used later while pre-processing our dataset and training our network. End of explanation train_image_generator = ImageDataGenerator(rescale=1./255) # Generator for our training data validation_image_generator = ImageDataGenerator(rescale=1./255) # Generator for our validation data Explanation: Data Preparation Images must be formatted into appropriately pre-processed floating point tensors before being fed into the network. The steps involved in preparing these images are: Read images from the disk Decode contents of these images and convert it into proper grid format as per their RGB content Convert them into floating point tensors Rescale the tensors from values between 0 and 255 to values between 0 and 1, as neural networks prefer to deal with small input values. Fortunately, all these tasks can be done using the class tf.keras.preprocessing.image.ImageDataGenerator. We can set this up in a couple of lines of code. End of explanation train_data_gen = train_image_generator.flow_from_directory(batch_size=BATCH_SIZE, directory=train_dir, shuffle=True, target_size=(IMG_SHAPE,IMG_SHAPE), #(150,150) class_mode='binary') val_data_gen = validation_image_generator.flow_from_directory(batch_size=BATCH_SIZE, directory=validation_dir, shuffle=False, target_size=(IMG_SHAPE,IMG_SHAPE), #(150,150) class_mode='binary') Explanation: After defining our generators for training and validation images, flow_from_directory method will load images from the disk, apply rescaling, and resize them using single line of code. End of explanation sample_training_images, _ = next(train_data_gen) Explanation: Visualizing Training images We can visualize our training images by getting a batch of images from the training generator, and then plotting a few of them using matplotlib. End of explanation # This function will plot images in the form of a grid with 1 row and 5 columns where images are placed in each column. def plotImages(images_arr): fig, axes = plt.subplots(1, 5, figsize=(20,20)) axes = axes.flatten() for img, ax in zip(images_arr, axes): ax.imshow(img) plt.tight_layout() plt.show() plotImages(sample_training_images[:5]) # Plot images 0-4 Explanation: The next function returns a batch from the dataset. One batch is a tuple of (many images, many labels). For right now, we're discarding the labels because we just want to look at the images. End of explanation model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)), tf.keras.layers.MaxPooling2D(2, 2), tf.keras.layers.Conv2D(64, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Conv2D(128, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Conv2D(128, (3,3), activation='relu'), tf.keras.layers.MaxPooling2D(2,2), tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(2) ]) Explanation: Model Creation Define the model The model consists of four convolution blocks with a max pool layer in each of them. Then we have a fully connected layer with 512 units, with a relu activation function. The model will output class probabilities for two classes — dogs and cats — using softmax. End of explanation model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) Explanation: Compile the model As usual, we will use the adam optimizer. Since we output a softmax categorization, we'll use sparse_categorical_crossentropy as the loss function. We would also like to look at training and validation accuracy on each epoch as we train our network, so we are passing in the metrics argument. End of explanation model.summary() Explanation: Model Summary Let's look at all the layers of our network using summary method. End of explanation EPOCHS = 100 history = model.fit_generator( train_data_gen, steps_per_epoch=int(np.ceil(total_train / float(BATCH_SIZE))), epochs=EPOCHS, validation_data=val_data_gen, validation_steps=int(np.ceil(total_val / float(BATCH_SIZE))) ) Explanation: Train the model It's time we train our network. Since our batches are coming from a generator (ImageDataGenerator), we'll use fit_generator instead of fit. End of explanation acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs_range = range(EPOCHS) plt.figure(figsize=(8, 8)) plt.subplot(1, 2, 1) plt.plot(epochs_range, acc, label='Training Accuracy') plt.plot(epochs_range, val_acc, label='Validation Accuracy') plt.legend(loc='lower right') plt.title('Training and Validation Accuracy') plt.subplot(1, 2, 2) plt.plot(epochs_range, loss, label='Training Loss') plt.plot(epochs_range, val_loss, label='Validation Loss') plt.legend(loc='upper right') plt.title('Training and Validation Loss') plt.savefig('./foo.png') plt.show() Explanation: Visualizing results of the training We'll now visualize the results we get after training our network. End of explanation
7,322
Given the following text description, write Python code to implement the functionality described below step by step Description: All API's Step1: After writing a code that returns a result, now automating that for the various dates using a function Step2: 2) What are all the different book categories the NYT ranked in June 6, 2009? How about June 6, 2015? Step3: 4) What's the title of the first story to mention the word 'hipster' in 1995? What's the first paragraph? Step4: 5) How many times was gay marriage mentioned in the NYT between 1950-1959, 1960-1969, 1970-1978, 1980-1989, 1990-2099, 2000-2009, and 2010-present? Tip Step5: 6) What section talks about motorcycles the most? Tip Step6: 7) How many of the last 20 movies reviewed by the NYT were Critics' Picks? How about the last 40? The last 60? Tip Step7: 8) Out of the last 40 movie reviews from the NYT, which critic has written the most reviews?
Python Code: #API Key: 0c3ba2a8848c44eea6a3443a17e57448 import requests bestseller_response = requests.get('http://api.nytimes.com/svc/books/v2/lists/2009-05-10/hardcover-fiction?api-key=0c3ba2a8848c44eea6a3443a17e57448') bestseller_data = bestseller_response.json() print("The type of bestseller_data is:", type(bestseller_data)) print("The keys of bestseller_data are:", bestseller_data.keys()) # Exploring the data structure further bestseller_books = bestseller_data['results'] print(type(bestseller_books)) print(bestseller_books[0]) for book in bestseller_books: #print("NEW BOOK!!!") #print(book['book_details']) #print(book['rank']) if book['rank'] == 1: for element in book['book_details']: print("The book that topped the hardcover fiction NYT Beststeller list on Mothers Day in 2009 was", element['title'], "written by", element['author']) Explanation: All API's: http://developer.nytimes.com/ Article search API: http://developer.nytimes.com/article_search_v2.json Best-seller API: http://developer.nytimes.com/books_api.json#/Documentation Test/build queries: http://developer.nytimes.com/ Tip: Remember to include your API key in all requests! And their interactive web thing is pretty bad. You'll need to register for the API key. 1) What books topped the Hardcover Fiction NYT best-sellers list on Mother's Day in 2009 and 2010? How about Father's Day? End of explanation def bestseller(x, y): bestsellerA_response = requests.get('http://api.nytimes.com/svc/books/v2/lists/'+ x +'/hardcover-fiction?api-key=0c3ba2a8848c44eea6a3443a17e57448') bestsellerA_data = bestsellerA_response.json() bestsellerA_books = bestsellerA_data['results'] for book in bestsellerA_books: if book['rank'] == 1: for element in book['book_details']: print("The book that topped the hardcover fiction NYT Beststeller list on", y, "was", element['title'], "written by", element['author']) bestseller('2009-05-10', "Mothers Day 2009") bestseller('2010-05-09', "Mothers Day 2010") bestseller('2009-06-21', "Fathers Day 2009") bestseller('2010-06-20', "Fathers Day 2010") #Alternative solution would be, instead of putting this code into a function to loop it: #1) to create a dictionary called dates containing y as keys and x as values to these keys #2) to take the above code and nest it into a for loop that loops through the dates, each time using the next key:value pair # for date in dates: # replace value in URL and run the above code used inside the function # replace key in print statement Explanation: After writing a code that returns a result, now automating that for the various dates using a function: End of explanation # STEP 1: Exploring the data structure using just one of the dates from the question bookcat_response = requests.get('http://api.nytimes.com/svc/books/v2/lists/names.json?published-date=2009-06-06&api-key=0c3ba2a8848c44eea6a3443a17e57448') bookcat_data = bookcat_response.json() print(type(bookcat_data)) print(bookcat_data.keys()) bookcat = bookcat_data['results'] print(type(bookcat)) print(bookcat[0]) # STEP 2: Writing a loop that runs the same code for both dates (no function, as only one variable) dates = ['2009-06-06', '2015-06-15'] for date in dates: bookcatN_response = requests.get('http://api.nytimes.com/svc/books/v2/lists/names.json?published-date=' + date + '&api-key=0c3ba2a8848c44eea6a3443a17e57448') bookcatN_data = bookcatN_response.json() bookcatN = bookcatN_data['results'] category_listN = [] for category in bookcatN: category_listN.append(category['display_name']) print(" ") print("THESE WERE THE DIFFERENT BOOK CATEGORIES THE NYT RANKED ON", date) for cat in category_listN: print(cat) # STEP 1a: EXPLORING THE DATA test_response = requests.get('http://api.nytimes.com/svc/search/v2/articlesearch.json?q=Gaddafi+Libya&api-key=0c3ba2a8848c44eea6a3443a17e57448') test_data = test_response.json() print(type(test_data)) print(test_data.keys()) test_hits = test_data['response'] print(type(test_hits)) print(test_hits.keys()) # STEP 1b: EXPLORING THE META DATA test_hits_meta = test_data['response']['meta'] print("The meta data of the search request is a", type(test_hits_meta)) print("The dictionary despot_hits_meta has the following keys:", test_hits_meta.keys()) print("The search requests with the TEST URL yields total:") test_hit_count = test_hits_meta['hits'] print(test_hit_count) # STEP 2: BUILDING THE CODE TO LOOP THROUGH DIFFERENT SPELLINGS despot_names = ['Gadafi', 'Gaddafi', 'Kadafi', 'Qaddafi'] for name in despot_names: despot_response = requests.get('http://api.nytimes.com/svc/search/v2/articlesearch.json?q=' + name +'+Libya&api-key=0c3ba2a8848c44eea6a3443a17e57448') despot_data = despot_response.json() despot_hits_meta = despot_data['response']['meta'] despot_hit_count = despot_hits_meta['hits'] print("The NYT has referred to the Libyan despot", despot_hit_count, "times using the spelling", name) Explanation: 2) What are all the different book categories the NYT ranked in June 6, 2009? How about June 6, 2015? End of explanation hip_response = requests.get('http://api.nytimes.com/svc/search/v2/articlesearch.json?q=hipster&fq=pub_year:1995&api-key=0c3ba2a8848c44eea6a3443a17e57448') hip_data = hip_response.json() print(type(hip_data)) print(hip_data.keys()) # STEP 1: EXPLORING THE DATA STRUCTURE: hipsters = hip_data['response'] #print(hipsters) #hipsters_meta = hipsters['meta'] #print(type(hipsters_meta)) hipsters_results = hipsters['docs'] print(hipsters_results[0].keys()) #print(type(hipsters_results)) #STEP 2: LOOPING FOR THE ANSWER: earliest_date = '1996-01-01' for mention in hipsters_results: if mention['pub_date'] < earliest_date: earliest_date = mention['pub_date'] print("This is the headline of the first text to mention 'hipster' in 1995:", mention['headline']['main']) print("It was published on:", mention['pub_date']) print("This is its lead paragraph:") print(mention['lead_paragraph']) Explanation: 4) What's the title of the first story to mention the word 'hipster' in 1995? What's the first paragraph? End of explanation # data structure requested same as in task 3, just this time loop though different date ranges def countmention(a, b, c): if b == ' ': marry_response = requests.get('http://api.nytimes.com/svc/search/v2/articlesearch.json?q="gay marriage"&begin_date='+ a +'&api-key=0c3ba2a8848c44eea6a3443a17e57448') else: marry_response = requests.get('http://api.nytimes.com/svc/search/v2/articlesearch.json?q="gay marriage"&begin_date='+ a +'&end_date='+ b +'&api-key=0c3ba2a8848c44eea6a3443a17e57448') marry_data = marry_response.json() marry_hits_meta = marry_data['response']['meta'] marry_hit_count = marry_hits_meta['hits'] print("The count for NYT articles mentioning 'gay marriage' between", c, "is", marry_hit_count) #supposedly, there's a way to solve the following part in a more efficient way, but those I tried did not work, #so it ended up being more time-efficient just to type it: countmention('19500101', '19591231', '1950 and 1959') countmention('19600101', '19691231', '1960 and 1969') countmention('19700101', '19791231', '1970 and 1979') countmention('19800101', '19891231', '1980 and 1989') countmention('19900101', '19991231', '1990 and 1999') countmention('20000101', '20091231', '2000 and 2009') countmention('20100101', ' ', '2010 and present') Explanation: 5) How many times was gay marriage mentioned in the NYT between 1950-1959, 1960-1969, 1970-1978, 1980-1989, 1990-2099, 2000-2009, and 2010-present? Tip: You'll want to put quotes around the search term so it isn't just looking for "gay" and "marriage" in the same article. Tip: Write code to find the number of mentions between Jan 1, 1950 and Dec 31, 1959. End of explanation moto_response = requests.get('http://api.nytimes.com/svc/search/v2/articlesearch.json?q=motorcycle&facet_field=section_name&facet_filter=true&api-key=0c3ba2a8848c44eea6a3443a17e57448') moto_data = moto_response.json() #STEP 1: EXPLORING DATA STRUCTURE #print(type(moto_data)) #print(moto_data.keys()) #print(moto_data['response']) #print(moto_data['response'].keys()) #print(moto_data['response']['facets']) #STEP 2: Code to get to the answer moto_facets = moto_data['response']['facets'] #print(moto_facets) #print(moto_facets.keys()) moto_sections = moto_facets['section_name']['terms'] #print(moto_sections) #this for loop is not necessary, but it's nice to know the counts #(also to check whether the next loop identifies the right section) for section in moto_sections: print("The section", section['term'], "mentions motorcycles", section['count'], "times.") most_motorcycles = 0 for section in moto_sections: if section['count'] > most_motorcycles: most_motorcycles = section['count'] print(" ") print("That means the section", section['term'], "mentions motorcycles the most, namely", section['count'], "times.") Explanation: 6) What section talks about motorcycles the most? Tip: You'll be using facets End of explanation picks_offset_values = [0, 20, 40] picks_review_list = [] for value in picks_offset_values: picks_response = requests.get ('http://api.nytimes.com/svc/movies/v2/reviews/search.json?&offset=' + str(value) + '&api-key=0c3ba2a8848c44eea6a3443a17e57448') picks_data = picks_response.json() #STEP 1: EXPLORING THE DATA STRUCTURE (without the loop) #print(picks_data.keys()) #print(picks_data['num_results']) #print(picks_data['results']) #print(type(picks_data['results'])) #print(picks_data['results'][0].keys()) #STEP 2: After writing a test code (not shown) without the loop, now CODING THE LOOP last_reviews = picks_data['num_results'] picks_results = picks_data['results'] critics_pick_count = 0 for review in picks_results: if review['critics_pick'] == 1: critics_pick_count = critics_pick_count + 1 picks_new_count = critics_pick_count picks_review_list.append(picks_new_count) print("Out of the last", last_reviews + value, "movie reviews,", sum(picks_review_list), "were Critics' picks.") Explanation: 7) How many of the last 20 movies reviewed by the NYT were Critics' Picks? How about the last 40? The last 60? Tip: You really don't want to do this 3 separate times (1-20, 21-40 and 41-60) and add them together. What if, perhaps, you were able to figure out how to combine two lists? Then you could have a 1-20 list, a 1-40 list, and a 1-60 list, and then just run similar code for each of them. End of explanation #STEP 1: EXPLORING THE DATA STRUCTURE (without the loop) #critics_response = requests.get('http://api.nytimes.com/svc/movies/v2/reviews/search.json?&offset=0&api-key=0c3ba2a8848c44eea6a3443a17e57448') #critics_data = critics_response.json() #print(critics_data.keys()) #print(critics_data['num_results']) #print(critics_data['results']) #print(type(critics_data['results'])) #print(critics_data['results'][0].keys()) #STEP 2: CREATE A LOOP, THAT GOES THROUGH THE SEARCH RESULTS FOR EACH OFFSET VALUE AND STORES THE RESULTS IN THE SAME LIST #(That list is then passed on to step 3) critics_offset_value = [0, 20] critics_list = [ ] for value in critics_offset_value: critics_response = requests.get('http://api.nytimes.com/svc/movies/v2/reviews/search.json?&offset=' + str(value) + '&api-key=0c3ba2a8848c44eea6a3443a17e57448') critics_data = critics_response.json() critics = critics_data['results'] for review in critics: critics_list.append(review['byline']) #print(critics_list) unique_critics = set(critics_list) #print(unique_critics) #STEP 3: FOR EVERY NAME IN THE UNIQUE CRITICS LIST, LOOP THROUGH NON-UNIQUE LIST TO COUNT HOW OFTEN THEY OCCUR #STEP 4: SELECT THE ONE THAT HAS WRITTEN THE MOST (from the #print statement below, I know it's two people with same score) max_count = 0 for name in unique_critics: name_count = 0 for critic in critics_list: if critic == name: name_count = name_count + 1 if name_count > max_count: max_count = name_count max_name = name if name_count == max_count: same_count = name_count same_name = name #print(name, "has written", name_count, "reviews out of the last 40 reviews.") print(max_name, "has written the most of the last 40 reviews:", max_count) print(same_name, "has written the most of the last 40 reviews:", same_count) Explanation: 8) Out of the last 40 movie reviews from the NYT, which critic has written the most reviews? End of explanation
7,323
Given the following text description, write Python code to implement the functionality described below step by step Description: Before we get started, a couple of reminders to keep in mind when using iPython notebooks Step1: Fixing Data Types Step2: Note when running the above cells that we are actively changing the contents of our data variables. If you try to run these cells multiple times in the same session, an error will occur. Investigating the Data Step3: Problems in the Data Step4: Missing Engagement Records Step5: Checking for More Problem Records Step6: Tracking Down the Remaining Problems Step7: Refining the Question Step8: Getting Data from First Week Step9: Exploring Student Engagement Step10: Debugging Data Analysis Code Step11: Lessons Completed in First Week Step12: Number of Visits in First Week Step13: Splitting out Passing Students Step14: Comparing the Two Student Groups Step15: Making Histograms Step16: Improving Plots and Sharing Findings
Python Code: import unicodecsv ## Longer version of code (replaced with shorter, equivalent version below) # enrollments = [] # f = open('enrollments.csv', 'rb') # reader = unicodecsv.DictReader(f) # for row in reader: # enrollments.append(row) # f.close() def open_file(filename): with open(filename, 'rb') as f: reader = unicodecsv.DictReader(f) file_result = list(reader) return file_result enrollments = open_file('enrollments.csv') ##################################### # 1 # ##################################### ## Read in the data from daily_engagement.csv and project_submissions.csv ## and store the results in the below variables. ## Then look at the first row of each table. daily_engagement = open_file('daily_engagement.csv') project_submissions = open_file('project_submissions.csv') Explanation: Before we get started, a couple of reminders to keep in mind when using iPython notebooks: Remember that you can see from the left side of a code cell when it was last run if there is a number within the brackets. When you start a new notebook session, make sure you run all of the cells up to the point where you last left off. Even if the output is still visible from when you ran the cells in your previous session, the kernel starts in a fresh state so you'll need to reload the data, etc. on a new session. The previous point is useful to keep in mind if your answers do not match what is expected in the lesson's quizzes. Try reloading the data and run all of the processing steps one by one in order to make sure that you are working with the same variables and data that are at each quiz stage. Load Data from CSVs End of explanation from datetime import datetime as dt # Takes a date as a string, and returns a Python datetime object. # If there is no date given, returns None def parse_date(date): if date == '': return None else: return dt.strptime(date, '%Y-%m-%d') # Takes a string which is either an empty string or represents an integer, # and returns an int or None. def parse_maybe_int(i): if i == '': return None else: return int(i) # Clean up the data types in the enrollments table for enrollment in enrollments: enrollment['cancel_date'] = parse_date(enrollment['cancel_date']) enrollment['days_to_cancel'] = parse_maybe_int(enrollment['days_to_cancel']) enrollment['is_canceled'] = enrollment['is_canceled'] == 'True' enrollment['is_udacity'] = enrollment['is_udacity'] == 'True' enrollment['join_date'] = parse_date(enrollment['join_date']) enrollments[0] # Clean up the data types in the engagement table for engagement_record in daily_engagement: engagement_record['lessons_completed'] = int(float(engagement_record['lessons_completed'])) engagement_record['num_courses_visited'] = int(float(engagement_record['num_courses_visited'])) engagement_record['projects_completed'] = int(float(engagement_record['projects_completed'])) engagement_record['total_minutes_visited'] = float(engagement_record['total_minutes_visited']) engagement_record['utc_date'] = parse_date(engagement_record['utc_date']) daily_engagement[0] # Clean up the data types in the submissions table for submission in project_submissions: submission['completion_date'] = parse_date(submission['completion_date']) submission['creation_date'] = parse_date(submission['creation_date']) project_submissions[0] Explanation: Fixing Data Types End of explanation ##################################### # 2 # ##################################### def get_unique(data, key_s): unique_students = set() for data_point in data: unique_students.add(data_point[key_s]) return unique_students ## Find the total number of rows and the number of unique students (account keys) ## in each table. len(enrollments) unique_enrolled_students = get_unique(enrollments,'account_key') len(unique_enrolled_students) len(daily_engagement) unique_engagement_students = get_unique(daily_engagement,'acct') len(unique_engagement_students) len(project_submissions) unique_project_submitters = get_unique(project_submissions,'account_key') len(unique_project_submitters) Explanation: Note when running the above cells that we are actively changing the contents of our data variables. If you try to run these cells multiple times in the same session, an error will occur. Investigating the Data End of explanation ##################################### # 3 # ##################################### ## Rename the "acct" column in the daily_engagement table to "account_key". for elem in daily_engagement: elem['account_key'] = elem['acct'] del elem['acct'] len(get_unique(daily_engagement,'account_key')) daily_engagement[0] Explanation: Problems in the Data End of explanation ##################################### # 4 # ##################################### ## Find any one student enrollments where the student is missing from the daily engagement table. ## Output that enrollment. for enrollment in enrollments: student = enrollment['account_key'] if student not in unique_engagement_students: print enrollment break # We have canceled users!! Explanation: Missing Engagement Records End of explanation ##################################### # 5 # ##################################### ## Find the number of surprising data points (enrollments missing from ## the engagement table) that remain, if any. num_surprises = 0 for enrollment in enrollments: student = enrollment['account_key'] if (enrollment['cancel_date'] != enrollment['join_date'] and student not in unique_engagement_students): num_surprises += 1 num_surprises Explanation: Checking for More Problem Records End of explanation # Create a set of the account keys for all Udacity test accounts udacity_test_accounts = set() for enrollment in enrollments: if enrollment['is_udacity']: udacity_test_accounts.add(enrollment['account_key']) len(udacity_test_accounts) # Given some data with an account_key field, removes any records corresponding to Udacity test accounts def remove_udacity_accounts(data): non_udacity_data = [] for data_point in data: if data_point['account_key'] not in udacity_test_accounts: non_udacity_data.append(data_point) return non_udacity_data # Remove Udacity test accounts from all three tables non_udacity_enrollments = remove_udacity_accounts(enrollments) non_udacity_engagement = remove_udacity_accounts(daily_engagement) non_udacity_submissions = remove_udacity_accounts(project_submissions) print len(non_udacity_enrollments) print len(non_udacity_engagement) print len(non_udacity_submissions) Explanation: Tracking Down the Remaining Problems End of explanation ##################################### # 6 # ##################################### ## Create a dictionary named paid_students containing all students who either ## haven't canceled yet or who remained enrolled for more than 7 days. The keys ## should be account keys, and the values should be the date the student enrolled. paid_students = {} for enrollment in non_udacity_enrollments: account_key = str(enrollment['account_key']) enrollment_date = enrollment['join_date'] if enrollment['days_to_cancel'] > 7 or enrollment['days_to_cancel'] == None: if (account_key not in paid_students or enrollment_date > paid_students[account_key]): paid_students[account_key] = enrollment_date len(paid_students) len(paid_students.keys()) Explanation: Refining the Question End of explanation # Takes a student's join date and the date of a specific engagement record, # and returns True if that engagement record happened within one week # of the student joining. def within_one_week(join_date, engagement_date): time_delta = engagement_date - join_date return time_delta.days < 7 ##################################### # 7 # ##################################### ## Create a list of rows from the engagement table including only rows where ## the student is one of the paid students you just found, and the date is within ## one week of the student's join date. paid_engagement_in_first_week = list() for element in non_udacity_engagement: account = element['account_key'] if account in paid_students: join_date = paid_students[account] engagement_record_date = element['utc_date'] if within_one_week(join_date, engagement_record_date): paid_engagement_in_first_week.append(element) len(paid_engagement_in_first_week) Explanation: Getting Data from First Week End of explanation from collections import defaultdict # Create a dictionary of engagement grouped by student. # The keys are account keys, and the values are lists of engagement records. engagement_by_account = defaultdict(list) for engagement_record in paid_engagement_in_first_week: account_key = engagement_record['account_key'] engagement_by_account[account_key].append(engagement_record) # Create a dictionary with the total minutes each student spent in the classroom during the first week. # The keys are account keys, and the values are numbers (total minutes) total_minutes_by_account = {} for account_key, engagement_for_student in engagement_by_account.items(): total_minutes = 0 for engagement_record in engagement_for_student: total_minutes += engagement_record['total_minutes_visited'] total_minutes_by_account[account_key] = total_minutes import numpy as np # Summarize the data about minutes spent in the classroom total_minutes = total_minutes_by_account.values() print 'Mean:', np.mean(total_minutes) print 'Standard deviation:', np.std(total_minutes) print 'Minimum:', np.min(total_minutes) print 'Maximum:', np.max(total_minutes) Explanation: Exploring Student Engagement End of explanation ##################################### # 8 # ##################################### ## Go through a similar process as before to see if there is a problem. ## Locate at least one surprising piece of data, output it, and take a look at it. Explanation: Debugging Data Analysis Code End of explanation ##################################### # 9 # ##################################### ## Adapt the code above to find the mean, standard deviation, minimum, and maximum for ## the number of lessons completed by each student during the first week. Try creating ## one or more functions to re-use the code above. Explanation: Lessons Completed in First Week End of explanation ###################################### # 10 # ###################################### ## Find the mean, standard deviation, minimum, and maximum for the number of ## days each student visits the classroom during the first week. Explanation: Number of Visits in First Week End of explanation ###################################### # 11 # ###################################### ## Create two lists of engagement data for paid students in the first week. ## The first list should contain data for students who eventually pass the ## subway project, and the second list should contain data for students ## who do not. subway_project_lesson_keys = ['746169184', '3176718735'] passing_engagement = non_passing_engagement = Explanation: Splitting out Passing Students End of explanation ###################################### # 12 # ###################################### ## Compute some metrics you're interested in and see how they differ for ## students who pass the subway project vs. students who don't. A good ## starting point would be the metrics we looked at earlier (minutes spent ## in the classroom, lessons completed, and days visited). Explanation: Comparing the Two Student Groups End of explanation ###################################### # 13 # ###################################### ## Make histograms of the three metrics we looked at earlier for both ## students who passed the subway project and students who didn't. You ## might also want to make histograms of any other metrics you examined. Explanation: Making Histograms End of explanation ###################################### # 14 # ###################################### ## Make a more polished version of at least one of your visualizations ## from earlier. Try importing the seaborn library to make the visualization ## look better, adding axis labels and a title, and changing one or more ## arguments to the hist() function. Explanation: Improving Plots and Sharing Findings End of explanation
7,324
Given the following text description, write Python code to implement the functionality described below step by step Description: Nearest Neighbors When exploring a large set of documents -- such as Wikipedia, news articles, StackOverflow, etc. -- it can be useful to get a list of related material. To find relevant documents you typically * Decide on a notion of similarity * Find the documents that are most similar In the assignment you will * Gain intuition for different notions of similarity and practice finding similar documents. * Explore the tradeoffs with representing documents using raw word counts and TF-IDF * Explore the behavior of different distance metrics by looking at the Wikipedia pages most similar to President Obama’s page. Note to Amazon EC2 users Step1: Load Wikipedia dataset We will be using the same dataset of Wikipedia pages that we used in the Machine Learning Foundations course (Course 1). Each element of the dataset consists of a link to the wikipedia article, the name of the person, and the text of the article (in lowercase). Step2: Extract word count vectors As we have seen in Course 1, we can extract word count vectors using a GraphLab utility function. We add this as a column in wiki. Step3: Find nearest neighbors Let's start by finding the nearest neighbors of the Barack Obama page using the word count vectors to represent the articles and Euclidean distance to measure distance. For this, again will we use a GraphLab Create implementation of nearest neighbor search. Step4: Let's look at the top 10 nearest neighbors by performing the following query Step6: All of the 10 people are politicians, but about half of them have rather tenuous connections with Obama, other than the fact that they are politicians. Francisco Barrio is a Mexican politician, and a former governor of Chihuahua. Walter Mondale and Don Bonker are Democrats who made their career in late 1970s. Wynn Normington Hugh-Jones is a former British diplomat and Liberal Party official. Andy Anstett is a former politician in Manitoba, Canada. Nearest neighbors with raw word counts got some things right, showing all politicians in the query result, but missed finer and important details. For instance, let's find out why Francisco Barrio was considered a close neighbor of Obama. To do this, let's look at the most frequently used words in each of Barack Obama and Francisco Barrio's pages Step7: Let's extract the list of most frequent words that appear in both Obama's and Barrio's documents. We've so far sorted all words from Obama and Barrio's articles by their word frequencies. We will now use a dataframe operation known as join. The join operation is very useful when it comes to playing around with data Step8: Since both tables contained the column named count, SFrame automatically renamed one of them to prevent confusion. Let's rename the columns to tell which one is for which. By inspection, we see that the first column (count) is for Obama and the second (count.1) for Barrio. Step9: Note. The join operation does not enforce any particular ordering on the shared column. So to obtain, say, the five common words that appear most often in Obama's article, sort the combined table by the Obama column. Don't forget ascending=False to display largest counts first. Step10: Quiz Question. Among the words that appear in both Barack Obama and Francisco Barrio, take the 5 that appear most frequently in Obama. How many of the articles in the Wikipedia dataset contain all of those 5 words? Hint Step11: Checkpoint. Check your has_top_words function on two random articles Step12: Quiz Question. Measure the pairwise distance between the Wikipedia pages of Barack Obama, George W. Bush, and Joe Biden. Which of the three pairs has the smallest distance? Hint Step13: Let's determine whether this list makes sense. * With a notable exception of Roland Grossenbacher, the other 8 are all American politicians who are contemporaries of Barack Obama. * Phil Schiliro, Jesse Lee, Samantha Power, and Eric Stern worked for Obama. Clearly, the results are more plausible with the use of TF-IDF. Let's take a look at the word vector for Obama and Schilirio's pages. Notice that TF-IDF representation assigns a weight to each word. This weight captures relative importance of that word in the document. Let us sort the words in Obama's article by their TF-IDF weights; we do the same for Schiliro's article as well. Step14: Using the join operation we learned earlier, try your hands at computing the common words shared by Obama's and Schiliro's articles. Sort the common words by their TF-IDF weights in Obama's document. The first 10 words should say Step15: Notice the huge difference in this calculation using TF-IDF scores instead of raw word counts. We've eliminated noise arising from extremely common words. Choosing metrics You may wonder why Joe Biden, Obama's running mate in two presidential elections, is missing from the query results of model_tf_idf. Let's find out why. First, compute the distance between TF-IDF features of Obama and Biden. Quiz Question. Compute the Euclidean distance between TF-IDF features of Obama and Biden. Hint Step16: But one may wonder, is Biden's article that different from Obama's, more so than, say, Schiliro's? It turns out that, when we compute nearest neighbors using the Euclidean distances, we unwittingly favor short articles over long ones. Let us compute the length of each Wikipedia document, and examine the document lengths for the 100 nearest neighbors to Obama's page. Step17: To see how these document lengths compare to the lengths of other documents in the corpus, let's make a histogram of the document lengths of Obama's 100 nearest neighbors and compare to a histogram of document lengths for all documents. Step18: Relative to the rest of Wikipedia, nearest neighbors of Obama are overwhemingly short, most of them being shorter than 2000 words. The bias towards short articles is not appropriate in this application as there is really no reason to favor short articles over long articles (they are all Wikipedia articles, after all). Many Wikipedia articles are 2500 words or more, and both Obama and Biden are over 2500 words long. Note Step19: From a glance at the above table, things look better. For example, we now see Joe Biden as Barack Obama's nearest neighbor! We also see Hillary Clinton on the list. This list looks even more plausible as nearest neighbors of Barack Obama. Let's make a plot to better visualize the effect of having used cosine distance in place of Euclidean on our TF-IDF vectors. Step20: Indeed, the 100 nearest neighbors using cosine distance provide a sampling across the range of document lengths, rather than just short articles like Euclidean distance provided. Moral of the story Step21: Let's look at the TF-IDF vectors for this tweet and for Barack Obama's Wikipedia entry, just to visually see their differences. Step22: Now, compute the cosine distance between the Barack Obama article and this tweet Step23: Let's compare this distance to the distance between the Barack Obama article and all of its Wikipedia 10 nearest neighbors
Python Code: import graphlab import matplotlib.pyplot as plt import numpy as np %matplotlib inline Explanation: Nearest Neighbors When exploring a large set of documents -- such as Wikipedia, news articles, StackOverflow, etc. -- it can be useful to get a list of related material. To find relevant documents you typically * Decide on a notion of similarity * Find the documents that are most similar In the assignment you will * Gain intuition for different notions of similarity and practice finding similar documents. * Explore the tradeoffs with representing documents using raw word counts and TF-IDF * Explore the behavior of different distance metrics by looking at the Wikipedia pages most similar to President Obama’s page. Note to Amazon EC2 users: To conserve memory, make sure to stop all the other notebooks before running this notebook. Import necessary packages As usual we need to first import the Python packages that we will need. End of explanation wiki = graphlab.SFrame('people_wiki.gl') wiki Explanation: Load Wikipedia dataset We will be using the same dataset of Wikipedia pages that we used in the Machine Learning Foundations course (Course 1). Each element of the dataset consists of a link to the wikipedia article, the name of the person, and the text of the article (in lowercase). End of explanation wiki['word_count'] = graphlab.text_analytics.count_words(wiki['text']) wiki Explanation: Extract word count vectors As we have seen in Course 1, we can extract word count vectors using a GraphLab utility function. We add this as a column in wiki. End of explanation model = graphlab.nearest_neighbors.create(wiki, label='name', features=['word_count'], method='brute_force', distance='euclidean') Explanation: Find nearest neighbors Let's start by finding the nearest neighbors of the Barack Obama page using the word count vectors to represent the articles and Euclidean distance to measure distance. For this, again will we use a GraphLab Create implementation of nearest neighbor search. End of explanation model.query(wiki[wiki['name']=='Barack Obama'], label='name', k=10) Explanation: Let's look at the top 10 nearest neighbors by performing the following query: End of explanation def top_words(name): Get a table of the most frequent words in the given person's wikipedia page. row = wiki[wiki['name'] == name] word_count_table = row[['word_count']].stack('word_count', new_column_name=['word','count']) return word_count_table.sort('count', ascending=False) obama_words = top_words('Barack Obama') obama_words barrio_words = top_words('Francisco Barrio') barrio_words Explanation: All of the 10 people are politicians, but about half of them have rather tenuous connections with Obama, other than the fact that they are politicians. Francisco Barrio is a Mexican politician, and a former governor of Chihuahua. Walter Mondale and Don Bonker are Democrats who made their career in late 1970s. Wynn Normington Hugh-Jones is a former British diplomat and Liberal Party official. Andy Anstett is a former politician in Manitoba, Canada. Nearest neighbors with raw word counts got some things right, showing all politicians in the query result, but missed finer and important details. For instance, let's find out why Francisco Barrio was considered a close neighbor of Obama. To do this, let's look at the most frequently used words in each of Barack Obama and Francisco Barrio's pages: End of explanation combined_words = obama_words.join(barrio_words, on='word') combined_words Explanation: Let's extract the list of most frequent words that appear in both Obama's and Barrio's documents. We've so far sorted all words from Obama and Barrio's articles by their word frequencies. We will now use a dataframe operation known as join. The join operation is very useful when it comes to playing around with data: it lets you combine the content of two tables using a shared column (in this case, the word column). See the documentation for more details. For instance, running obama_words.join(barrio_words, on='word') will extract the rows from both tables that correspond to the common words. End of explanation combined_words = combined_words.rename({'count':'Obama', 'count.1':'Barrio'}) combined_words Explanation: Since both tables contained the column named count, SFrame automatically renamed one of them to prevent confusion. Let's rename the columns to tell which one is for which. By inspection, we see that the first column (count) is for Obama and the second (count.1) for Barrio. End of explanation combined_words.sort('Obama', ascending=False) Explanation: Note. The join operation does not enforce any particular ordering on the shared column. So to obtain, say, the five common words that appear most often in Obama's article, sort the combined table by the Obama column. Don't forget ascending=False to display largest counts first. End of explanation common_words = ... # YOUR CODE HERE def has_top_words(word_count_vector): # extract the keys of word_count_vector and convert it to a set unique_words = ... # YOUR CODE HERE # return True if common_words is a subset of unique_words # return False otherwise return ... # YOUR CODE HERE wiki['has_top_words'] = wiki['word_count'].apply(has_top_words) # use has_top_words column to answer the quiz question ... # YOUR CODE HERE Explanation: Quiz Question. Among the words that appear in both Barack Obama and Francisco Barrio, take the 5 that appear most frequently in Obama. How many of the articles in the Wikipedia dataset contain all of those 5 words? Hint: * Refer to the previous paragraph for finding the words that appear in both articles. Sort the common words by their frequencies in Obama's article and take the largest five. * Each word count vector is a Python dictionary. For each word count vector in SFrame, you'd have to check if the set of the 5 common words is a subset of the keys of the word count vector. Complete the function has_top_words to accomplish the task. - Convert the list of top 5 words into set using the syntax set(common_words) where common_words is a Python list. See this link if you're curious about Python sets. - Extract the list of keys of the word count dictionary by calling the keys() method. - Convert the list of keys into a set as well. - Use issubset() method to check if all 5 words are among the keys. * Now apply the has_top_words function on every row of the SFrame. * Compute the sum of the result column to obtain the number of articles containing all the 5 top words. End of explanation print 'Output from your function:', has_top_words(wiki[32]['word_count']) print 'Correct output: True' print 'Also check the length of unique_words. It should be 167' print 'Output from your function:', has_top_words(wiki[33]['word_count']) print 'Correct output: False' print 'Also check the length of unique_words. It should be 188' Explanation: Checkpoint. Check your has_top_words function on two random articles: End of explanation wiki['tf_idf'] = graphlab.text_analytics.tf_idf(wiki['word_count']) model_tf_idf = graphlab.nearest_neighbors.create(wiki, label='name', features=['tf_idf'], method='brute_force', distance='euclidean') model_tf_idf.query(wiki[wiki['name'] == 'Barack Obama'], label='name', k=10) Explanation: Quiz Question. Measure the pairwise distance between the Wikipedia pages of Barack Obama, George W. Bush, and Joe Biden. Which of the three pairs has the smallest distance? Hint: To compute the Euclidean distance between two dictionaries, use graphlab.toolkits.distances.euclidean. Refer to this link for usage. Quiz Question. Collect all words that appear both in Barack Obama and George W. Bush pages. Out of those words, find the 10 words that show up most often in Obama's page. Note. Even though common words are swamping out important subtle differences, commonalities in rarer political words still matter on the margin. This is why politicians are being listed in the query result instead of musicians, for example. In the next subsection, we will introduce a different metric that will place greater emphasis on those rarer words. TF-IDF to the rescue Much of the perceived commonalities between Obama and Barrio were due to occurrences of extremely frequent words, such as "the", "and", and "his". So nearest neighbors is recommending plausible results sometimes for the wrong reasons. To retrieve articles that are more relevant, we should focus more on rare words that don't happen in every article. TF-IDF (term frequency–inverse document frequency) is a feature representation that penalizes words that are too common. Let's use GraphLab Create's implementation of TF-IDF and repeat the search for the 10 nearest neighbors of Barack Obama: End of explanation def top_words_tf_idf(name): row = wiki[wiki['name'] == name] word_count_table = row[['tf_idf']].stack('tf_idf', new_column_name=['word','weight']) return word_count_table.sort('weight', ascending=False) obama_tf_idf = top_words_tf_idf('Barack Obama') obama_tf_idf schiliro_tf_idf = top_words_tf_idf('Phil Schiliro') schiliro_tf_idf Explanation: Let's determine whether this list makes sense. * With a notable exception of Roland Grossenbacher, the other 8 are all American politicians who are contemporaries of Barack Obama. * Phil Schiliro, Jesse Lee, Samantha Power, and Eric Stern worked for Obama. Clearly, the results are more plausible with the use of TF-IDF. Let's take a look at the word vector for Obama and Schilirio's pages. Notice that TF-IDF representation assigns a weight to each word. This weight captures relative importance of that word in the document. Let us sort the words in Obama's article by their TF-IDF weights; we do the same for Schiliro's article as well. End of explanation common_words = ... # YOUR CODE HERE def has_top_words(word_count_vector): # extract the keys of word_count_vector and convert it to a set unique_words = ... # YOUR CODE HERE # return True if common_words is a subset of unique_words # return False otherwise return ... # YOUR CODE HERE wiki['has_top_words'] = wiki['word_count'].apply(has_top_words) # use has_top_words column to answer the quiz question ... # YOUR CODE HERE Explanation: Using the join operation we learned earlier, try your hands at computing the common words shared by Obama's and Schiliro's articles. Sort the common words by their TF-IDF weights in Obama's document. The first 10 words should say: Obama, law, democratic, Senate, presidential, president, policy, states, office, 2011. Quiz Question. Among the words that appear in both Barack Obama and Phil Schiliro, take the 5 that have largest weights in Obama. How many of the articles in the Wikipedia dataset contain all of those 5 words? End of explanation model_tf_idf.query(wiki[wiki['name'] == 'Barack Obama'], label='name', k=10) Explanation: Notice the huge difference in this calculation using TF-IDF scores instead of raw word counts. We've eliminated noise arising from extremely common words. Choosing metrics You may wonder why Joe Biden, Obama's running mate in two presidential elections, is missing from the query results of model_tf_idf. Let's find out why. First, compute the distance between TF-IDF features of Obama and Biden. Quiz Question. Compute the Euclidean distance between TF-IDF features of Obama and Biden. Hint: When using Boolean filter in SFrame/SArray, take the index 0 to access the first match. The distance is larger than the distances we found for the 10 nearest neighbors, which we repeat here for readability: End of explanation def compute_length(row): return len(row['text']) wiki['length'] = wiki.apply(compute_length) nearest_neighbors_euclidean = model_tf_idf.query(wiki[wiki['name'] == 'Barack Obama'], label='name', k=100) nearest_neighbors_euclidean = nearest_neighbors_euclidean.join(wiki[['name', 'length']], on={'reference_label':'name'}) nearest_neighbors_euclidean.sort('rank') Explanation: But one may wonder, is Biden's article that different from Obama's, more so than, say, Schiliro's? It turns out that, when we compute nearest neighbors using the Euclidean distances, we unwittingly favor short articles over long ones. Let us compute the length of each Wikipedia document, and examine the document lengths for the 100 nearest neighbors to Obama's page. End of explanation plt.figure(figsize=(10.5,4.5)) plt.hist(wiki['length'], 50, color='k', edgecolor='None', histtype='stepfilled', normed=True, label='Entire Wikipedia', zorder=3, alpha=0.8) plt.hist(nearest_neighbors_euclidean['length'], 50, color='r', edgecolor='None', histtype='stepfilled', normed=True, label='100 NNs of Obama (Euclidean)', zorder=10, alpha=0.8) plt.axvline(x=wiki['length'][wiki['name'] == 'Barack Obama'][0], color='k', linestyle='--', linewidth=4, label='Length of Barack Obama', zorder=2) plt.axvline(x=wiki['length'][wiki['name'] == 'Joe Biden'][0], color='g', linestyle='--', linewidth=4, label='Length of Joe Biden', zorder=1) plt.axis([1000, 5500, 0, 0.004]) plt.legend(loc='best', prop={'size':15}) plt.title('Distribution of document length') plt.xlabel('# of words') plt.ylabel('Percentage') plt.rcParams.update({'font.size':16}) plt.tight_layout() Explanation: To see how these document lengths compare to the lengths of other documents in the corpus, let's make a histogram of the document lengths of Obama's 100 nearest neighbors and compare to a histogram of document lengths for all documents. End of explanation model2_tf_idf = graphlab.nearest_neighbors.create(wiki, label='name', features=['tf_idf'], method='brute_force', distance='cosine') nearest_neighbors_cosine = model2_tf_idf.query(wiki[wiki['name'] == 'Barack Obama'], label='name', k=100) nearest_neighbors_cosine = nearest_neighbors_cosine.join(wiki[['name', 'length']], on={'reference_label':'name'}) nearest_neighbors_cosine.sort('rank') Explanation: Relative to the rest of Wikipedia, nearest neighbors of Obama are overwhemingly short, most of them being shorter than 2000 words. The bias towards short articles is not appropriate in this application as there is really no reason to favor short articles over long articles (they are all Wikipedia articles, after all). Many Wikipedia articles are 2500 words or more, and both Obama and Biden are over 2500 words long. Note: Both word-count features and TF-IDF are proportional to word frequencies. While TF-IDF penalizes very common words, longer articles tend to have longer TF-IDF vectors simply because they have more words in them. To remove this bias, we turn to cosine distances: $$ d(\mathbf{x},\mathbf{y}) = 1 - \frac{\mathbf{x}^T\mathbf{y}}{\|\mathbf{x}\| \|\mathbf{y}\|} $$ Cosine distances let us compare word distributions of two articles of varying lengths. Let us train a new nearest neighbor model, this time with cosine distances. We then repeat the search for Obama's 100 nearest neighbors. End of explanation plt.figure(figsize=(10.5,4.5)) plt.figure(figsize=(10.5,4.5)) plt.hist(wiki['length'], 50, color='k', edgecolor='None', histtype='stepfilled', normed=True, label='Entire Wikipedia', zorder=3, alpha=0.8) plt.hist(nearest_neighbors_euclidean['length'], 50, color='r', edgecolor='None', histtype='stepfilled', normed=True, label='100 NNs of Obama (Euclidean)', zorder=10, alpha=0.8) plt.hist(nearest_neighbors_cosine['length'], 50, color='b', edgecolor='None', histtype='stepfilled', normed=True, label='100 NNs of Obama (cosine)', zorder=11, alpha=0.8) plt.axvline(x=wiki['length'][wiki['name'] == 'Barack Obama'][0], color='k', linestyle='--', linewidth=4, label='Length of Barack Obama', zorder=2) plt.axvline(x=wiki['length'][wiki['name'] == 'Joe Biden'][0], color='g', linestyle='--', linewidth=4, label='Length of Joe Biden', zorder=1) plt.axis([1000, 5500, 0, 0.004]) plt.legend(loc='best', prop={'size':15}) plt.title('Distribution of document length') plt.xlabel('# of words') plt.ylabel('Percentage') plt.rcParams.update({'font.size': 16}) plt.tight_layout() Explanation: From a glance at the above table, things look better. For example, we now see Joe Biden as Barack Obama's nearest neighbor! We also see Hillary Clinton on the list. This list looks even more plausible as nearest neighbors of Barack Obama. Let's make a plot to better visualize the effect of having used cosine distance in place of Euclidean on our TF-IDF vectors. End of explanation sf = graphlab.SFrame({'text': ['democratic governments control law in response to popular act']}) sf['word_count'] = graphlab.text_analytics.count_words(sf['text']) encoder = graphlab.feature_engineering.TFIDF(features=['word_count'], output_column_prefix='tf_idf') encoder.fit(wiki) sf = encoder.transform(sf) sf Explanation: Indeed, the 100 nearest neighbors using cosine distance provide a sampling across the range of document lengths, rather than just short articles like Euclidean distance provided. Moral of the story: In deciding the features and distance measures, check if they produce results that make sense for your particular application. Problem with cosine distances: tweets vs. long articles Happily ever after? Not so fast. Cosine distances ignore all document lengths, which may be great in certain situations but not in others. For instance, consider the following (admittedly contrived) example. +--------------------------------------------------------+ | +--------+ | | One that shall not be named | Follow | | | @username +--------+ | | | | Democratic governments control law in response to | | popular act. | | | | 8:05 AM - 16 May 2016 | | | | Reply Retweet (1,332) Like (300) | | | +--------------------------------------------------------+ How similar is this tweet to Barack Obama's Wikipedia article? Let's transform the tweet into TF-IDF features, using an encoder fit to the Wikipedia dataset. (That is, let's treat this tweet as an article in our Wikipedia dataset and see what happens.) End of explanation tweet_tf_idf = sf[0]['tf_idf.word_count'] tweet_tf_idf obama Explanation: Let's look at the TF-IDF vectors for this tweet and for Barack Obama's Wikipedia entry, just to visually see their differences. End of explanation obama = wiki[wiki['name'] == 'Barack Obama'] obama_tf_idf = obama[0]['tf_idf'] graphlab.toolkits.distances.cosine(obama_tf_idf, tweet_tf_idf) Explanation: Now, compute the cosine distance between the Barack Obama article and this tweet: End of explanation model2_tf_idf.query(obama, label='name', k=10) Explanation: Let's compare this distance to the distance between the Barack Obama article and all of its Wikipedia 10 nearest neighbors: End of explanation
7,325
Given the following text problem statement, write Python code to implement the functionality described below in problem statement Problem: import a gpt2 tokenizer to tokenize my text dataset
Python Code:: from transformers import GPT2Tokenizer tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
7,326
Given the following text description, write Python code to implement the functionality described below step by step Description: Use BlackJAX with TFP BlackJAX can take any log-probability function as long as it is compatible with JAX's JIT. In this notebook we show how we can use tensorflow-probability as a modeling language and BlackJAX as an inference library. We reproduce the Eight Schools example from the TFP documentation (all credit for the model goes to the TFP team). For this notebook to run you will need to install tfp-nightly Step1: Data Please refer to the original TFP example for a description of the problem and the model that is used. This notebook focuses exclusively on the possibility to use TFP as a modeling language and BlackJAX as an inference library. Step3: Model Step4: Let us first run the window adaptation to find a good value for the step size and for the inverse mass matrix. As in the original example we will run the integrator 3 times at each step. Step5: BlackJAX does not come with an inference loop (yet) so you have to implement it yourself, which just takes a few lines with JAX Step6: Extra information about the inference is contained in the infos namedtuple. Let us compute the average acceptance rate Step7: The samples are contained as a dictionnary in states.position. Let us compute the posterior of the school treatment effect Step8: And now let us plot the correponding chains and distributions Step9: Compare sampling time with TFP
Python Code: import jax import jax.numpy as jnp import numpy as np from tensorflow_probability.substrates import jax as tfp tfd = tfp.distributions import blackjax Explanation: Use BlackJAX with TFP BlackJAX can take any log-probability function as long as it is compatible with JAX's JIT. In this notebook we show how we can use tensorflow-probability as a modeling language and BlackJAX as an inference library. We reproduce the Eight Schools example from the TFP documentation (all credit for the model goes to the TFP team). For this notebook to run you will need to install tfp-nightly: bash pip install tfp-nightly End of explanation num_schools = 8 # number of schools treatment_effects = np.array( [28, 8, -3, 7, -1, 1, 18, 12], dtype=np.float32 ) # treatment effects treatment_stddevs = np.array( [15, 10, 16, 11, 9, 11, 10, 18], dtype=np.float32 ) # treatment SE Explanation: Data Please refer to the original TFP example for a description of the problem and the model that is used. This notebook focuses exclusively on the possibility to use TFP as a modeling language and BlackJAX as an inference library. End of explanation model = tfd.JointDistributionSequential( [ tfd.Normal(loc=0.0, scale=10.0, name="avg_effect"), # `mu` above tfd.Normal(loc=5.0, scale=1.0, name="avg_stddev"), # `log(tau)` above tfd.Independent( tfd.Normal( loc=jnp.zeros(num_schools), scale=jnp.ones(num_schools), name="school_effects_standard", ), # `theta_prime` reinterpreted_batch_ndims=1, ), lambda school_effects_standard, avg_stddev, avg_effect: ( tfd.Independent( tfd.Normal( loc=( avg_effect[..., jnp.newaxis] + jnp.exp(avg_stddev[..., jnp.newaxis]) * school_effects_standard ), # `theta` above scale=treatment_stddevs, ), name="treatment_effects", # `y` above reinterpreted_batch_ndims=1, ) ), ] ) def target_logprob_fn(avg_effect, avg_stddev, school_effects_standard): Unnormalized target density as a function of states. return model.log_prob( (avg_effect, avg_stddev, school_effects_standard, treatment_effects) ) logprob_fn = lambda x: target_logprob_fn(**x) rng_key = jax.random.PRNGKey(0) initial_position = { "avg_effect": jnp.zeros([]), "avg_stddev": jnp.zeros([]), "school_effects_standard": jnp.ones([num_schools]), } Explanation: Model End of explanation %%time adapt = blackjax.window_adaptation( blackjax.hmc, logprob_fn, 1000, num_integration_steps=3 ) last_state, kernel, _ = adapt.run(rng_key, initial_position) Explanation: Let us first run the window adaptation to find a good value for the step size and for the inverse mass matrix. As in the original example we will run the integrator 3 times at each step. End of explanation %%time def inference_loop(rng_key, kernel, initial_state, num_samples): def one_step(state, rng_key): state, info = kernel(rng_key, state) return state, (state, info) keys = jax.random.split(rng_key, num_samples) _, (states, infos) = jax.lax.scan(one_step, initial_state, keys) return states, infos # Sample from the posterior distribution states, infos = inference_loop(rng_key, kernel, last_state, 500_000) states.position["avg_effect"].block_until_ready() Explanation: BlackJAX does not come with an inference loop (yet) so you have to implement it yourself, which just takes a few lines with JAX: End of explanation acceptance_rate = np.mean(infos.acceptance_probability) print(f"Acceptance rate: {acceptance_rate:.2f}") Explanation: Extra information about the inference is contained in the infos namedtuple. Let us compute the average acceptance rate: End of explanation samples = states.position school_effects_samples = ( samples["avg_effect"][:, np.newaxis] + np.exp(samples["avg_stddev"])[:, np.newaxis] * samples["school_effects_standard"] ) Explanation: The samples are contained as a dictionnary in states.position. Let us compute the posterior of the school treatment effect: End of explanation import seaborn as sns from matplotlib import pyplot as plt fig, axes = plt.subplots(8, 2, sharex="col", sharey="col") fig.set_size_inches(12, 10) for i in range(num_schools): axes[i][0].plot(school_effects_samples[:, i]) axes[i][0].title.set_text(f"School {i} treatment effect chain") sns.kdeplot(school_effects_samples[:, i], ax=axes[i][1], shade=True) axes[i][1].title.set_text(f"School {i} treatment effect distribution") axes[num_schools - 1][0].set_xlabel("Iteration") axes[num_schools - 1][1].set_xlabel("School effect") fig.tight_layout() plt.show() Explanation: And now let us plot the correponding chains and distributions: End of explanation import tensorflow.compat.v2 as tf tf.enable_v2_behavior() %%time num_results = 500_000 num_burnin_steps = 0 # Improve performance by tracing the sampler using `tf.function` # and compiling it using XLA. @tf.function(autograph=False, experimental_compile=True, experimental_relax_shapes=True) def do_sampling(): return tfp.mcmc.sample_chain( num_results=num_results, num_burnin_steps=num_burnin_steps, current_state=[ jnp.zeros([]), jnp.zeros([]), jnp.ones([num_schools]), ], kernel=tfp.mcmc.HamiltonianMonteCarlo( target_log_prob_fn=target_logprob_fn, step_size=0.4, num_leapfrog_steps=3 ), seed=rng_key, ) states, kernel_results = do_sampling() Explanation: Compare sampling time with TFP End of explanation
7,327
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning with Python Speaker Step1: $$ \hat{\theta} = (\mathbf{X}^T \cdot \mathbf{X})^{-1} \cdot \mathbf{X}^T \cdot \mathbf{y} $$ Step2: which is the same result. However ... Normal Equation computes the inverse of $X^T \cdot X$, which is an $n\times n$ matrix (where $n$ is the number of features. The computational complexity of inverting such a matrix is about $O(n^{2.4})$ to $O(n^{3})$<sup>1</sup>. However, again, this equation is linear with the number of training examples so it can handle large training sets efficiently, given that all the training data can fit in memory. <a name="myfootnote1">1</a> Step3: Polynomial Regression lets generate data using the following function $$ y = \frac{1}{2} x^2 + x + 2 + \mu $$ where $ x \in [-3, 3]$ and $\mu \in [0, 1]$ is a random noise. Step4: Clearly, it dose not fit. Step5: now, X_ploy contains not only the original value, but the square of the value too. Step6: our original formula Step7: Preprocessing tool $PloynomialFeatures(degree=d)$ transforms an array containing $n$ features into an array containing $\frac{(n+d)!}{d!n!}$ features. given two features $a$ and $b$, When $degree=3$, it would not only add $a^2, a^3, b^2$ and $b^3$, but also $ab, a^2b$ and $ab^2$. Learning Curves
Python Code: # prepare some data import numpy as np np.random.seed(42) # only if you want reproduceable result X = 2 * np.random.rand(100, 1) y = 4 + 3 * X + np.random.randn(100, 1) %matplotlib inline import matplotlib.pyplot as plt plt.scatter(X, y) # calculate inverse of the matrix X using inv() function # from NumPy's Linear Algebra module X_b = np.c_[np.ones((100, 1)), X] # add x0 = 1 for each instance (why? hint \theta_0 the bias term) theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y) Explanation: Machine Learning with Python Speaker: Yingzhi Gou Decision Systems Lab, University of Wollongong NOTE this jupyter notebook is available on github https://github.com/YingzhiGou/AI-Meetup-Decision-Systems-Lab-UOW Acknowledgement source code in this tutorial is based on the book Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems by Aurélien Géron Understand Training Training is teaching, or developing in oneself or others, any skills and knowledge that relate to specific useful competencies. Training has specific goals of improving one's capability, capacity, productivity and performance. what does it mean for machine learning models? normally involves to find a set of model parameters s.t. the value of a given cost/error function is minimized. one example of the cost functions is Mean Square Error (MSE) How do we train a machine learning model? by using a direct "closed-form"equation that directly computes the model parameters that best fit the model to the training examples (training set). using a iterative optimization approach, called Gradient Descent, that gradually tweaks the model parameters to minimize the cost function Linear Regression This model is a linear function of the input features. Given the input $X = \langle x_1, x_2, \ldots, x_n \rangle$, the linear regression model is defined as, $$ \hat{y} = \theta_0 + \theta_1x_1 + \theta_2x_2 + \ldots + \theta_nx_n $$ where * $\hat{y}$ is the predicted value * $n$ is the number of features (input) * $x_i$ is the value of the $i^{th}$ feature * $\theta_j$ is the $j^{th}$ model parameter * $\theta_0$ is the bias term * $\theta_1, \theta_2, \ldots, \theta_n$ are the feature weights Also in vectorized form $$ \hat{y} = h_{\theta}(X) = \theta^T \cdot X $$ where function $h_\theta$ commonly called hypothesis function using parameter $\theta$. Cost Function Now we need a measure of how well (or poorly) the model fits the training data. A common performance measure of a regression model is Root Mean Square Error (RMSE). the goal of the training is to minimize RMSE over training set. however, in practice, we simply use Mean Square Error (MSE) which is simpler to calculate. $$ MSE(X, h_\theta) = \frac{1}{m}\sum_{i=1}^{m}(\theta^T \cdot X^{(i)} - y^{(i)}) ^2 $$ The Normal Equation To find $\theta$ that minimize the cost function (MSE), there is a close-form solution (recalled the first way of training a model). i.e. there is a mathematical equation that gives the result directly, which is called Normal Equation $$ \hat{\theta} = (\mathbf{X}^T \cdot \mathbf{X})^{-1} \cdot \mathbf{X}^T \cdot \mathbf{y} $$ End of explanation print(theta_best) X_new = np.array([[0],[2]]) X_new_b = np.c_[np.ones((2, 1)), X_new] y_predict = X_new_b.dot(theta_best) print(y_predict) plt.scatter(X, y) plt.plot(X_new, y_predict, "r-") # using Scikit-learn from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(X, y) print(lin_reg.intercept_, lin_reg.coef_) lin_reg.predict(X_new) Explanation: $$ \hat{\theta} = (\mathbf{X}^T \cdot \mathbf{X})^{-1} \cdot \mathbf{X}^T \cdot \mathbf{y} $$ End of explanation def plot_gradient_descent(eta, theta=None, theta_path=None, random_state=None, n_iterations=1000): if random_state: np.random.seed(random_state) if not theta: theta = np.random.randn(2,1) # random initialization m = len(X_b) plt.plot(X, y, "b.") for iteration in range(n_iterations): if iteration < 10: # only plot the first 10 iterations y_predict = X_new_b.dot(theta) style = "b-" if iteration > 0 else "r--" plt.plot(X_new, y_predict, style) gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y) theta = theta - eta * gradients if theta_path is not None: theta_path.append(theta) plt.xlabel("$x_1$", fontsize=18) plt.axis([0, 2, 0, 15]) plt.title(r"$\eta = {}$".format(eta), fontsize=16) # create temp variable to store all theta during training theta_path_1 = [] theta_path_2 = [] theta_path_3 = [] plt.figure(figsize=(10,4)) plt.subplot(131); plot_gradient_descent(eta=0.02, random_state=42, theta_path=theta_path_1) plt.ylabel("$y$", rotation=0, fontsize=18) plt.subplot(132); plot_gradient_descent(eta=0.1, random_state=42, theta_path=theta_path_2) plt.subplot(133); plot_gradient_descent(eta=0.5, random_state=42, theta_path=theta_path_3) plt.show() # convert python list to numpy array theta_path_1 = np.array(theta_path_1) theta_path_2 = np.array(theta_path_2) theta_path_3 = np.array(theta_path_3) # simple a grad for heat map cell_size = 0.05 theta_0s = np.arange(2, 5, cell_size) theta_1s = np.arange(2, 4, cell_size) m = len(X_b) mses = [[np.mean(np.power(X_b.dot([[theta_0], [theta_1]])-y, 2)) for theta_0 in theta_0s] for theta_1 in theta_1s] mses = np.array(mses) plt.pcolor(theta_0s, theta_1s, mses) plt.plot(4, 3, "X", label="target") plt.xlabel(r"$\theta_0$", fontsize=20) plt.ylabel(r"$\theta_1$", fontsize=20, rotation=0) plt.colorbar() plt.show() # let's virsulize the theta change path of different learning rate plt.figure() plt.plot(4, 3, "X", label="target") plt.pcolormesh(theta_0s, theta_1s, mses) plt.plot(theta_path_1[:, 0], theta_path_1[:, 1], "-s", alpha=0.4, linewidth=1, label="eta=0.02") plt.plot(theta_path_2[:, 0], theta_path_2[:, 1], "-+", alpha=0.4, linewidth=2, label="eta=0.1") plt.plot(theta_path_3[:, 0], theta_path_3[:, 1], "-o", alpha=0.4, linewidth=3, label="eta=0.5") plt.legend(loc="upper left", fontsize=16) plt.xlabel(r"$\theta_0$", fontsize=20) plt.ylabel(r"$\theta_1$", fontsize=20, rotation=0) plt.axis([2.5, 4.5, 2.3, 3.9]) plt.colorbar() plt.show() Explanation: which is the same result. However ... Normal Equation computes the inverse of $X^T \cdot X$, which is an $n\times n$ matrix (where $n$ is the number of features. The computational complexity of inverting such a matrix is about $O(n^{2.4})$ to $O(n^{3})$<sup>1</sup>. However, again, this equation is linear with the number of training examples so it can handle large training sets efficiently, given that all the training data can fit in memory. <a name="myfootnote1">1</a>:https://en.wikipedia.org/wiki/Computational_complexity_of_mathematical_operations Gradient Descent Gradient Descent is a very generic optimization algorithm capable of finding (sometimes local) optimal solutions. <img src="https://www.safaribooksonline.com/library/view/hands-on-machine-learning/9781491962282/assets/mlst_0402.png" width=400> <img src="http://what-when-how.com/wp-content/uploads/2012/07/tmpc2f9388_thumb22.png" width=400> <img src="https://sebastianraschka.com/images/blog/2015/singlelayer_neural_networks_files/perceptron_learning_rate.png" width=400/> NOTE: The notation of the diagram are different from ours Partial Derivatives of the Cost Function $$ \frac{\partial}{\partial\theta_j} MSE(\theta) = \frac{2}{m}\sum_{i=1}^{m}(\theta^T\cdot\mathbf{x}^{(i)}-y^{(i)})x_j^{(i)} $$ Gradient Vector of the Cost Function $$ \nabla_{\theta} MSE(\theta) = \begin{pmatrix} \frac{\partial}{\partial\theta_0} MSE(\theta) \ \frac{\partial}{\partial\theta_1} MSE(\theta) \ \vdots \ \frac{\partial}{\partial\theta_n} MSE(\theta) \ \end{pmatrix} = \frac{2}{m} \textbf{X}^T\cdot(\textbf{X}\cdot\theta-\textbf{y}) $$ Gradient Descent Step $$ \theta^{(k+1)} = \theta^{(k)} - \eta \nabla_{\theta^{(k)}} MSE(\theta^{(k)}) $$ End of explanation import numpy as np np.random.seed(42) m = 100 X = 6 * np.random.rand(m, 1) - 3 y = 0.5 * X ** 2 + X + 2 + np.random.randn(m, 1) plt.plot(X, y, "b.") plt.xlabel("$x_1$", fontsize=18) plt.ylabel("$y$", rotation=0, fontsize=18) plt.axis([-3, 3, 0, 10]) plt.show() # use linear model directly lin_reg = LinearRegression() lin_reg.fit(X, y) plt.scatter(X, y) plt.plot(X_new, lin_reg.predict([[-5],[5]]), "r-") Explanation: Polynomial Regression lets generate data using the following function $$ y = \frac{1}{2} x^2 + x + 2 + \mu $$ where $ x \in [-3, 3]$ and $\mu \in [0, 1]$ is a random noise. End of explanation from sklearn.preprocessing import PolynomialFeatures poly_features = PolynomialFeatures(degree=2, include_bias=False) X_poly = poly_features.fit_transform(X) X[0] X_poly[0] Explanation: Clearly, it dose not fit. End of explanation lin_reg.fit(X_poly, y) lin_reg.intercept_, lin_reg.coef_ Explanation: now, X_ploy contains not only the original value, but the square of the value too. End of explanation X_new=np.linspace(-3, 3, 100).reshape(100, 1) X_new_poly = poly_features.transform(X_new) y_new = lin_reg.predict(X_new_poly) plt.plot(X, y, "b.") plt.plot(X_new, y_new, "r-", linewidth=2, label="Predictions") plt.xlabel("$x_1$", fontsize=18) plt.ylabel("$y$", rotation=0, fontsize=18) plt.legend(loc="upper left", fontsize=14) plt.axis([-3, 3, 0, 10]) plt.show() Explanation: our original formula: $$ y = \frac{1}{2} x^2 + x + 2 + \mu $$ regression model: $$ \hat{y} = 0.56456263 x^2 + 0.93366893 x + 1.78134581 $$ End of explanation from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline for style, width, degree in (("g-", 1, 300), ("b--", 2, 2), ("r-+", 2, 1)): poly_features = PolynomialFeatures(degree=degree, include_bias=False) std_scaler = StandardScaler() lin_reg = LinearRegression() polynomial_regression = Pipeline( [ ("poly_features", poly_features), ("std_scaler", std_scaler), ("lin_reg", lin_reg) ] ) polynomial_regression.fit(X, y) y_newbig = polynomial_regression.predict(X_new) plt.plot(X_new, y_newbig, style, label=str(degree), linewidth=width) plt.plot(X, y, "b.", linewidth=3) plt.legend(loc="upper left") plt.xlabel("$x_1$", fontsize=18) plt.ylabel("$y$", rotation=0, fontsize=18) plt.axis([-3, 3, 0, 10]) plt.show() from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split def plot_learning_curves(model, X, y): X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=10) train_errors, val_errors = [], [] for m in range(1, len(X_train)): model.fit(X_train[:m], y_train[:m]) y_train_predict = model.predict(X_train[:m]) y_val_predict = model.predict(X_val) train_errors.append(mean_squared_error(y_train_predict, y_train[:m])) val_errors.append(mean_squared_error(y_val_predict, y_val)) plt.plot(np.sqrt(train_errors), "r-+", linewidth=2, label="train") plt.plot(np.sqrt(val_errors), "b-", linewidth=3, label="val") plt.legend(loc="upper right", fontsize=14) plt.xlabel("Training set size", fontsize=14) plt.ylabel("RMSE", fontsize=14) lin_reg = LinearRegression() plot_learning_curves(lin_reg, X, y) plt.axis([0, 80, 0, 3]) plt.show() from sklearn.pipeline import Pipeline # degree 2 polynomial polynomial_regression = Pipeline([ ("poly_features", PolynomialFeatures(degree=2, include_bias=False)), ("lin_reg", LinearRegression()), ]) plot_learning_curves(polynomial_regression, X, y) plt.axis([0, 80, 0, 3]) plt.show() # degree 10 polynomial polynomial_regression = Pipeline([ ("poly_features", PolynomialFeatures(degree=10, include_bias=False)), ("lin_reg", LinearRegression()), ]) plot_learning_curves(polynomial_regression, X, y) plt.axis([0, 80, 0, 3]) plt.show() # degree 300 polynomial polynomial_regression = Pipeline([ ("poly_features", PolynomialFeatures(degree=300, include_bias=False)), ("lin_reg", LinearRegression()), ]) plot_learning_curves(polynomial_regression, X, y) plt.axis([0, 80, 0, 3]) plt.show() Explanation: Preprocessing tool $PloynomialFeatures(degree=d)$ transforms an array containing $n$ features into an array containing $\frac{(n+d)!}{d!n!}$ features. given two features $a$ and $b$, When $degree=3$, it would not only add $a^2, a^3, b^2$ and $b^3$, but also $ab, a^2b$ and $ab^2$. Learning Curves End of explanation
7,328
Given the following text description, write Python code to implement the functionality described below step by step Description: Dinámica del Amor El modelo describe el estado emotivo de Laura, Petrarca y la Inspración de Petrarca, al paso del tiempo. <table> <tr> <td> <img src="https Step1: Tasa de cambio del estado emotivo de Laura $\frac{dL(t)}{dt}=-\alpha_{1}L(t)+R_{L}(P(t))+\beta_{1}A_{P}$ Tasa de cambio del estado emotivo de Petrarca $\frac{dP(t)}{dt}=-\alpha_{2}L(t)+R_{p}(L(t))+\beta_{2}\frac{A_{L}}{1+\delta Z(t)}$ Tasa de cambio de la inspiración del Poeta $\frac{dZ(t)}{dt}=-\alpha_{3}Z(t)+\beta_{3}P(t)$ Reacción del Poeta a Laura $R_{P}(L)=\gamma_{2}L$ Reacción de la Bella al Poeta $R_{L}(P)=\beta_{1}P\left(1-\left(\frac{P}{\gamma}\right)^{2}\right)$ $\alpha_{1}>\alpha_{2}>\alpha_{3}$ Modelo computacional El modelo se simplifica sustituyendo, en el sistema de ecuaciones de la tasa de cambio emotivo e inspiración, los argumentos de las reacciones de Laura y Petrarca al otro. De esta manera las únicas variables son $L$, $P$ y $Z$. Step2: Espacio fase
Python Code: # Para hacer experimentos numéricos importamos numpy import numpy as np #import pandas as pd # y biblioteca para plotear import matplotlib import matplotlib.pyplot as plt %matplotlib inline # cómputo simbólico con sympy from sympy import * init_printing() Explanation: Dinámica del Amor El modelo describe el estado emotivo de Laura, Petrarca y la Inspración de Petrarca, al paso del tiempo. <table> <tr> <td> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Altichiero%2C_ritratto_di_Francesco_Petrarca.jpg/192px-Altichiero%2C_ritratto_di_Francesco_Petrarca.jpg" /> </td> <td> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/48/Francesco_Petrarca01.jpg/200px-Francesco_Petrarca01.jpg" /> </td> </tr> </table> End of explanation def dL(t): return -3.6 * L[t] + 1.2 * (P[t]*(1-P[t]**2) - 1) def dP(t): return -1.2 * L[t] + 6 * L[t] + 12 / (1 + Z[t]) def dZ(t): return -0.12 * Z[t] + 12 * P[t] years = 20 dt = 0.01 steps = int(years / dt) L = np.zeros(steps) P = np.zeros(steps) Z = np.zeros(steps) for t in range(steps-1): L[t+1] = L[t] + dt*dL(t) P[t+1] = P[t] + dt*dP(t) Z[t+1] = Z[t] + dt*dZ(t) plt.plot(range(steps), P, color='blue') #plt.plot(range(steps), Z/12.0, color='teal') plt.plot(range(steps), L, color='deeppink') plt.xlabel("tiempo (año/100)") plt.ylabel("estado emotivo") plt.plot(range(steps), Z) plt.xlabel("tiempo (año/100)") plt.ylabel("inspiración") Explanation: Tasa de cambio del estado emotivo de Laura $\frac{dL(t)}{dt}=-\alpha_{1}L(t)+R_{L}(P(t))+\beta_{1}A_{P}$ Tasa de cambio del estado emotivo de Petrarca $\frac{dP(t)}{dt}=-\alpha_{2}L(t)+R_{p}(L(t))+\beta_{2}\frac{A_{L}}{1+\delta Z(t)}$ Tasa de cambio de la inspiración del Poeta $\frac{dZ(t)}{dt}=-\alpha_{3}Z(t)+\beta_{3}P(t)$ Reacción del Poeta a Laura $R_{P}(L)=\gamma_{2}L$ Reacción de la Bella al Poeta $R_{L}(P)=\beta_{1}P\left(1-\left(\frac{P}{\gamma}\right)^{2}\right)$ $\alpha_{1}>\alpha_{2}>\alpha_{3}$ Modelo computacional El modelo se simplifica sustituyendo, en el sistema de ecuaciones de la tasa de cambio emotivo e inspiración, los argumentos de las reacciones de Laura y Petrarca al otro. De esta manera las únicas variables son $L$, $P$ y $Z$. End of explanation from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(11,11)) ax = fig.gca(projection='3d') # Make the grid l, p, z = np.meshgrid(np.linspace(-1, 2, 11), np.linspace(-1, 1, 11), np.linspace(0, 18, 11)) # Make the direction data for the arrows u = -3.6 * l + 1.2 * (p*(1-p**2) - 1) v = -1.2 * l + 6 * l + 12 / (1 + z) w = -0.12 * z + 12 * p ax.quiver(l, p, z, u, v, w, length=0.1, normalize=True, arrow_length_ratio=1, colors='deeppink') ax.set_xlabel("P") ax.set_ylabel("L") ax.set_zlabel("Z") ax.plot(P, L, Z) plt.show() fig = plt.figure(figsize=(11,11)) ax = fig.gca(projection='3d') # Make the grid l, p, z = np.meshgrid(np.linspace(-2, 2, 11), np.linspace(-2, 5, 11), np.linspace(-130, -100, 11)) # Make the direction data for the arrows u = -3.6 * l + 1.2 * (p*(1-p**2) - 1) v = -1.2 * l + 6 * l + 12 / (1 + z) w = -0.12 * z + 12 * p ax.quiver(l, p, z, u, v, w, length=0.1, normalize=True, arrow_length_ratio=1, colors='deeppink') years = 20 dt = 0.01 steps = int(years / dt) L = np.zeros(steps) P = np.zeros(steps) Z = np.zeros(steps) L[0]=5 P[0]=-2 Z[0]=-120 for t in range(steps-1): L[t+1] = L[t] + dt*dL(t) P[t+1] = P[t] + dt*dP(t) Z[t+1] = Z[t] + dt*dZ(t) ax.set_xlabel("P") ax.set_ylabel("L") ax.set_zlabel("Z") ax.plot(P, L, Z) plt.show() Explanation: Espacio fase End of explanation
7,329
Given the following text description, write Python code to implement the functionality described below step by step Description: <IMG SRC="https Step1: Step 2. Reading the time series The next step is to import the time series data. Three series are used in this example; the observed groundwater head, the rainfall and the evaporation. The data can be read using different methods, in this case the Pandas read_csv method is used to read the csv files. Each file consists of two columns; a date column called 'Date' and a column containing the values for the time series. The index column is the first column and is read as a date format. The heads series are stored in the variable obs, the rainfall in rain and the evaporation in evap. All variables are transformed to SI-units. Step2: Step 3. Creating the model After reading in the time series, a Pastas Model instance can be created, Model. The Model instance is stored in the variable ml and takes two input arguments; the head time series obs, and a model name Step3: Step 4. Adding stress models A RechargeModel instance is created and stored in the variable rm, taking the rainfall and potential evaporation time series as input arguments, as well as a name and a response function. In this example the Gamma response function is used (the Gamma function is available as ps.Gamma). After creation the recharge stress model instance is added to the model. Step4: Step 5. Solving the model The model parameters are estimated by calling the solve method of the Model instance. In this case the default settings are used (for all but the tmax argument) to solve the model. Several options can be specified in the .solve method, for example; a tmin and tmax or the type of solver used (this defaults to a least squares solver, ps.LeastSquares). This solve method prints a fit report with basic information about the model setup and the results of the model fit. Step5: Step 6. Visualizing the results The final step of the "cookbook" recipe is to visualize the results of the TFN model. The Pastas package has several build in plotting methods, available through the ml.plots instance. Here the .results plotting method is used. This method plots an overview of the model results, including the simulation and the observations of the groundwater head, the optimized model parameters, the residuals and the noise, the contribution of each stressmodel, and the step response function for each stressmodel. Step6: 7. Diagnosing the noise series The diagnostics plot can be used to interpret how well the noise follows a normal distribution and suffers from autocorrelation (or not). Step7: Make plots for publication In the next codeblocks the Figures used in the Pastas paper are created. The first codeblock sets the matplotlib parameters to obtain publication-quality figures. The following figures are created Step8: Make a plot of the impulse and step response for the Gamma and Hantush functions Step9: Make a plot of the stresses used in the model Step10: Make a custom figure of the model fit and the estimated step response Step11: Make a figure of the fit report Step12: Make a Figure of the noise, residuals and autocorrelation
Python Code: import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import pastas as ps ps.set_log_level("ERROR") %matplotlib inline # This notebook has been developed using Pastas version 0.9.9 and Python 3.7 print("Pastas version: {}".format(ps.__version__)) print("Pandas version: {}".format(pd.__version__)) print("Numpy version: {}".format(np.__version__)) print("Python version: {}".format(os.sys.version)) Explanation: <IMG SRC="https://raw.githubusercontent.com/pastas/pastas/master/doc/_static/logo.png" WIDTH=250 ALIGN="right"> Example 1: Pastas Cookbook recipe This notebook is supplementary material to the following paper submitted to Groundwater: R.A. Collenteur, M. Bakker, R. Calje, S. Klop, F. Schaars, (2019) Pastas: open source software for the analysis of groundwater time series, Manuscript under review. In this notebook the Pastas "cookbook" recipe is shown. In this example it is investigated how well the heads measured in a borehole near Kingstown, Rhode Island, US, can be simulated using rainfall and potential evaporation. A transfer function noise (TFN) model using impulse response function is created to simulate the observed heads. The observed heads are obtained from the Ground-Water Climate Response Network (CRN) of the USGS (https://groundwaterwatch.usgs.gov/). The corresponding USGS site id is 412918071321001. The rainfall data is taken from the Global Summary of the Day dataset (GSOD) available at the National Climatic Data Center (NCDC). The rainfall series is obtained from the weather station in Kingston (station number: NCDC WBAN 54796) located at 41.491$^\circ$, -71.541$^\circ$. The evaporation is calculated from the mean temperature obtained from the same USGS station using Thornthwaite's method (Pereira and Pruitt, 2004). Pereira AR, Pruitt WO (2004), Adaptation of the Thornthwaite scheme for estimating daily reference evapotranspiration, Agricultural Water Management 66(3), 251-257 Step 1. Importing the python packages The first step to creating the TFN model is to import the python packages. In this notebook two packages are used, the Pastas package and the Pandas package to import the time series data. Both packages are short aliases for convenience (ps for the Pastas package and pd for the Pandas package). The other packages that are imported are not needed for the analysis but are needed to make the publication figures. End of explanation obs = pd.read_csv('obs.csv', index_col='Date', parse_dates=True) * 0.3048 rain = pd.read_csv('rain.csv', index_col='Date', parse_dates=True) * 0.3048 rain = rain.asfreq("D", fill_value=0.0) # There are some nan-values present evap = pd.read_csv('evap.csv', index_col='Date', parse_dates=True) * 0.3048 Explanation: Step 2. Reading the time series The next step is to import the time series data. Three series are used in this example; the observed groundwater head, the rainfall and the evaporation. The data can be read using different methods, in this case the Pandas read_csv method is used to read the csv files. Each file consists of two columns; a date column called 'Date' and a column containing the values for the time series. The index column is the first column and is read as a date format. The heads series are stored in the variable obs, the rainfall in rain and the evaporation in evap. All variables are transformed to SI-units. End of explanation ml = ps.Model(obs.loc[::14], name='Kingstown') Explanation: Step 3. Creating the model After reading in the time series, a Pastas Model instance can be created, Model. The Model instance is stored in the variable ml and takes two input arguments; the head time series obs, and a model name: "Kingstown". End of explanation rm = ps.RechargeModel(rain, evap, name='recharge', rfunc=ps.Gamma) ml.add_stressmodel(rm) Explanation: Step 4. Adding stress models A RechargeModel instance is created and stored in the variable rm, taking the rainfall and potential evaporation time series as input arguments, as well as a name and a response function. In this example the Gamma response function is used (the Gamma function is available as ps.Gamma). After creation the recharge stress model instance is added to the model. End of explanation ml.solve(tmax="2014"); # Print some information on the model fit for the validation period print("\nThe R2 and the RMSE in the validation period are ", ml.stats.rsq(tmin="2015", tmax="2019").round(2), "and", ml.stats.rmse(tmin="2015", tmax="2019").round(2), ", respectively.") Explanation: Step 5. Solving the model The model parameters are estimated by calling the solve method of the Model instance. In this case the default settings are used (for all but the tmax argument) to solve the model. Several options can be specified in the .solve method, for example; a tmin and tmax or the type of solver used (this defaults to a least squares solver, ps.LeastSquares). This solve method prints a fit report with basic information about the model setup and the results of the model fit. End of explanation ml.plots.results(tmax="2018"); Explanation: Step 6. Visualizing the results The final step of the "cookbook" recipe is to visualize the results of the TFN model. The Pastas package has several build in plotting methods, available through the ml.plots instance. Here the .results plotting method is used. This method plots an overview of the model results, including the simulation and the observations of the groundwater head, the optimized model parameters, the residuals and the noise, the contribution of each stressmodel, and the step response function for each stressmodel. End of explanation ml.plots.diagnostics() Explanation: 7. Diagnosing the noise series The diagnostics plot can be used to interpret how well the noise follows a normal distribution and suffers from autocorrelation (or not). End of explanation # Set matplotlib params to create publication figures params = { 'axes.labelsize': 18, 'axes.grid': True, 'font.size': 16, 'font.family': 'serif', 'legend.fontsize': 16, 'xtick.labelsize': 16, 'ytick.labelsize': 16, 'text.usetex': False, 'figure.figsize': [8.2, 5], 'lines.linewidth' : 2 } plt.rcParams.update(params) # Save figures or not savefig = True figpath = "figures" if not os.path.exists(figpath): os.mkdir(figpath) Explanation: Make plots for publication In the next codeblocks the Figures used in the Pastas paper are created. The first codeblock sets the matplotlib parameters to obtain publication-quality figures. The following figures are created: Figure of the impulse and step respons for the scaled Gamma response function Figure of the stresses used in the model Figure of the modelfit and the step response Figure of the model fit as returned by Pastas Figure of the model residuals and noise Figure of the Autocorrelation function End of explanation rfunc = ps.Gamma(cutoff=0.999) p = [100, 1.5, 15] b = np.append(0, rfunc.block(p)) s = rfunc.step(p) rfunc2 = ps.Hantush(cutoff=0.999) p2 = [-100, 4, 15] b2 = np.append(0, rfunc2.block(p2)) s2 = rfunc2.step(p2) # Make a figure of the step and block response fig, [ax1, ax2] = plt.subplots(1, 2, sharex=True, figsize=(8, 4)) ax1.plot(b) ax1.plot(b2) ax1.set_ylabel("block response") ax1.set_xlabel("days") ax1.legend(["Gamma", "Hantush"], handlelength=1.3) ax1.axhline(0.0, linestyle="--", c="k") ax2.plot(s) ax2.plot(s2) ax2.set_xlim(0,100) ax2.set_ylim(-105, 105) ax2.set_ylabel("step response") ax2.set_xlabel("days") ax2.axhline(0.0, linestyle="--", c="k") ax2.annotate('', xy=(95, 100), xytext=(95, 0), arrowprops={'arrowstyle': '<->'}) ax2.annotate('A', xy=(95, 100), xytext=(85, 50)) ax2.annotate('', xy=(95, -100), xytext=(95, 0), arrowprops={'arrowstyle': '<->'}) ax2.annotate('A', xy=(95, 100), xytext=(85, -50)) plt.tight_layout() if savefig: path = os.path.join(figpath, "impuls_step_response.eps") plt.savefig(path, dpi=300, bbox_inches="tight") Explanation: Make a plot of the impulse and step response for the Gamma and Hantush functions End of explanation fig, [ax1, ax2, ax3] = plt.subplots(3,1, sharex=True, figsize=(8, 7)) ax1.plot(obs, 'k.',label='obs', markersize=2) ax1.set_ylabel('head (m)', labelpad=0) ax1.set_yticks([-4, -3, -2]) plot_rain = ax2.plot(rain * 1000, color='k', label='prec', linewidth=1) ax2.set_ylabel('rain (mm/d)', labelpad=-5) ax2.set_xlabel('Date'); ax2.set_ylim([0,150]) ax2.set_yticks(np.arange(0, 151, 50)) plot_evap = ax3.plot(evap * 1000,'k', label='evap', linewidth=1) ax3.set_ylabel('evap (mm/d)') ax3.tick_params('y') ax3.set_ylim([0,8]) plt.xlim(['2003','2019']) plt.xticks([str(x) for x in np.arange(2004, 2019, 2)], rotation=0, horizontalalignment='center') ax2.set_xlabel("") ax3.set_xlabel("year") if savefig: path = os.path.join(figpath, "data_example_1.eps") plt.savefig(path, bbox_inches='tight', dpi=300) Explanation: Make a plot of the stresses used in the model End of explanation # Create the main plot fig, ax = plt.subplots(figsize=(16,5)) ax.plot(obs, marker=".", c="grey", linestyle=" ") ax.plot(obs.loc[:"2013":14], marker="x", markersize=7, c="C3", linestyle=" ", mew=2) ax.plot(ml.simulate(tmax="2019"), c="k") plt.ylabel('head (m)') plt.xlabel('year') plt.title("") plt.xticks([str(x) for x in np.arange(2004, 2019, 2)], rotation=0, horizontalalignment='center') plt.xlim('2003', '2019') plt.ylim(-4.7, -1.6) plt.yticks(np.arange(-4, -1, 1)) # Create the arrows indicating the calibration and validation period ax.annotate("calibration period", xy=("2003-01-01", -4.6), xycoords='data', xytext=(300, 0), textcoords='offset points', arrowprops=dict(arrowstyle="->"), va="center", ha="center") ax.annotate("", xy=("2014-01-01", -4.6), xycoords='data', xytext=(-230, 0), textcoords='offset points', arrowprops=dict(arrowstyle="->"), va="center", ha="center") ax.annotate("validation", xy=("2014-01-01", -4.6), xycoords='data', xytext=(150, 0), textcoords='offset points', arrowprops=dict(arrowstyle="->"), va="center", ha="center") ax.annotate("", xy=("2019-01-01", -4.6), xycoords='data', xytext=(-85, 0), textcoords='offset points', arrowprops=dict(arrowstyle="->"), va="center", ha="center") plt.legend(["observed head", "used for calibration","simulated head"], loc=2, numpoints=3) # Create the inset plot with the step response ax2 = plt.axes([0.66, 0.65, 0.22, 0.2]) s = ml.get_step_response("recharge") ax2.plot(s, c="k") ax2.set_ylabel("response") ax2.set_xlabel("days", labelpad=-15) ax2.set_xlim(0, s.index.size) ax2.set_xticks([0, 300]) if savefig: path = os.path.join(figpath, "results.eps") plt.savefig(path, bbox_inches='tight', dpi=300) Explanation: Make a custom figure of the model fit and the estimated step response End of explanation from matplotlib.font_manager import FontProperties font = FontProperties() #font.set_size(10) font.set_weight('normal') font.set_family('monospace') font.set_name("courier new") plt.text(-1, -1, str(ml.fit_report()), fontproperties=font) plt.axis('off') plt.tight_layout() if savefig: path = os.path.join(figpath, "fit_report.eps") plt.savefig(path, bbox_inches='tight', dpi=600) Explanation: Make a figure of the fit report End of explanation fig, ax1 = plt.subplots(1,1, figsize=(8, 3)) ml.residuals(tmax="2019").plot(ax=ax1, c="k") ml.noise(tmax="2019").plot(ax=ax1, c="C0") plt.xticks([str(x) for x in np.arange(2004, 2019, 2)], rotation=0, horizontalalignment='center') ax1.set_ylabel('(m)') ax1.set_xlabel('year') ax1.legend(["residuals", "noise"], ncol=2) if savefig: path = os.path.join(figpath, "residuals.eps") plt.savefig(path, bbox_inches='tight', dpi=300) fig, ax2 = plt.subplots(1,1, figsize=(9, 2)) n =ml.noise() conf = 1.96 / np.sqrt(n.index.size) acf = ps.stats.acf(n) ax2.axhline(conf, linestyle='--', color="dimgray") ax2.axhline(-conf, linestyle='--', color="dimgray") ax2.stem(acf.index, acf.values) ax2.set_ylabel('ACF (-)') ax2.set_xlabel('lag (days)') plt.xlim(0, 370) plt.ylim(-0.25, 0.25) plt.legend(["95% confidence interval"]) if savefig: path = os.path.join(figpath, "acf.eps") plt.savefig(path, bbox_inches='tight', dpi=300) h, test = ps.stats.ljung_box(ml.noise()) print("The hypothesis that there is significant autocorrelation is:", h) test Explanation: Make a Figure of the noise, residuals and autocorrelation End of explanation
7,330
Given the following text description, write Python code to implement the functionality described below step by step Description: NumPy Numerical Python Provides an efficient way to store and manipulate arrays. Numpy is all about VECTORIZATION. Mental model is different than regular python and works with Step1: Example of Cell Magic Using 3 '%%%' Step2: Line magic uses 1 '%' Example Using Functional Programming Remove class definition Step3: small improvement in time Vectorized Approach Like When You Did Things in MATLAB Step4: WOW 2x as fast Numpy ifying Step5: Getting Started with Basic Numpy Array Create an array Clobber the namespace so we dont have to np.<name> Step6: Create an np array. You can pass any type of python seq Step7: Multidimensional array using list of lists Step8: Reshape and Resize Operations Step9: Do Some Vector Math Not for Loop Math Step10: %%capture <varname> captures the result of the operation into a var Step11: Statistical Analysis
Python Code: import random class RandomWalker(object): def __init__(self): self.position = 0 def walk(self, n): self.position = 0 for i in range(n): yield self.position self.position += 2*random.randint(0,1) - 1 Explanation: NumPy Numerical Python Provides an efficient way to store and manipulate arrays. Numpy is all about VECTORIZATION. Mental model is different than regular python and works with: - "vectors" - "arrays" - "views" - "ufuncs" advanced - ndarray provides efficient storage and manipulation of 1d arrays (vectors), (NxM) matrices, higher dimensional datasets Example Using Object Oriented Techniques End of explanation %%%timeit walker = RandomWalker() walk = [position for position in walker.walk(10000)] Explanation: Example of Cell Magic Using 3 '%%%' End of explanation def random_walk_f(n): position = 0 walk = [position] for i in range(n): position = 2 * random.randint(0,1) - 1 walk.append(position) return walk %%%timeit walk = random_walk_f(10000) Explanation: Line magic uses 1 '%' Example Using Functional Programming Remove class definition End of explanation from itertools import accumulate def random_walker_v(n): steps = random.sample([1, -1] * n, n) return list(accumulate(steps)) %%%timeit walk = random_walker_v(10000) Explanation: small improvement in time Vectorized Approach Like When You Did Things in MATLAB :( Get rid of the loop End of explanation import numpy as np def random_walker_np(n): steps = 2 * np.random.randint(0, 2, size=n) - 1 return np.cumsum(steps) %%%timeit walk = random_walker_np(10000) Explanation: WOW 2x as fast Numpy ifying End of explanation import numpy as np Explanation: Getting Started with Basic Numpy Array Create an array Clobber the namespace so we dont have to np.<name> End of explanation a = np.array([0,1,2,3,4,5]) a Explanation: Create an np array. You can pass any type of python seq: list, tuples, etc End of explanation m = np.array([[1,2,3], [4,5,6]]) m.shape ad = a.data list(ad) # what type is a type(a) # what is the numerica type of the elements in the array a.dtype # What shape (dimensions) is the array a.shape # Bytes per element. 32bit integers should be 4 bytes a.itemsize # Total size in bytes of the array a.nbytes # Beware of type coercion # a holds dtypes int32 print(a) a[0] = 10.38383 print(a) x = np.array([0,1,1.5,3]) y = np.array([1,2,3,1]) Explanation: Multidimensional array using list of lists End of explanation # Element wise addition # Element wise subtraction Explanation: Reshape and Resize Operations End of explanation %%%timeit dy = y[1:] - y[:-1] Explanation: Do Some Vector Math Not for Loop Math End of explanation %%capture timeit_result %timeit python_list1 = range(1,1000) %timeit python_list2 = np.arange(1,1000) print(timeit_result) Explanation: %%capture <varname> captures the result of the operation into a var End of explanation data_set = random.random((2,3)) print(data_set) # example of namespace....cant access np.max and builtin max is being used max(data_set[0]) Explanation: Statistical Analysis End of explanation
7,331
Given the following text description, write Python code to implement the functionality described. Description: Program for sum of cosh ( x ) series upto Nth term function to return the factorial of a number ; function to return the Sum of the series ; Driver code
Python Code: def fact(n ) : i , fac = 1 , 1 for i in range(1 , n + 1 ) : fac = fac * i  return fac  def log_Expansion(x , n ) : Sum = 0 i = 0 for i in range(n ) : Sum = Sum + pow(x , 2 * i ) / fact(2 * i )  return Sum  x = 1 n = 10 print(log_Expansion(x , n ) )
7,332
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2021 The TensorFlow Authors. Step1: TensorFlow Lite Metadata Writer API <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step2: Create Model Metadata for Task Library and Codegen <a name=image_classifiers></a> Image classifiers See the image classifier model compatibility requirements for more details about the supported model format. Step 1 Step3: Step 2 Step4: Step 3 Step5: <a name=object_detectors></a> Object detectors See the object detector model compatibility requirements for more details about the supported model format. Step 1 Step6: Step 2 Step7: Step 3 Step8: <a name=image_segmenters></a> Image segmenters See the image segmenter model compatibility requirements for more details about the supported model format. Step 1 Step9: Step 2 Step10: Step 3 Step11: <a name=nl_classifiers></a> Natural language classifiers See the natural language classifier model compatibility requirements for more details about the supported model format. Step 1 Step12: Step 2 Step13: Step 3 Step14: <a name=audio_classifiers></a> Audio classifiers See the audio classifier model compatibility requirements for more details about the supported model format. Step 1 Step15: Step 2 Step16: Step 3 Step17: Create Model Metadata with semantic information You can fill in more descriptive information about the model and each tensor through the Metadata Writer API to help improve model understanding. It can be done through the 'create_from_metadata_info' method in each metadata writer. In general, you can fill in data through the parameters of 'create_from_metadata_info', i.e. general_md, input_md, and output_md. See the example below to create a rich Model Metadata for image classifers. Step 1 Step18: Step 2 Step19: Step 3 Step20: Step 4 Step21: Read the metadata populated to your model. You can display the metadata and associated files in a TFLite model through the following code
Python Code: #@title 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 # # https://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. Explanation: Copyright 2021 The TensorFlow Authors. End of explanation !pip install tflite-support-nightly Explanation: TensorFlow Lite Metadata Writer API <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/lite/models/convert/metadata_writer_tutorial"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/models/convert/metadata_writer_tutorial.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/g3doc/models/convert/metadata_writer_tutorial.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/tensorflow/tensorflow/lite/g3doc/models/convert/metadata_writer_tutorial.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table> TensorFlow Lite Model Metadata is a standard model description format. It contains rich semantics for general model information, inputs/outputs, and associated files, which makes the model self-descriptive and exchangeable. Model Metadata is currently used in the following two primary use cases: 1. Enable easy model inference using TensorFlow Lite Task Library and codegen tools. Model Metadata contains the mandatory information required during inference, such as label files in image classification, sampling rate of the audio input in audio classification, and tokenizer type to process input string in Natural Language models. Enable model creators to include documentation, such as description of model inputs/outputs or how to use the model. Model users can view these documentation via visualization tools such as Netron. TensorFlow Lite Metadata Writer API provides an easy-to-use API to create Model Metadata for popular ML tasks supported by the TFLite Task Library. This notebook shows examples on how the metadata should be populated for the following tasks below: Image classifiers Object detectors Image segmenters Natural language classifiers Audio classifiers Metadata writers for BERT natural language classifiers and BERT question answerers are coming soon. If you want to add metadata for use cases that are not supported, please use the Flatbuffers Python API. See the tutorials here. Prerequisites Install the TensorFlow Lite Support Pypi package. End of explanation from tflite_support.metadata_writers import image_classifier from tflite_support.metadata_writers import writer_utils Explanation: Create Model Metadata for Task Library and Codegen <a name=image_classifiers></a> Image classifiers See the image classifier model compatibility requirements for more details about the supported model format. Step 1: Import the required packages. End of explanation !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/image_classifier/mobilenet_v2_1.0_224.tflite -o mobilenet_v2_1.0_224.tflite !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/image_classifier/labels.txt -o mobilenet_labels.txt Explanation: Step 2: Download the example image classifier, mobilenet_v2_1.0_224.tflite, and the label file. End of explanation ImageClassifierWriter = image_classifier.MetadataWriter _MODEL_PATH = "mobilenet_v2_1.0_224.tflite" # Task Library expects label files that are in the same format as the one below. _LABEL_FILE = "mobilenet_labels.txt" _SAVE_TO_PATH = "mobilenet_v2_1.0_224_metadata.tflite" # Normalization parameters is required when reprocessing the image. It is # optional if the image pixel values are in range of [0, 255] and the input # tensor is quantized to uint8. See the introduction for normalization and # quantization parameters below for more details. # https://www.tensorflow.org/lite/models/convert/metadata#normalization_and_quantization_parameters) _INPUT_NORM_MEAN = 127.5 _INPUT_NORM_STD = 127.5 # Create the metadata writer. writer = ImageClassifierWriter.create_for_inference( writer_utils.load_file(_MODEL_PATH), [_INPUT_NORM_MEAN], [_INPUT_NORM_STD], [_LABEL_FILE]) # Verify the metadata generated by metadata writer. print(writer.get_metadata_json()) # Populate the metadata into the model. writer_utils.save_file(writer.populate(), _SAVE_TO_PATH) Explanation: Step 3: Create metadata writer and populate. End of explanation from tflite_support.metadata_writers import object_detector from tflite_support.metadata_writers import writer_utils Explanation: <a name=object_detectors></a> Object detectors See the object detector model compatibility requirements for more details about the supported model format. Step 1: Import the required packages. End of explanation !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/object_detector/ssd_mobilenet_v1.tflite -o ssd_mobilenet_v1.tflite !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/object_detector/labelmap.txt -o ssd_mobilenet_labels.txt Explanation: Step 2: Download the example object detector, ssd_mobilenet_v1.tflite, and the label file. End of explanation ObjectDetectorWriter = object_detector.MetadataWriter _MODEL_PATH = "ssd_mobilenet_v1.tflite" # Task Library expects label files that are in the same format as the one below. _LABEL_FILE = "ssd_mobilenet_labels.txt" _SAVE_TO_PATH = "ssd_mobilenet_v1_metadata.tflite" # Normalization parameters is required when reprocessing the image. It is # optional if the image pixel values are in range of [0, 255] and the input # tensor is quantized to uint8. See the introduction for normalization and # quantization parameters below for more details. # https://www.tensorflow.org/lite/models/convert/metadata#normalization_and_quantization_parameters) _INPUT_NORM_MEAN = 127.5 _INPUT_NORM_STD = 127.5 # Create the metadata writer. writer = ObjectDetectorWriter.create_for_inference( writer_utils.load_file(_MODEL_PATH), [_INPUT_NORM_MEAN], [_INPUT_NORM_STD], [_LABEL_FILE]) # Verify the metadata generated by metadata writer. print(writer.get_metadata_json()) # Populate the metadata into the model. writer_utils.save_file(writer.populate(), _SAVE_TO_PATH) Explanation: Step 3: Create metadata writer and populate. End of explanation from tflite_support.metadata_writers import image_segmenter from tflite_support.metadata_writers import writer_utils Explanation: <a name=image_segmenters></a> Image segmenters See the image segmenter model compatibility requirements for more details about the supported model format. Step 1: Import the required packages. End of explanation !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/image_segmenter/deeplabv3.tflite -o deeplabv3.tflite !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/image_segmenter/labelmap.txt -o deeplabv3_labels.txt Explanation: Step 2: Download the example image segmenter, deeplabv3.tflite, and the label file. End of explanation ImageSegmenterWriter = image_segmenter.MetadataWriter _MODEL_PATH = "deeplabv3.tflite" # Task Library expects label files that are in the same format as the one below. _LABEL_FILE = "deeplabv3_labels.txt" _SAVE_TO_PATH = "deeplabv3_metadata.tflite" # Normalization parameters is required when reprocessing the image. It is # optional if the image pixel values are in range of [0, 255] and the input # tensor is quantized to uint8. See the introduction for normalization and # quantization parameters below for more details. # https://www.tensorflow.org/lite/models/convert/metadata#normalization_and_quantization_parameters) _INPUT_NORM_MEAN = 127.5 _INPUT_NORM_STD = 127.5 # Create the metadata writer. writer = ImageSegmenterWriter.create_for_inference( writer_utils.load_file(_MODEL_PATH), [_INPUT_NORM_MEAN], [_INPUT_NORM_STD], [_LABEL_FILE]) # Verify the metadata generated by metadata writer. print(writer.get_metadata_json()) # Populate the metadata into the model. writer_utils.save_file(writer.populate(), _SAVE_TO_PATH) Explanation: Step 3: Create metadata writer and populate. End of explanation from tflite_support.metadata_writers import nl_classifier from tflite_support.metadata_writers import metadata_info from tflite_support.metadata_writers import writer_utils Explanation: <a name=nl_classifiers></a> Natural language classifiers See the natural language classifier model compatibility requirements for more details about the supported model format. Step 1: Import the required packages. End of explanation !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/nl_classifier/movie_review.tflite -o movie_review.tflite !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/nl_classifier/labels.txt -o movie_review_labels.txt !curl -L https://storage.googleapis.com/download.tensorflow.org/models/tflite_support/nl_classifier/vocab.txt -o movie_review_vocab.txt Explanation: Step 2: Download the example natural language classifier, movie_review.tflite, the label file, and the vocab file. End of explanation NLClassifierWriter = nl_classifier.MetadataWriter _MODEL_PATH = "movie_review.tflite" # Task Library expects label files and vocab files that are in the same formats # as the ones below. _LABEL_FILE = "movie_review_labels.txt" _VOCAB_FILE = "movie_review_vocab.txt" # NLClassifier supports tokenize input string using the regex tokenizer. See # more details about how to set up RegexTokenizer below: # https://github.com/tensorflow/tflite-support/blob/master/tensorflow_lite_support/metadata/python/metadata_writers/metadata_info.py#L130 _DELIM_REGEX_PATTERN = r"[^\w\']+" _SAVE_TO_PATH = "moview_review_metadata.tflite" # Create the metadata writer. writer = nl_classifier.MetadataWriter.create_for_inference( writer_utils.load_file(_MODEL_PATH), metadata_info.RegexTokenizerMd(_DELIM_REGEX_PATTERN, _VOCAB_FILE), [_LABEL_FILE]) # Verify the metadata generated by metadata writer. print(writer.get_metadata_json()) # Populate the metadata into the model. writer_utils.save_file(writer.populate(), _SAVE_TO_PATH) Explanation: Step 3: Create metadata writer and populate. End of explanation from tflite_support.metadata_writers import audio_classifier from tflite_support.metadata_writers import metadata_info from tflite_support.metadata_writers import writer_utils Explanation: <a name=audio_classifiers></a> Audio classifiers See the audio classifier model compatibility requirements for more details about the supported model format. Step 1: Import the required packages. End of explanation !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/audio_classifier/yamnet_wavin_quantized_mel_relu6.tflite -o yamnet.tflite !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/audio_classifier/yamnet_521_labels.txt -o yamnet_labels.txt Explanation: Step 2: Download the example audio classifier, yamnet.tflite, and the label file. End of explanation AudioClassifierWriter = audio_classifier.MetadataWriter _MODEL_PATH = "yamnet.tflite" # Task Library expects label files that are in the same format as the one below. _LABEL_FILE = "yamnet_labels.txt" # Expected sampling rate of the input audio buffer. _SAMPLE_RATE = 16000 # Expected number of channels of the input audio buffer. Note, Task library only # support single channel so far. _CHANNELS = 1 _SAVE_TO_PATH = "yamnet_metadata.tflite" # Create the metadata writer. writer = AudioClassifierWriter.create_for_inference( writer_utils.load_file(_MODEL_PATH), _SAMPLE_RATE, _CHANNELS, [_LABEL_FILE]) # Verify the metadata generated by metadata writer. print(writer.get_metadata_json()) # Populate the metadata into the model. writer_utils.save_file(writer.populate(), _SAVE_TO_PATH) Explanation: Step 3: Create metadata writer and populate. End of explanation from tflite_support.metadata_writers import image_classifier from tflite_support.metadata_writers import metadata_info from tflite_support.metadata_writers import writer_utils from tflite_support import metadata_schema_py_generated as _metadata_fb Explanation: Create Model Metadata with semantic information You can fill in more descriptive information about the model and each tensor through the Metadata Writer API to help improve model understanding. It can be done through the 'create_from_metadata_info' method in each metadata writer. In general, you can fill in data through the parameters of 'create_from_metadata_info', i.e. general_md, input_md, and output_md. See the example below to create a rich Model Metadata for image classifers. Step 1: Import the required packages. End of explanation !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/image_classifier/mobilenet_v2_1.0_224.tflite -o mobilenet_v2_1.0_224.tflite !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/image_classifier/labels.txt -o mobilenet_labels.txt Explanation: Step 2: Download the example image classifier, mobilenet_v2_1.0_224.tflite, and the label file. End of explanation model_buffer = writer_utils.load_file("mobilenet_v2_1.0_224.tflite") # Create general model information. general_md = metadata_info.GeneralMd( name="ImageClassifier", version="v1", description=("Identify the most prominent object in the image from a " "known set of categories."), author="TensorFlow Lite", licenses="Apache License. Version 2.0") # Create input tensor information. input_md = metadata_info.InputImageTensorMd( name="input image", description=("Input image to be classified. The expected image is " "128 x 128, with three channels (red, blue, and green) per " "pixel. Each element in the tensor is a value between min and " "max, where (per-channel) min is [0] and max is [255]."), norm_mean=[127.5], norm_std=[127.5], color_space_type=_metadata_fb.ColorSpaceType.RGB, tensor_type=writer_utils.get_input_tensor_types(model_buffer)[0]) # Create output tensor information. output_md = metadata_info.ClassificationTensorMd( name="probability", description="Probabilities of the 1001 labels respectively.", label_files=[ metadata_info.LabelFileMd(file_path="mobilenet_labels.txt", locale="en") ], tensor_type=writer_utils.get_output_tensor_types(model_buffer)[0]) Explanation: Step 3: Create model and tensor information. End of explanation ImageClassifierWriter = image_classifier.MetadataWriter # Create the metadata writer. writer = ImageClassifierWriter.create_from_metadata_info( model_buffer, general_md, input_md, output_md) # Verify the metadata generated by metadata writer. print(writer.get_metadata_json()) # Populate the metadata into the model. writer_utils.save_file(writer.populate(), _SAVE_TO_PATH) Explanation: Step 4: Create metadata writer and populate. End of explanation from tflite_support import metadata displayer = metadata.MetadataDisplayer.with_model_file("mobilenet_v2_1.0_224_metadata.tflite") print("Metadata populated:") print(displayer.get_metadata_json()) print("Associated file(s) populated:") for file_name in displayer.get_packed_associated_file_list(): print("file name: ", file_name) print("file content:") print(displayer.get_associated_file_buffer(file_name)) Explanation: Read the metadata populated to your model. You can display the metadata and associated files in a TFLite model through the following code: End of explanation
7,333
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Face Generation In this project, you'll use generative adversarial networks to generate new images of faces. Get the Data You'll be using two datasets in this project Step3: Explore the Data MNIST As you're aware, the MNIST dataset contains images of handwritten digits. You can view the first number of examples by changing show_n_images. Step5: CelebA The CelebFaces Attributes Dataset (CelebA) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations. You can view the first number of examples by changing show_n_images. Step7: Preprocess the Data Since the project's main focus is on building the GANs, we'll preprocess the data for you. The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images. The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28. The MNIST images are black and white images with a single [color channel](https Step10: Input Implement the model_inputs function to create TF Placeholders for the Neural Network. It should create the following placeholders Step13: Discriminator Implement discriminator to create a discriminator neural network that discriminates on images. This function should be able to reuse the variables in the neural network. Use tf.variable_scope with a scope name of "discriminator" to allow the variables to be reused. The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator). Step16: Generator Implement generator to generate an image using z. This function should be able to reuse the variables in the neural network. Use tf.variable_scope with a scope name of "generator" to allow the variables to be reused. The function should return the generated 28 x 28 x out_channel_dim images. Step19: Loss Implement model_loss to build the GANs for training and calculate the loss. The function should return a tuple of (discriminator loss, generator loss). Use the following functions you implemented Step22: Optimization Implement model_opt to create the optimization operations for the GANs. Use tf.trainable_variables to get all the trainable variables. Filter the variables with names that are in the discriminator and generator scope names. The function should return a tuple of (discriminator training operation, generator training operation). Step25: Neural Network Training Show Output Use this function to show the current output of the generator during training. It will help you determine how well the GANs is training. Step27: Train Implement train to build and train the GANs. Use the following functions you implemented Step29: MNIST Test your GANs architecture on MNIST. After 2 epochs, the GANs should be able to generate images that look like handwritten digits. Make sure the loss of the generator is lower than the loss of the discriminator or close to 0. Step31: CelebA Run your GANs on CelebA. It will take around 20 minutes on the average GPU to run one epoch. You can run the whole epoch or stop when it starts to generate realistic faces.
Python Code: data_dir = './data' # FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe" #data_dir = '/input' DON'T MODIFY ANYTHING IN THIS CELL import helper helper.download_extract('mnist', data_dir) helper.download_extract('celeba', data_dir) Explanation: Face Generation In this project, you'll use generative adversarial networks to generate new images of faces. Get the Data You'll be using two datasets in this project: - MNIST - CelebA Since the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural network on MNIST before CelebA. Running the GANs on MNIST will allow you to see how well your model trains sooner. If you're using FloydHub, set data_dir to "/input" and use the FloydHub data ID "R5KrjnANiKVhLWAkpXhNBe". End of explanation show_n_images = 25 DON'T MODIFY ANYTHING IN THIS CELL %matplotlib inline import os from glob import glob from matplotlib import pyplot mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L') pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray') Explanation: Explore the Data MNIST As you're aware, the MNIST dataset contains images of handwritten digits. You can view the first number of examples by changing show_n_images. End of explanation show_n_images = 25 DON'T MODIFY ANYTHING IN THIS CELL mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB') pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB')) Explanation: CelebA The CelebFaces Attributes Dataset (CelebA) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations. You can view the first number of examples by changing show_n_images. End of explanation DON'T MODIFY ANYTHING IN THIS CELL from distutils.version import LooseVersion import warnings import tensorflow as tf # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__) print('TensorFlow Version: {}'.format(tf.__version__)) # Check for a GPU if not tf.test.gpu_device_name(): warnings.warn('No GPU found. Please use a GPU to train your neural network.') else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) Explanation: Preprocess the Data Since the project's main focus is on building the GANs, we'll preprocess the data for you. The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images. The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28. The MNIST images are black and white images with a single [color channel](https://en.wikipedia.org/wiki/Channel_(digital_image%29) while the CelebA images have [3 color channels (RGB color channel)](https://en.wikipedia.org/wiki/Channel_(digital_image%29#RGB_Images). Build the Neural Network You'll build the components necessary to build a GANs by implementing the following functions below: - model_inputs - discriminator - generator - model_loss - model_opt - train Check the Version of TensorFlow and Access to GPU This will check to make sure you have the correct version of TensorFlow and access to a GPU End of explanation import problem_unittests as tests def model_inputs(image_width, image_height, image_channels, z_dim): Create the model inputs :param image_width: The input image width :param image_height: The input image height :param image_channels: The number of image channels :param z_dim: The dimension of Z :return: Tuple of (tensor of real input images, tensor of z data, learning rate) # TODO: Implement Function real_image = tf.placeholder(tf.float32, (None, image_width, image_height, image_channels), name='real_image') z_data = tf.placeholder(tf.float32, (None, z_dim), name="z_data") learning_rate = tf.placeholder(tf.float32, name="learning_rate") return real_image, z_data, learning_rate DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_model_inputs(model_inputs) Explanation: Input Implement the model_inputs function to create TF Placeholders for the Neural Network. It should create the following placeholders: - Real input images placeholder with rank 4 using image_width, image_height, and image_channels. - Z input placeholder with rank 2 using z_dim. - Learning rate placeholder with rank 0. Return the placeholders in the following the tuple (tensor of real input images, tensor of z data) End of explanation def discriminator(images, reuse=False, alpha=0.001): Create the discriminator network :param images: Tensor of input image(s) :param reuse: Boolean if the weights should be reused :return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator) # TODO: Implement Function with tf.variable_scope('discriminator', reuse=reuse): # layer 1 in 28*28*(1 or 3) conv_1 = tf.layers.conv2d(images, 16, 2, 2, padding='same') conv_1 = tf.maximum(conv_1, conv_1*alpha) # layer 2 in 14x14*16 conv_2 = tf.layers.conv2d(conv_1, 32, 2, 2, padding='same') conv_2 = tf.layers.batch_normalization(conv_2) conv_2 = tf.maximum(conv_2, conv_2*alpha) # layer 3 in 7x7*32 conv_3 = tf.layers.conv2d(conv_2, 64, 2, 2, padding='same') conv_3 = tf.layers.batch_normalization(conv_3) conv_3 = tf.maximum(conv_3, conv_3*alpha) # output in 4x4x64 flat = tf.reshape(conv_2, (-1, 32*4*4)) logits = tf.layers.dense(flat, 1) output = tf.sigmoid(logits) return output, logits DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_discriminator(discriminator, tf) Explanation: Discriminator Implement discriminator to create a discriminator neural network that discriminates on images. This function should be able to reuse the variables in the neural network. Use tf.variable_scope with a scope name of "discriminator" to allow the variables to be reused. The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator). End of explanation def generator(z, out_channel_dim, is_train=True, alpha=0.001): Create the generator network :param z: Input z :param out_channel_dim: The number of channels in the output image :param is_train: Boolean if generator is being used for training :return: The tensor output of the generator # TODO: Implement Function with tf.variable_scope('generator', reuse=not is_train): # layer 1 input is z, a flat vector layer_1 = tf.layers.dense(z, 2*2*512) layer_1 = tf.reshape(layer_1,(-1,2,2,512)) # layer 2 - 2x2x512 conv_1 = tf.layers.conv2d_transpose(layer_1, 256, 2, 2, padding='same') conv_1 = tf.maximum(conv_1, conv_1*alpha) # layer 3 - 4x4x256 conv_2 = tf.layers.conv2d_transpose(conv_1, 128, 4, 1, padding='valid') conv_2 = tf.layers.batch_normalization(conv_2, training=is_train) conv_2 = tf.maximum(conv_2, conv_2*alpha) # layer 4 - 7x7x128 conv_3 = tf.layers.conv2d_transpose(conv_2, 64, 2, 2, padding='same') conv_3 = tf.layers.batch_normalization(conv_3, training=is_train) conv_3 = tf.maximum(conv_3, conv_3*alpha) # layer 5 - 14x14x128 conv_4 = tf.layers.conv2d_transpose(conv_3, 32, 2, 2, padding='same') conv_4 = tf.maximum(conv_4, conv_4*alpha) # output - 28x28x64 logits = tf.layers.conv2d_transpose(conv_4, out_channel_dim, 2, 1, padding='same') output = tf.tanh(logits) return output DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_generator(generator, tf) Explanation: Generator Implement generator to generate an image using z. This function should be able to reuse the variables in the neural network. Use tf.variable_scope with a scope name of "generator" to allow the variables to be reused. The function should return the generated 28 x 28 x out_channel_dim images. End of explanation def model_loss(input_real, input_z, out_channel_dim, smooth=0.9): Get the loss for the discriminator and generator :param input_real: Images from the real dataset :param input_z: Z input :param out_channel_dim: The number of channels in the output image :return: A tuple of (discriminator loss, generator loss) # TODO: Implement Function g_model = generator(input_z, out_channel_dim) d_output_real, d_logits_real = discriminator(input_real) d_output_fake, d_logits_fake = discriminator(g_model, reuse=True) d_loss_real = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=tf.ones_like(d_logits_real) * (1 - smooth))) d_loss_fake = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.zeros_like(d_logits_real))) d_loss = d_loss_real + d_loss_fake g_loss = tf.reduce_mean( tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_fake, labels=tf.ones_like(d_logits_fake))) return d_loss, g_loss DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_model_loss(model_loss) Explanation: Loss Implement model_loss to build the GANs for training and calculate the loss. The function should return a tuple of (discriminator loss, generator loss). Use the following functions you implemented: - discriminator(images, reuse=False) - generator(z, out_channel_dim, is_train=True) End of explanation def model_opt(d_loss, g_loss, learning_rate, beta1): Get optimization operations :param d_loss: Discriminator loss Tensor :param g_loss: Generator loss Tensor :param learning_rate: Learning Rate Placeholder :param beta1: The exponential decay rate for the 1st moment in the optimizer :return: A tuple of (discriminator training operation, generator training operation) # TODO: Implement Function # Get the trainable_variables, split into G and D parts t_vars = tf.trainable_variables() g_vars = [var for var in t_vars if var.name.startswith("generator")] d_vars = [var for var in t_vars if var.name.startswith("discriminator")] # batch normalization needs to update the graph update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) g_updates = [opt for opt in update_ops if opt.name.startswith('generator')] with tf.control_dependencies(g_updates): d_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(d_loss, var_list=d_vars) g_train_opt = tf.train.AdamOptimizer(learning_rate).minimize(g_loss, var_list=g_vars) return d_train_opt, g_train_opt DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_model_opt(model_opt, tf) Explanation: Optimization Implement model_opt to create the optimization operations for the GANs. Use tf.trainable_variables to get all the trainable variables. Filter the variables with names that are in the discriminator and generator scope names. The function should return a tuple of (discriminator training operation, generator training operation). End of explanation DON'T MODIFY ANYTHING IN THIS CELL import numpy as np def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode): Show example output for the generator :param sess: TensorFlow session :param n_images: Number of Images to display :param input_z: Input Z Tensor :param out_channel_dim: The number of channels in the output image :param image_mode: The mode to use for images ("RGB" or "L") cmap = None if image_mode == 'RGB' else 'gray' z_dim = input_z.get_shape().as_list()[-1] example_z = np.random.uniform(-1, 1, size=[n_images, z_dim]) samples = sess.run( generator(input_z, out_channel_dim, False), feed_dict={input_z: example_z}) images_grid = helper.images_square_grid(samples, image_mode) pyplot.imshow(images_grid, cmap=cmap) pyplot.show() Explanation: Neural Network Training Show Output Use this function to show the current output of the generator during training. It will help you determine how well the GANs is training. End of explanation def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode): Train the GAN :param epoch_count: Number of epochs :param batch_size: Batch Size :param z_dim: Z dimension :param learning_rate: Learning Rate :param beta1: The exponential decay rate for the 1st moment in the optimizer :param get_batches: Function to get batches :param data_shape: Shape of the data :param data_image_mode: The image mode to use for images ("RGB" or "L") # TODO: Build Model # input shape _, image_width, image_height, image_channels = data_shape # model inputs input_real, input_z, learn_rate = model_inputs(image_width, image_height, image_channels, z_dim) # model losses d_loss, g_loss = model_loss(input_real, input_z, image_channels) # optimization d_opt, g_opt = model_opt(d_loss, g_loss, learning_rate, beta1) saver = tf.train.Saver() samples = [] losses = [] steps = 0 print_loss_every = 10 show_images_every = 80 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for epoch_i in range(epoch_count): for batch_images in get_batches(batch_size): # TODO: Train Model # Get images, reshape and rescale to pass to D # images are b/w -0.5 to 0.5, so rescaling to -1 to 1 batch_images = batch_images * 2 # Sample random noise for G batch_z = np.random.uniform(-1, 1, size=(batch_size,z_dim)) batch_images = batch_images * 2.0 # Run optimizers _ = sess.run(d_opt, feed_dict={input_real: batch_images, input_z: batch_z}) _ = sess.run(g_opt, feed_dict={input_z: batch_z}) steps += 1 # get the losses and print them out every so often if steps % print_loss_every == 0: train_loss_d = sess.run(d_loss, {input_z: batch_z, input_real: batch_images}) train_loss_g = g_loss.eval({input_z: batch_z}) print("Epoch {}/{}...".format(epoch_i+1, epoch_count), "Discriminator Loss: {:.4f}...".format(train_loss_d), "Generator Loss: {:.4f}".format(train_loss_g)) # Save losses to view after training losses.append((train_loss_d, train_loss_g)) # show generated images every so often if steps % show_images_every == 0: show_generator_output(sess, 20, input_z, image_channels, data_image_mode) Explanation: Train Implement train to build and train the GANs. Use the following functions you implemented: - model_inputs(image_width, image_height, image_channels, z_dim) - model_loss(input_real, input_z, out_channel_dim) - model_opt(d_loss, g_loss, learning_rate, beta1) Use the show_generator_output to show generator output while you train. Running show_generator_output for every batch will drastically increase training time and increase the size of the notebook. It's recommended to print the generator output every 100 batches. End of explanation batch_size = 64 z_dim = 128 learning_rate = 0.001 beta1 = 0.5 DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE epochs = 2 mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg'))) with tf.Graph().as_default(): train(epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches, mnist_dataset.shape, mnist_dataset.image_mode) Explanation: MNIST Test your GANs architecture on MNIST. After 2 epochs, the GANs should be able to generate images that look like handwritten digits. Make sure the loss of the generator is lower than the loss of the discriminator or close to 0. End of explanation batch_size = None z_dim = None learning_rate = None beta1 = None DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE epochs = 1 celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))) with tf.Graph().as_default(): train(epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches, celeba_dataset.shape, celeba_dataset.image_mode) Explanation: CelebA Run your GANs on CelebA. It will take around 20 minutes on the average GPU to run one epoch. You can run the whole epoch or stop when it starts to generate realistic faces. End of explanation
7,334
Given the following text description, write Python code to implement the functionality described below step by step Description: Brewing Logistic Regression then Going Deeper While Caffe is made for deep networks it can likewise represent "shallow" models like logistic regression for classification. We'll do simple logistic regression on synthetic data that we'll generate and save to HDF5 to feed vectors to Caffe. Once that model is done, we'll add layers to improve accuracy. That's what Caffe is about Step1: Synthesize a dataset of 10,000 4-vectors for binary classification with 2 informative features and 2 noise features. Step2: Learn and evaluate scikit-learn's logistic regression with stochastic gradient descent (SGD) training. Time and check the classifier's accuracy. Step3: Save the dataset to HDF5 for loading in Caffe. Step4: Let's define logistic regression in Caffe through Python net specification. This is a quick and natural way to define nets that sidesteps manually editing the protobuf model. Step5: Time to learn and evaluate our Caffeinated logistic regression in Python. Step6: Do the same through the command line interface for detailed output on the model and solving. Step7: If you look at output or the logreg_auto_train.prototxt, you'll see that the model is simple logistic regression. We can make it a little more advanced by introducing a non-linearity between weights that take the input and weights that give the output -- now we have a two-layer network. That network is given in nonlinear_auto_train.prototxt, and that's the only change made in nonlinear_solver.prototxt which we will now use. The final accuracy of the new network should be higher than logistic regression! Step8: Do the same through the command line interface for detailed output on the model and solving.
Python Code: import numpy as np import matplotlib.pyplot as plt %matplotlib inline import os os.chdir('..') import sys sys.path.insert(0, './python') import caffe import os import h5py import shutil import tempfile import sklearn import sklearn.datasets import sklearn.linear_model import pandas as pd Explanation: Brewing Logistic Regression then Going Deeper While Caffe is made for deep networks it can likewise represent "shallow" models like logistic regression for classification. We'll do simple logistic regression on synthetic data that we'll generate and save to HDF5 to feed vectors to Caffe. Once that model is done, we'll add layers to improve accuracy. That's what Caffe is about: define a model, experiment, and then deploy. End of explanation X, y = sklearn.datasets.make_classification( n_samples=10000, n_features=4, n_redundant=0, n_informative=2, n_clusters_per_class=2, hypercube=False, random_state=0 ) # Split into train and test X, Xt, y, yt = sklearn.cross_validation.train_test_split(X, y) # Visualize sample of the data ind = np.random.permutation(X.shape[0])[:1000] df = pd.DataFrame(X[ind]) _ = pd.scatter_matrix(df, figsize=(9, 9), diagonal='kde', marker='o', s=40, alpha=.4, c=y[ind]) Explanation: Synthesize a dataset of 10,000 4-vectors for binary classification with 2 informative features and 2 noise features. End of explanation %%timeit # Train and test the scikit-learn SGD logistic regression. clf = sklearn.linear_model.SGDClassifier( loss='log', n_iter=1000, penalty='l2', alpha=1e-3, class_weight='auto') clf.fit(X, y) yt_pred = clf.predict(Xt) print('Accuracy: {:.3f}'.format(sklearn.metrics.accuracy_score(yt, yt_pred))) Explanation: Learn and evaluate scikit-learn's logistic regression with stochastic gradient descent (SGD) training. Time and check the classifier's accuracy. End of explanation # Write out the data to HDF5 files in a temp directory. # This file is assumed to be caffe_root/examples/hdf5_classification.ipynb dirname = os.path.abspath('./examples/hdf5_classification/data') if not os.path.exists(dirname): os.makedirs(dirname) train_filename = os.path.join(dirname, 'train.h5') test_filename = os.path.join(dirname, 'test.h5') # HDF5DataLayer source should be a file containing a list of HDF5 filenames. # To show this off, we'll list the same data file twice. with h5py.File(train_filename, 'w') as f: f['data'] = X f['label'] = y.astype(np.float32) with open(os.path.join(dirname, 'train.txt'), 'w') as f: f.write(train_filename + '\n') f.write(train_filename + '\n') # HDF5 is pretty efficient, but can be further compressed. comp_kwargs = {'compression': 'gzip', 'compression_opts': 1} with h5py.File(test_filename, 'w') as f: f.create_dataset('data', data=Xt, **comp_kwargs) f.create_dataset('label', data=yt.astype(np.float32), **comp_kwargs) with open(os.path.join(dirname, 'test.txt'), 'w') as f: f.write(test_filename + '\n') Explanation: Save the dataset to HDF5 for loading in Caffe. End of explanation from caffe import layers as L from caffe import params as P def logreg(hdf5, batch_size): # logistic regression: data, matrix multiplication, and 2-class softmax loss n = caffe.NetSpec() n.data, n.label = L.HDF5Data(batch_size=batch_size, source=hdf5, ntop=2) n.ip1 = L.InnerProduct(n.data, num_output=2, weight_filler=dict(type='xavier')) n.accuracy = L.Accuracy(n.ip1, n.label) n.loss = L.SoftmaxWithLoss(n.ip1, n.label) return n.to_proto() with open('examples/hdf5_classification/logreg_auto_train.prototxt', 'w') as f: f.write(str(logreg('examples/hdf5_classification/data/train.txt', 10))) with open('examples/hdf5_classification/logreg_auto_test.prototxt', 'w') as f: f.write(str(logreg('examples/hdf5_classification/data/test.txt', 10))) Explanation: Let's define logistic regression in Caffe through Python net specification. This is a quick and natural way to define nets that sidesteps manually editing the protobuf model. End of explanation %%timeit caffe.set_mode_cpu() solver = caffe.get_solver('examples/hdf5_classification/solver.prototxt') solver.solve() accuracy = 0 batch_size = solver.test_nets[0].blobs['data'].num test_iters = int(len(Xt) / batch_size) for i in range(test_iters): solver.test_nets[0].forward() accuracy += solver.test_nets[0].blobs['accuracy'].data accuracy /= test_iters print("Accuracy: {:.3f}".format(accuracy)) Explanation: Time to learn and evaluate our Caffeinated logistic regression in Python. End of explanation !./build/tools/caffe train -solver examples/hdf5_classification/solver.prototxt Explanation: Do the same through the command line interface for detailed output on the model and solving. End of explanation from caffe import layers as L from caffe import params as P def nonlinear_net(hdf5, batch_size): # one small nonlinearity, one leap for model kind n = caffe.NetSpec() n.data, n.label = L.HDF5Data(batch_size=batch_size, source=hdf5, ntop=2) # define a hidden layer of dimension 40 n.ip1 = L.InnerProduct(n.data, num_output=40, weight_filler=dict(type='xavier')) # transform the output through the ReLU (rectified linear) non-linearity n.relu1 = L.ReLU(n.ip1, in_place=True) # score the (now non-linear) features n.ip2 = L.InnerProduct(n.ip1, num_output=2, weight_filler=dict(type='xavier')) # same accuracy and loss as before n.accuracy = L.Accuracy(n.ip2, n.label) n.loss = L.SoftmaxWithLoss(n.ip2, n.label) return n.to_proto() with open('examples/hdf5_classification/nonlinear_auto_train.prototxt', 'w') as f: f.write(str(nonlinear_net('examples/hdf5_classification/data/train.txt', 10))) with open('examples/hdf5_classification/nonlinear_auto_test.prototxt', 'w') as f: f.write(str(nonlinear_net('examples/hdf5_classification/data/test.txt', 10))) %%timeit caffe.set_mode_cpu() solver = caffe.get_solver('examples/hdf5_classification/nonlinear_solver.prototxt') solver.solve() accuracy = 0 batch_size = solver.test_nets[0].blobs['data'].num test_iters = int(len(Xt) / batch_size) for i in range(test_iters): solver.test_nets[0].forward() accuracy += solver.test_nets[0].blobs['accuracy'].data accuracy /= test_iters print("Accuracy: {:.3f}".format(accuracy)) Explanation: If you look at output or the logreg_auto_train.prototxt, you'll see that the model is simple logistic regression. We can make it a little more advanced by introducing a non-linearity between weights that take the input and weights that give the output -- now we have a two-layer network. That network is given in nonlinear_auto_train.prototxt, and that's the only change made in nonlinear_solver.prototxt which we will now use. The final accuracy of the new network should be higher than logistic regression! End of explanation !./build/tools/caffe train -solver examples/hdf5_classification/nonlinear_solver.prototxt # Clean up (comment this out if you want to examine the hdf5_classification/data directory). shutil.rmtree(dirname) Explanation: Do the same through the command line interface for detailed output on the model and solving. End of explanation
7,335
Given the following text description, write Python code to implement the functionality described. Description: Minimum lines to cover all points Utility method to get gcd of a and b ; method returns reduced form of dy / dx as a pair ; get sign of result ; method returns minimum number of lines to cover all points where all lines goes through ( xO , yO ) ; set to store slope as a pair ; loop over all points once ; get x and y co - ordinate of current point ; if this slope is not there in set , increase ans by 1 and insert in set ; Driver code
Python Code: def gcd(a , b ) : if(b == 0 ) : return a  return gcd(b , a % b )  def getReducedForm(dy , dx ) : g = gcd(abs(dy ) , abs(dx ) ) sign =(dy < 0 ) ^(dx < 0 ) if(sign ) : return(- abs(dy ) // g , abs(dx ) // g )  else : return(abs(dy ) // g , abs(dx ) // g )   def minLinesToCoverPoints(points , N , xO , yO ) : st = dict() minLines = 0 for i in range(N ) : curX = points[i ][0 ] curY = points[i ][1 ] temp = getReducedForm(curY - yO , curX - xO ) if(temp not in st ) : st[temp ] = 1 minLines += 1   return minLines  xO = 1 yO = 0 points =[[ - 1 , 3 ] ,[4 , 3 ] ,[2 , 1 ] ,[- 1 , - 2 ] ,[3 , - 3 ] ] N = len(points ) print(minLinesToCoverPoints(points , N , xO , yO ) )
7,336
Given the following text description, write Python code to implement the functionality described below step by step Description: 확률론적 언어 모형 확률론적 언어 모형(Probabilistic Language Model)은 $m$개의 단어 $w_1, w_2, \ldots, w_m$ 열(word sequence)이 주어졌을 때 문장으로써 성립될 확률 $P(w_1, w_2, \ldots, w_m)$ 을 출력함으로써 이 단어 열이 실제로 현실에서 사용될 수 있는 문장(sentence)인지를 판별하는 모형이다. 이 확률은 각 단어의 확률과 단어들의 조건부 확률을 이용하여 다음과 같이 계산할 수 있다. $$ \begin{eqnarray} P(w_1, w_2, \ldots, w_m) &=& P(w_1, w_2, \ldots, w_{m-1}) \cdot P(w_m\;|\; w_1, w_2, \ldots, w_{m-1}) \ &=& P(w_1, w_2, \ldots, w_{m-2}) \cdot P(w_{m-1}\;|\; w_1, w_2, \ldots, w_{m-2}) \cdot P(w_m\;|\; w_1, w_2, \ldots, w_{m-1}) \ &=& P(w_1) \cdot P(w_2 \;|\; w_1) \cdot P(w_3 \;|\; w_1, w_2) P(w_4 \;|\; w_1, w_2, w_3) \cdots P(w_m\;|\; w_1, w_2, \ldots, w_{m-1}) \end{eqnarray} $$ 여기에서 $P(w_m\;|\; w_1, w_2, \ldots, w_{m-1})$ 은 지금까지 $w_1, w_2, \ldots, w_{m-1}$라는 단어 열이 나왔을 때, 그 다음 단어로 $w_m$이 나올 조건부 확률을 말한다. 여기에서 지금까지 나온 단어를 문맥(context) 정보라고 한다. 이 때 조건부 확률을 어떻게 모형화하는냐에 따라 * 유니그램 모형 (Unigram Model) * 바이그램 모형 (Bigram Model) * N-그램 모형 (N-gram Model) 등으로 나뉘어 진다. 유니그램 모형 (Unigram Model) 만약 모든 단어의 활용이 완전히 서로 독립이라면 단어 열의 확률은 다음과 같이 각 단어의 확률의 곱이 된다. 이러한 모형을 유니그램 모형 (Unigram Model)이라고 한다. $$ P(w_1, w_2, \ldots, w_m) = \prod_{i=1}^m P(w_i) $$ 바이그램 모형 (Bigram Model) 만약 단어의 활용이 바로 전 단어에만 의존한다면 단어 열의 확률은 다음과 같다. 이러한 모형을 Bigram 모형 또는 마코프 모형(Markov Model)이라고 한다. $$ P(w_1, w_2, \ldots, w_m) = P(w_1) \prod_{i=2}^{m} P(w_{i}\;|\; w_{i-1}) $$ N-그램 모형 (N-gram Model) 만약 단어의 활용이 바로 전 $n$개의 단어에만 의존한다면 단어 열의 확률은 다음과 같다. 이러한 모형을 N-gram 모형이라고 한다. $$ P(w_1, w_2, \ldots, w_m) = P(w_1) \prod_{i=n}^{m} P(w_{i}\;|\; w_{i-1}, \ldots, w_{i-n}) $$ 확률 추정 방법 실제 텍스트 코퍼스(corpus)에서 확률을 추정하는 방법은 다음과 같다. 여기에서는 바이그램의 경우를 살펴본다. 일단 모든 문장에 문장의 시작과 끝을 나타내는 특별 토큰을 추가한다. 예를 들어 문장의 시작은 SS, 문장의 끝은 SE 이라는 토큰을 사용할 수 있다. 바이그램 모형에서는 전체 문장의 확률은 다음과 같이 조건부 확률의 곱으로 나타난다. $$ P(\text{SS I am a boy SE}) = P(\text{I}\;|\; \text{SS}) \cdot P(\text{am}\;|\; \text{I}) \cdot P(\text{a}\;|\; \text{am}) \cdot P(\text{boy}\;|\; \text{a}) \cdot P(\text{SE}\;|\; \text{boy}) $$ 조건부 확률은 다음과 같이 추정한다. $$ P(w_{i}\;|\; w_{i-1}) = \dfrac{C(w_{i}, w_{i-1})}{C(w_{i-1})} $$ 위 식에서 $C(w_{i}, w_{i-1})$은 전체 코퍼스에서 $(w_{i}, w_{i-1})$라는 바이그램이 나타나는 횟수이고 $C(w_{i-1})$은 전체 코퍼스에서 $(w_{i-1})$라는 유니그램(단어)이 나타나는 횟수이다. 예제 다음은 nltk 패키지의 샘플 코퍼스인 movie_reviews의 텍스트를 기반으로 N-그램 모형을 추정하고 모형 확률로부터 랜덤하게 문장을 생성하는 예제이다. 다음 문헌을 참고하여 일부 수정하였다. Roger Levy, Linguistics 165 Step2: 이제 이 입력으로부터 확률값을 추정한다. Step3: 트레이닝이 끝나면 조건부 확률의 값을 보거나 샘플 문장을 입력해서 문장의 로그 확률을 구할 수 있다. "i" 라는 단어가 나온 뒤에 "am"이라는 단어가 나올 확률을 계산하면 Step4: 이 모형을 기반으로 임의의 랜덤한 샘플 즉, 문장을 생성해 보면 다음과 같다. 여기에서는 하나의 단어부터 시작하여 문장의 확률이 난수값보다 크게 만드는 첫번째 단어를 찾아서 이어붙이는 방식을 취했다. 만약 최저 확률을 높이면 올바른 단어를 찾는 시간이 더 오래 걸리게 된다. Step5: 이번에는 한글 자료를 이용해보자 코퍼스로는 아래의 웹사이트에 공개된 Naver sentiment movie corpus 자료를 사용한다. * https
Python Code: from nltk.corpus import movie_reviews # 문서를 문장으로 분리 sentences = list(movie_reviews.sents()) import random # 섞는다. random.seed(1) random.shuffle(sentences) sentences[0] Explanation: 확률론적 언어 모형 확률론적 언어 모형(Probabilistic Language Model)은 $m$개의 단어 $w_1, w_2, \ldots, w_m$ 열(word sequence)이 주어졌을 때 문장으로써 성립될 확률 $P(w_1, w_2, \ldots, w_m)$ 을 출력함으로써 이 단어 열이 실제로 현실에서 사용될 수 있는 문장(sentence)인지를 판별하는 모형이다. 이 확률은 각 단어의 확률과 단어들의 조건부 확률을 이용하여 다음과 같이 계산할 수 있다. $$ \begin{eqnarray} P(w_1, w_2, \ldots, w_m) &=& P(w_1, w_2, \ldots, w_{m-1}) \cdot P(w_m\;|\; w_1, w_2, \ldots, w_{m-1}) \ &=& P(w_1, w_2, \ldots, w_{m-2}) \cdot P(w_{m-1}\;|\; w_1, w_2, \ldots, w_{m-2}) \cdot P(w_m\;|\; w_1, w_2, \ldots, w_{m-1}) \ &=& P(w_1) \cdot P(w_2 \;|\; w_1) \cdot P(w_3 \;|\; w_1, w_2) P(w_4 \;|\; w_1, w_2, w_3) \cdots P(w_m\;|\; w_1, w_2, \ldots, w_{m-1}) \end{eqnarray} $$ 여기에서 $P(w_m\;|\; w_1, w_2, \ldots, w_{m-1})$ 은 지금까지 $w_1, w_2, \ldots, w_{m-1}$라는 단어 열이 나왔을 때, 그 다음 단어로 $w_m$이 나올 조건부 확률을 말한다. 여기에서 지금까지 나온 단어를 문맥(context) 정보라고 한다. 이 때 조건부 확률을 어떻게 모형화하는냐에 따라 * 유니그램 모형 (Unigram Model) * 바이그램 모형 (Bigram Model) * N-그램 모형 (N-gram Model) 등으로 나뉘어 진다. 유니그램 모형 (Unigram Model) 만약 모든 단어의 활용이 완전히 서로 독립이라면 단어 열의 확률은 다음과 같이 각 단어의 확률의 곱이 된다. 이러한 모형을 유니그램 모형 (Unigram Model)이라고 한다. $$ P(w_1, w_2, \ldots, w_m) = \prod_{i=1}^m P(w_i) $$ 바이그램 모형 (Bigram Model) 만약 단어의 활용이 바로 전 단어에만 의존한다면 단어 열의 확률은 다음과 같다. 이러한 모형을 Bigram 모형 또는 마코프 모형(Markov Model)이라고 한다. $$ P(w_1, w_2, \ldots, w_m) = P(w_1) \prod_{i=2}^{m} P(w_{i}\;|\; w_{i-1}) $$ N-그램 모형 (N-gram Model) 만약 단어의 활용이 바로 전 $n$개의 단어에만 의존한다면 단어 열의 확률은 다음과 같다. 이러한 모형을 N-gram 모형이라고 한다. $$ P(w_1, w_2, \ldots, w_m) = P(w_1) \prod_{i=n}^{m} P(w_{i}\;|\; w_{i-1}, \ldots, w_{i-n}) $$ 확률 추정 방법 실제 텍스트 코퍼스(corpus)에서 확률을 추정하는 방법은 다음과 같다. 여기에서는 바이그램의 경우를 살펴본다. 일단 모든 문장에 문장의 시작과 끝을 나타내는 특별 토큰을 추가한다. 예를 들어 문장의 시작은 SS, 문장의 끝은 SE 이라는 토큰을 사용할 수 있다. 바이그램 모형에서는 전체 문장의 확률은 다음과 같이 조건부 확률의 곱으로 나타난다. $$ P(\text{SS I am a boy SE}) = P(\text{I}\;|\; \text{SS}) \cdot P(\text{am}\;|\; \text{I}) \cdot P(\text{a}\;|\; \text{am}) \cdot P(\text{boy}\;|\; \text{a}) \cdot P(\text{SE}\;|\; \text{boy}) $$ 조건부 확률은 다음과 같이 추정한다. $$ P(w_{i}\;|\; w_{i-1}) = \dfrac{C(w_{i}, w_{i-1})}{C(w_{i-1})} $$ 위 식에서 $C(w_{i}, w_{i-1})$은 전체 코퍼스에서 $(w_{i}, w_{i-1})$라는 바이그램이 나타나는 횟수이고 $C(w_{i-1})$은 전체 코퍼스에서 $(w_{i-1})$라는 유니그램(단어)이 나타나는 횟수이다. 예제 다음은 nltk 패키지의 샘플 코퍼스인 movie_reviews의 텍스트를 기반으로 N-그램 모형을 추정하고 모형 확률로부터 랜덤하게 문장을 생성하는 예제이다. 다음 문헌을 참고하여 일부 수정하였다. Roger Levy, Linguistics 165: Computational Linguistics (Winter 2015), University of California, San Diego http://idiom.ucsd.edu/~rlevy/teaching/2015winter/lign165/code/NgramModel.py 우선 다음과 같이 문장(단어 리스트)의 리스트를 만든다. End of explanation import collections, math from math import log from collections import Counter from konlpy.utils import pprint def stringify_context(context): return(" ".join(context)) boundaryToken = "</s>" def ngrams(n, sentences, boundaryToken=boundaryToken, verbose=False): c = {} q = [] for i in range(n-1): q.append(boundaryToken) for sentence in sentences: for w in sentence + [boundaryToken]: context_gram = stringify_context(q) if verbose: print(q) print(context_gram) print(w) if not context_gram in c: c[context_gram] = Counter() c[context_gram][w] += 1 q.pop(0) q.append(w) return(c) ngrams(2, sentences[:1000])["we"] class BigramModel: def __init__(self, training_sentences, smoothing='none'): train = ngrams(2, training_sentences) self.probs = {} if smoothing == 'none': for context_gram in train.keys(): N = sum(train[context_gram].values()) self.probs[context_gram] = Counter({k:v/N for k,v in train[context_gram].items()}) def prob(self, word, context): takes a word string and a context which is a list of word strings, and returns the probability of the word c = stringify_context(context) return(self.probs[c][word]) def scoreSentence(self, sentence, verbose=False): context = [boundaryToken] result = 0 for w in sentence + [boundaryToken]: lp = log(self.prob(w, context)) result = result + lp if verbose: pprint([context, w, lp]) context = [w] return result def generateSentence(self, verbose=False, goryDetails=False): context = [boundaryToken] result = [] w = None while not w == boundaryToken: r = random.random() # returns a random float between 0 and 1 x = 0 c = self.probs[stringify_context(context)] # this will be a Counter w = c.keys()[np.argmax(np.random.multinomial(1, c.values(), (1,))[0])] result.append(w) context = [w] if verbose: print(w) result.pop() # drop the boundary token return result m = BigramModel(sentences) Explanation: 이제 이 입력으로부터 확률값을 추정한다. End of explanation m.prob("am", ["i"]) m.prob("</s>", ["."]) # .(마침표) 뒤에 문장이 끝날 확률 m.probs["."] m.prob("the", ["in"]) # in 뒤에 the 가 올 확률 m.prob("in", ["the"]) # the 뒤에 in 이 올 확률 test_sentence = ['in', 'the', '1970s', '.'] m.scoreSentence(test_sentence, verbose=True) m.scoreSentence(["i", "am", "a", "boy", "."], verbose=True) Explanation: 트레이닝이 끝나면 조건부 확률의 값을 보거나 샘플 문장을 입력해서 문장의 로그 확률을 구할 수 있다. "i" 라는 단어가 나온 뒤에 "am"이라는 단어가 나올 확률을 계산하면 End of explanation random.seed(1) print(" ".join(m.generateSentence())) Explanation: 이 모형을 기반으로 임의의 랜덤한 샘플 즉, 문장을 생성해 보면 다음과 같다. 여기에서는 하나의 단어부터 시작하여 문장의 확률이 난수값보다 크게 만드는 첫번째 단어를 찾아서 이어붙이는 방식을 취했다. 만약 최저 확률을 높이면 올바른 단어를 찾는 시간이 더 오래 걸리게 된다. End of explanation import codecs def read_data(filename): with codecs.open(filename, encoding='utf-8', mode='r') as f: data = [line.split('\t') for line in f.read().splitlines()] data = data[1:] # header 제외 return data train_data = read_data('/home/dockeruser/data/nsmc/ratings_train.txt') from konlpy.tag import Twitter tagger = Twitter() def tokenize(doc): return ['/'.join(t) for t in tagger.pos(doc, norm=True, stem=True)] train_docs = [row[1] for row in train_data] sentences = [tokenize(d) for d in train_docs] m = BigramModel(sentences) m.prob(tokenize(u"영화")[0], tokenize(u"이")) m.scoreSentence(tokenize(u"이 영화 정말 좋네"), verbose=True) m.scoreSentence(tokenize(u"좋네 영화 이 정말"), verbose=True) random.seed(24) print("".join([w.split("/")[0] if w.split("/")[1] == "Josa" else " " + w.split("/")[0] for w in m.generateSentence()])) Explanation: 이번에는 한글 자료를 이용해보자 코퍼스로는 아래의 웹사이트에 공개된 Naver sentiment movie corpus 자료를 사용한다. * https://github.com/e9t/nsmc End of explanation
7,337
Given the following text description, write Python code to implement the functionality described below step by step Description: Contextual Bandits (incomplete) Step1: Query by Committee Step2: Stochastic Gradient Descent Step3: Random selection of data points at each iteration. Step4: SVM with Random Sampling Step5: Contextual Bandits We implement a contextual bandit algorithm for active learning, suggested by <a href="https Step6: Each cluster has a context vector containing 4 pieces of information Step7: We'll use Thompson Sampling with linear payoff and with Gaussian prior and likelihood. The algorithm is described in <a href="http Step8: Initially, we choose 100 random points to sample.
Python Code: import numpy as np import pandas as pd import pickle import seaborn as sns from pandas import DataFrame, Index from sklearn import metrics from sklearn.linear_model import SGDClassifier from sklearn.svm import SVC from sklearn.kernel_approximation import RBFSampler, Nystroem from sklearn.linear_model import PassiveAggressiveClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.cluster import MiniBatchKMeans from sklearn.utils import shuffle from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.cross_validation import KFold from scipy.spatial.distance import cosine from IPython.core.display import HTML from mclearn import * %matplotlib inline sns.set_palette("husl", 7) HTML(open("styles/stylesheet.css", "r").read()) # read in the data sdss = pd.io.parsers.read_csv("data/sdss_dr7_photometry.csv.gz", compression="gzip", index_col=["ra", "dec"]) # save the names of the 11 feature vectors and the target column feature_names = ["psfMag_u", "psfMag_g", "psfMag_r", "psfMag_i", "psfMag_z", "petroMag_u", "petroMag_g", "petroMag_r", "petroMag_i", "petroMag_z", "petroRad_r"] target_name = "class" X_train, X_test, y_train, y_test = train_test_split(np.array(sdss[feature_names]), np.array(sdss['class']), train_size=100000, test_size=30000) # shuffle the data X_train, y_train = shuffle(X_train, y_train) X_test, y_test = shuffle(X_test, y_test) Explanation: Contextual Bandits (incomplete) End of explanation accuracies = [] predictions = [[] for i in range(10)] forests = [None] * 11 # initially, pick 100 random points to query X_train_cur, y_train_cur = X_train[:100], y_train[:100] X_train_pool, y_train_pool = X_train[100:], y_train[100:] # find the accuracy rate, given the current training example forests[-1] = RandomForestClassifier(n_jobs=-1, class_weight='auto', random_state=5) forests[-1].fit(X_train_cur, y_train_cur) y_pred_test = forests[-1].predict(X_test) confusion_test = metrics.confusion_matrix(y_test, y_pred_test) accuracies.append(balanced_accuracy_expected(confusion_test)) # query by committee to pick the next point to sample kfold = KFold(len(y_train_cur), n_folds=10, shuffle=True) for i, (train_index, test_index) in enumerate(kfold): forests[i] = RandomForestClassifier(n_jobs=-1, class_weight='auto', random_state=5) forests[i].fit(X_train_cur[train_index], y_train_cur[train_index]) predictions[i] = forests[i].predict(X_train_pool) Explanation: Query by Committee End of explanation # normalise features to have mean 0 and variance 1 scaler = StandardScaler() scaler.fit(X_train) # fit only on training data X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) # approximates feature map of an RBF kernel by Monte Carlo approximation of its Fourier transform. rbf_feature = RBFSampler(n_components=200, gamma=0.3, random_state=1) X_train_rbf = rbf_feature.fit_transform(X_train) X_test_rbf = rbf_feature.transform(X_test) Explanation: Stochastic Gradient Descent End of explanation benchmark_sgd = SGDClassifier(loss="hinge", alpha=0.000001, penalty="l1", n_iter=10, n_jobs=-1, class_weight='auto', fit_intercept=True, random_state=1) benchmark_sgd.fit(X_train_rbf[:100], y_train[:100]) benchmark_y_pred = benchmark_sgd.predict(X_test_rbf) benchmark_confusion = metrics.confusion_matrix(y_test, benchmark_y_pred) benchmark_learning_curve = [] sample_sizes = np.concatenate((np.arange(100, 1000, 100), np.arange(1000, 10000, 1000), np.arange(10000, 100000, 10000), np.arange(100000, 1000000, 100000), np.arange(1000000, len(X_train), 500000), [len(X_train)])) benchmark_learning_curve.append(balanced_accuracy_expected(benchmark_confusion)) classes = np.unique(y_train) for i, j in zip(sample_sizes[:-1], sample_sizes[1:]): for _ in range(10): X_train_partial, y_train_partial = shuffle(X_train_rbf[i:j], y_train[i:j]) benchmark_sgd.partial_fit(X_train_partial, y_train_partial, classes=classes) benchmark_y_pred = benchmark_sgd.predict(X_test_rbf) benchmark_confusion = metrics.confusion_matrix(y_test, benchmark_y_pred) benchmark_learning_curve.append(balanced_accuracy_expected(benchmark_confusion)) # save output for later re-use with open('results/sdss_active_learning/sgd_benchmark.pickle', 'wb') as f: pickle.dump((benchmark_sgd, sample_sizes, benchmark_learning_curve), f, pickle.HIGHEST_PROTOCOL) plot_learning_curve(sample_sizes, benchmark_learning_curve, "Benchmark Learning Curve (Random Selection)") Explanation: Random selection of data points at each iteration. End of explanation svm_random = SVC(kernel='rbf', random_state=7, cache_size=2000, class_weight='auto') svm_random.fit(X_train[:100], y_train[:100]) svm_y_pred = svm_random.predict(X_test) svm_confusion = metrics.confusion_matrix(y_test, svm_y_pred) svm_learning_curve = [] sample_sizes = np.concatenate((np.arange(200, 1000, 100), np.arange(1000, 20000, 1000))) svm_learning_curve.append(balanced_accuracy_expected(svm_confusion)) previous_h = svm_random.predict(X_train) rewards = [] for i in sample_sizes: svm_random.fit(X_train[:i], y_train[:i]) svm_y_pred = svm_random.predict(X_test) svm_confusion = metrics.confusion_matrix(y_test, svm_y_pred) svm_learning_curve.append(balanced_accuracy_expected(svm_confusion)) current_h = svm_random.predict(X_train) reward = 0 for i, j in zip(current_h, previous_h): reward += 1 if i != j else 0 reward = reward / len(current_h) previous_h = current_h rewards.append(reward) # save output for later re-use with open('results/sdss_active_learning/sgd_svm_random.pickle', 'wb') as f: pickle.dump((sample_sizes, svm_learning_curve, rewards), f, pickle.HIGHEST_PROTOCOL) log_rewards = np.log(rewards) beta, intercept = np.polyfit(sample_sizes, log_rewards, 1) alpha = np.exp(intercept) plt.plot(sample_sizes, rewards) plt.plot(sample_sizes, alpha * np.exp(beta * sample_sizes)) plot_learning_curve(sample_sizes, svm_learning_curve, "SVM Learning Curve (Random Selection)") Explanation: SVM with Random Sampling End of explanation n_clusters = 100 kmeans = MiniBatchKMeans(n_clusters=n_clusters, init_size=100*n_clusters, random_state=2) X_train_transformed = kmeans.fit_transform(X_train) Explanation: Contextual Bandits We implement a contextual bandit algorithm for active learning, suggested by <a href="https://hal.archives-ouvertes.fr/hal-01069802" target="_blank">Bouneffouf et al (2014)</a>. End of explanation unlabelled_points = set(range(0, len(X_train))) empty_clusters = set() cluster_sizes = [len(np.flatnonzero(kmeans.labels_ == i)) for i in range(n_clusters)] cluster_points = [list(np.flatnonzero(kmeans.labels_ == i)) for i in range(n_clusters)] no_labelled = [0 for i in range(n_clusters)] prop_labelled = [0 for i in range(n_clusters)] d_means = [] d_var = [] for i in range(n_clusters): distance, distance_squared, count = 0, 0, 0 for j, p1 in enumerate(cluster_points[i]): for p2 in cluster_points[i][j+1:]: d = np.fabs(X_train_transformed[p1][i] - X_train_transformed[p2][i]) distance += d distance_squared += d**2 count += 1 if cluster_sizes[i] > 1: d_means.append(distance / count) d_var.append((distance_squared / count) - (distance / count)**2) else: d_means.append(0) d_var.append(0) context = np.array([list(x)for x in zip(d_means, d_var, cluster_sizes, prop_labelled)]) Explanation: Each cluster has a context vector containing 4 pieces of information: The mean distance between individual points in the cluster. The variance of the distance between individual points in the cluster. The number of points in the cluster. The proportion of points that have been labelled in the cluster. End of explanation context_size = 4 B = np.eye(context_size) mu = np.array([0] * context_size) f = np.array([0] * context_size) v_squared = 0.25 Explanation: We'll use Thompson Sampling with linear payoff and with Gaussian prior and likelihood. The algorithm is described in <a href="http://arxiv.org/abs/1209.3352" target="_blank">Argawal et al (2013)</a>. End of explanation active_sgd = SVC(kernel='rbf', random_state=7, cache_size=2000, class_weight='auto') #active_sgd = SGDClassifier(loss="hinge", alpha=0.000001, penalty="l1", n_iter=10, n_jobs=-1, # class_weight='auto', fit_intercept=True, random_state=1) X_train_cur, y_train_cur = X_train[:100], y_train[:100] active_sgd.fit(X_train_cur, y_train_cur) # update context for i in np.arange(0, 100): this_cluster = kmeans.labels_[i] cluster_points[this_cluster].remove(i) unlabelled_points.remove(i) if not cluster_points[this_cluster]: empty_clusters.add(this_cluster) no_labelled[this_cluster] += 1 context[this_cluster][3] = no_labelled[this_cluster] / cluster_sizes[this_cluster] # initial prediction active_y_pred = active_sgd.predict(X_test) active_confusion = metrics.confusion_matrix(y_test, active_y_pred) active_learning_curve = [] active_learning_curve.append(balanced_accuracy_expected(active_confusion)) classes = np.unique(y_train) # compute the current hypothesis previous_h = active_sgd.predict(X_train) active_steps = [100] no_choices = 1 rewards = [] for i in range(2000 // no_choices): mu_sample = np.random.multivariate_normal(mu, v_squared * np.linalg.inv(B)) reward_sample = [np.dot(c, mu_sample) for c in context] chosen_arm = np.argmax(reward_sample) while chosen_arm in empty_clusters: reward_sample[chosen_arm] = float('-inf') chosen_arm = np.argmax(reward_sample) # select a random point in the cluster query = np.random.choice(cluster_points[chosen_arm], min(len(cluster_points[chosen_arm]), no_choices), replace=False) # update context for q in query: cluster_points[chosen_arm].remove(q) unlabelled_points.remove(q) if not cluster_points[chosen_arm]: empty_clusters.add(chosen_arm) no_labelled[chosen_arm] += len(query) context[chosen_arm][3] = no_labelled[chosen_arm] / cluster_sizes[chosen_arm] active_steps.append(active_steps[-1] + len(query)) # run stochastic gradient descent #active_sgd.partial_fit(X_train_rbf[query], y_train[query], classes=classes) X_train_cur = np.vstack((X_train_cur, X_train[query])) y_train_cur = np.concatenate((y_train_cur, y_train[query])) active_sgd = SVC(kernel='rbf', random_state=7, cache_size=2000, class_weight='auto') active_sgd.fit(X_train_cur, y_train_cur) active_y_pred = active_sgd.predict(X_test) active_confusion = metrics.confusion_matrix(y_test, active_y_pred) active_learning_curve.append(balanced_accuracy_expected(active_confusion)) # compute the reward from choosing such arm current_h = active_sgd.predict(X_train) reward = 0 for i, j in zip(current_h, previous_h): reward += 1 if i != j else 0 reward = reward / len(current_h) reward = reward / (alpha * np.exp(beta * len(y_train_cur))) previous_h = current_h rewards.append(reward) # compute posterior distribution B = B + np.outer(context[chosen_arm], context[chosen_arm]) f = f + reward * context[chosen_arm] mu = np.dot(np.linalg.inv(B), f) plot_learning_curve(active_steps, active_learning_curve, "SVM Learning Curve (Active Learning)") Explanation: Initially, we choose 100 random points to sample. End of explanation
7,338
Given the following text description, write Python code to implement the functionality described below step by step Description: Repeatable splitting Learrning Objectives * explore the impact of different ways of creating train/valid/test splits Overview Repeatability is important in machine learning. If you do the same thing now and 5 minutes from now and get different answers, then it makes experimentation difficult. In other words, you will find it difficult to gauge whether a change you made has resulted in an improvement or not. Step2: <h3> Create a simple machine learning model </h3> The dataset that we will use is <a href="https Step4: <h3> What is wrong with calculating RMSE on the training and test data as follows? </h3> Step6: Hint Step8: <h2> Using HASH of date to split the data </h2> Let's split by date and train. Step10: We can now use the alpha to compute RMSE. Because the alpha value is repeatable, we don't need to worry that the alpha in the compute_rmse will be different from the alpha computed in the compute_alpha.
Python Code: from google.cloud import bigquery Explanation: Repeatable splitting Learrning Objectives * explore the impact of different ways of creating train/valid/test splits Overview Repeatability is important in machine learning. If you do the same thing now and 5 minutes from now and get different answers, then it makes experimentation difficult. In other words, you will find it difficult to gauge whether a change you made has resulted in an improvement or not. End of explanation compute_alpha = #standardSQL SELECT SAFE_DIVIDE( SUM(arrival_delay * departure_delay), SUM(departure_delay * departure_delay)) AS alpha FROM ( SELECT RAND() AS splitfield, arrival_delay, departure_delay FROM `bigquery-samples.airline_ontime_data.flights` WHERE departure_airport = 'DEN' AND arrival_airport = 'LAX' ) WHERE splitfield < 0.8 results = bigquery.Client().query(compute_alpha).to_dataframe() alpha = results["alpha"][0] print(alpha) Explanation: <h3> Create a simple machine learning model </h3> The dataset that we will use is <a href="https://bigquery.cloud.google.com/table/bigquery-samples:airline_ontime_data.flights">a BigQuery public dataset</a> of airline arrival data. Click on the link, and look at the column names. Switch to the Details tab to verify that the number of records is 70 million, and then switch to the Preview tab to look at a few rows. <p> We want to predict the arrival delay of an airline based on the departure delay. The model that we will use is a zero-bias linear model: $$ delay_{arrival} = \alpha * delay_{departure} $$ <p> To train the model is to estimate a good value for $\alpha$. <p> One approach to estimate alpha is to use this formula: $$ \alpha = \frac{\sum delay_{departure} delay_{arrival} }{ \sum delay_{departure}^2 } $$ Because we'd like to capture the idea that this relationship is different for flights from New York to Los Angeles vs. flights from Austin to Indianapolis (shorter flight, less busy airports), we'd compute a different $alpha$ for each airport-pair. For simplicity, we'll do this model only for flights between Denver and Los Angeles. <h2> Naive random split (not repeatable) </h2> End of explanation compute_rmse = #standardSQL SELECT dataset, SQRT( AVG( (arrival_delay - ALPHA * departure_delay) * (arrival_delay - ALPHA * departure_delay) ) ) AS rmse, COUNT(arrival_delay) AS num_flights FROM ( SELECT IF (RAND() < 0.8, 'train', 'eval') AS dataset, arrival_delay, departure_delay FROM `bigquery-samples.airline_ontime_data.flights` WHERE departure_airport = 'DEN' AND arrival_airport = 'LAX' ) GROUP BY dataset bigquery.Client().query( compute_rmse.replace("ALPHA", str(alpha)) ).to_dataframe() Explanation: <h3> What is wrong with calculating RMSE on the training and test data as follows? </h3> End of explanation train_and_eval_rand = #standardSQL WITH alldata AS ( SELECT IF (RAND() < 0.8, 'train', 'eval') AS dataset, arrival_delay, departure_delay FROM `bigquery-samples.airline_ontime_data.flights` WHERE departure_airport = 'DEN' AND arrival_airport = 'LAX' ), training AS ( SELECT SAFE_DIVIDE( SUM(arrival_delay * departure_delay), SUM(departure_delay * departure_delay)) AS alpha FROM alldata WHERE dataset = 'train' ) SELECT MAX(alpha) AS alpha, dataset, SQRT( AVG( (arrival_delay - alpha * departure_delay) * (arrival_delay - alpha * departure_delay) ) ) AS rmse, COUNT(arrival_delay) AS num_flights FROM alldata, training GROUP BY dataset bigquery.Client().query(train_and_eval_rand).to_dataframe() Explanation: Hint: * Are you really getting the same training data in the compute_rmse query as in the compute_alpha query? * Do you get the same answers each time you rerun the compute_alpha and compute_rmse blocks? <h3> How do we correctly train and evaluate? </h3> <br/> Here's the right way to compute the RMSE using the actual training and held-out (evaluation) data. Note how much harder this feels. Although the calculations are now correct, the experiment is still not repeatable. Try running it several times; do you get the same answer? End of explanation compute_alpha = #standardSQL SELECT SAFE_DIVIDE( SUM(arrival_delay * departure_delay), SUM(departure_delay * departure_delay)) AS alpha FROM `bigquery-samples.airline_ontime_data.flights` WHERE departure_airport = 'DEN' AND arrival_airport = 'LAX' AND ABS(MOD(FARM_FINGERPRINT(date), 10)) < 8 results = bigquery.Client().query(compute_alpha).to_dataframe() alpha = results["alpha"][0] print(alpha) Explanation: <h2> Using HASH of date to split the data </h2> Let's split by date and train. End of explanation compute_rmse = #standardSQL SELECT IF(ABS(MOD(FARM_FINGERPRINT(date), 10)) < 8, 'train', 'eval') AS dataset, SQRT( AVG( (arrival_delay - ALPHA * departure_delay) * (arrival_delay - ALPHA * departure_delay) ) ) AS rmse, COUNT(arrival_delay) AS num_flights FROM `bigquery-samples.airline_ontime_data.flights` WHERE departure_airport = 'DEN' AND arrival_airport = 'LAX' GROUP BY dataset print( bigquery.Client() .query(compute_rmse.replace("ALPHA", str(alpha))) .to_dataframe() .head() ) Explanation: We can now use the alpha to compute RMSE. Because the alpha value is repeatable, we don't need to worry that the alpha in the compute_rmse will be different from the alpha computed in the compute_alpha. End of explanation
7,339
Given the following text description, write Python code to implement the functionality described below step by step Description: <center> Doing Math with Python </center> <center> <p> <b>Amit Saha</b> <p>May 30, PyCon US 2016 <p>Portland, Oregon </center> ## About me - Software Engineer at [Freelancer.com](https Step1: <center><h1>Can we do more than write smart calculators?</h1></center> Python - Making other subjects more lively <img align="center" src="images/collage1.png"></img> matplotlib basemap Interactive Jupyter Notebooks Bringing Science to life Animation of a Projectile motion (Python Source)
Python Code: # Create graphs from algebraic expressions from sympy import Symbol, plot x = Symbol('x') p = plot(2*x**2 + 2*x + 2) # Solve equations from sympy import solve, Symbol x = Symbol('x') solve(2*x + 1) # Limits from sympy import Symbol, Limit, sin x = Symbol('x') Limit(sin(x)/x, x, 0).doit() # Derivative from sympy import Symbol, Derivative, sin, init_printing x = Symbol('x') init_printing() Derivative(sin(x)**(2*x+1), x).doit() # Indefinite integral from sympy import Symbol, Integral, sqrt, sin, init_printing x = Symbol('x') init_printing() Integral(sqrt(x)).doit() # Definite integral from sympy import Symbol, Integral, sqrt x = Symbol('x') Integral(sqrt(x), (x, 0, 2)).doit() Explanation: <center> Doing Math with Python </center> <center> <p> <b>Amit Saha</b> <p>May 30, PyCon US 2016 <p>Portland, Oregon </center> ## About me - Software Engineer at [Freelancer.com](https://www.freelancer.com) HQ in Sydney, Australia - Author of "Doing Math with Python" (No Starch Press, 2015) - Writes for Linux Voice, Linux Journal, and others. - [Blog](http://echorand.me), [GitHub](http://github.com/amitsaha) #### Contact - [@echorand](http://twitter.com/echorand) - [Email](mailto:amitsaha.in@gmail.com) ### Book: Doing Math with Python *Use PYCONMATH code to get 30% off "Doing Math with Python" from [No Starch Press](https://www.nostarch.com/doingmathwithpython)* <img align="center" src="images/dmwp-cover.png" href="https://doingmathwithpython.github.io"></img> (Valid from May 26th - June 8th) Book Signing - May 31st - 2.00 PM - No Starch Press booth ### What? *Python can lead to a more enriching learning and teaching experience in the classroom* How? *Next slides* ### Tools (or, Giant shoulders we will stand on) <img align="center" src="images/giant_shoulders_collage.jpg"></img> *Python 3*, *SymPy*, *matplotlib* *Individual logos are copyright of the respective projects. [Source](http://www.orphancaremovement.org/standing-on-the-shoulder-of-giants/) of the "giant shoulders" image. ### Python - a scientific calculator Whose calculator looks like this? ```python >>> (131 + 21.5 + 100.2 + 88.7 + 99.5 + 100.5 + 200.5)/4 185.475 ``` *Python 3 is my favorite calculator (not Python 2 because 1/2 = 0)* Beyond basic operations: - `fabs()`, `abs()`, `sin()`, `cos()`, `gcd()`, `log()` and more (See [math](https://docs.python.org/3/library/math.html)) - Descriptive statistics (See [statistics](https://docs.python.org/3/library/statistics.html#module-statistics)) ### Python - a scientific calculator - Develop your own functions: unit conversion, finding correlation, .., anything really - Use PYTHONSTARTUP to extend the battery of readily available mathematical functions ```python $ PYTHONSTARTUP=~/work/dmwp/pycon-us-2016/startup_math.py idle3 -s ``` ### Unit conversion functions ```python >>> unit_conversion() 1. Kilometers to Miles 2. Miles to Kilometers 3. Kilograms to Pounds 4. Pounds to Kilograms 5. Celsius to Fahrenheit 6. Fahrenheit to Celsius Which conversion would you like to do? 6 Enter temperature in fahrenheit: 98 Temperature in celsius: 36.66666666666667 >>> ``` ### Finding linear correlation ```python >>> >>> x = [1, 2, 3, 4] >>> y = [2, 4, 6.1, 7.9] >>> find_corr_x_y(x, y) 0.9995411791453812 ``` ### Python - a really fancy calculator SymPy - a pure Python symbolic math library *from sympy import awesomeness* - don't try that :) End of explanation from IPython.display import YouTubeVideo YouTubeVideo("8uWRVh58KdQ") Explanation: <center><h1>Can we do more than write smart calculators?</h1></center> Python - Making other subjects more lively <img align="center" src="images/collage1.png"></img> matplotlib basemap Interactive Jupyter Notebooks Bringing Science to life Animation of a Projectile motion (Python Source) End of explanation
7,340
Given the following text description, write Python code to implement the functionality described below step by step Description: First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The labels are limited to 'A' through 'J' (10 classes). The training set has about 500k and the testset 19000 labelled examples. Given these sizes, it should be possible to train models quickly on any machine. Step2: Deep Learning Assignment 1 The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later. This notebook uses the notMNIST dataset to be used with python experiments. This dataset is designed to look like the classic MNIST dataset, while looking a little more like real data Step3: Extract the dataset from the compressed .tar.gz file. This should give you a set of directories, labelled A through J. Step4: Problem 1 Let's take a peek at some of the data to make sure it looks sensible. Each exemplar should be an image of a character A through J rendered in a different font. Display a sample of the images that we just downloaded. Hint Step6: Now let's load the data in a more manageable format. Since, depending on your computer setup you might not be able to fit it all in memory, we'll load each class into a separate dataset, store them on disk and curate them independently. Later we'll merge them into a single dataset of manageable size. We'll convert the entire dataset into a 3D array (image index, x, y) of floating point values, normalized to have approximately zero mean and standard deviation ~0.5 to make training easier down the road. A few images might not be readable, we'll just skip them. Step7: Problem 2 Let's verify that the data still looks good. Displaying a sample of the labels and images from the ndarray. Hint Step8: Problem 3 Another check Step9: Merge and prune the training data as needed. Depending on your computer setup, you might not be able to fit it all in memory, and you can tune s_iTrainSize as needed. The labels will be stored into a separate array of integers 0 through 9. Also create a validation dataset for hyperparameter tuning. Step10: Next, we'll randomize the data. It's important to have the labels well shuffled for the training and test distributions to match. Step11: Problem 4 Convince yourself that the data is still good after shuffling! Step12: Finally, let's save the data for later reuse Step13: Problem 5 By construction, this dataset might contain a lot of overlapping samples, including training data that's also contained in the validation and test set! Overlap between training and test can skew the results if you expect to use your model in an environment where there is never an overlap, but are actually ok if you expect to see training samples recur when you use it. Measure how much overlap there is between training, validation and test samples. Optional questions Step14: Problem 6 Let's get an idea of what an off-the-shelf classifier can give you on this data. It's always good to check that there is something to learn, and that it's a problem that is not so trivial that a canned solution solves it. Train a simple model on this data using 50, 100, 1000 and 5000 training samples. Hint
Python Code: # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import matplotlib.pyplot as plt import numpy as np import os import sys import tarfile from IPython.display import display, Image from scipy import ndimage from sklearn.linear_model import LogisticRegression from six.moves.urllib.request import urlretrieve from six.moves import cPickle as pickle Explanation: First, we'll download the dataset to our local machine. The data consists of characters rendered in a variety of fonts on a 28x28 image. The labels are limited to 'A' through 'J' (10 classes). The training set has about 500k and the testset 19000 labelled examples. Given these sizes, it should be possible to train models quickly on any machine. End of explanation url = 'http://yaroslavvb.com/upload/notMNIST/' def maybe_download(filename, expected_bytes, force=False): Download a file if not present, and make sure it's the right size. if force or not os.path.exists(filename): filename, _ = urlretrieve(url + filename, filename) statinfo = os.stat(filename) if statinfo.st_size == expected_bytes: print('Found and verified', filename) else: raise Exception( 'Failed to verify ' + filename + '. Can you get to it with a browser?') return filename strRawCompressedTrainSetFilename = maybe_download('notMNIST_large.tar.gz', 247336696) strRawCompressedTestSetFilename = maybe_download('notMNIST_small.tar.gz', 8458043) Explanation: Deep Learning Assignment 1 The objective of this assignment is to learn about simple data curation practices, and familiarize you with some of the data we'll be reusing later. This notebook uses the notMNIST dataset to be used with python experiments. This dataset is designed to look like the classic MNIST dataset, while looking a little more like real data: it's a harder task, and the data is a lot less 'clean' than MNIST. End of explanation s_iNum_classes = 10 np.random.seed(133) def maybe_extract(filename, force=False): root = os.path.splitext(os.path.splitext(filename)[0])[0] # remove .tar.gz if os.path.isdir(root) and not force: # You may override by setting force=True. print('%s already present - Skipping extraction of %s.' % (root, filename)) else: print('Extracting data for %s. This may take a while. Please wait.' % root) tar = tarfile.open(filename) sys.stdout.flush() tar.extractall() tar.close() data_folders = [ os.path.join(root, d) for d in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, d))] if len(data_folders) != s_iNum_classes: raise Exception( 'Expected %d folders, one per class. Found %d instead.' % ( s_iNum_classes, len(data_folders))) print(data_folders) return data_folders print("s_strListExtractedTrainFolderNames: ") s_strListExtractedTrainFolderNames = maybe_extract(strRawCompressedTrainSetFilename) print("\ns_strListExtractedTestFolderNames: ") s_strListExtractedTestFolderNames = maybe_extract(strRawCompressedTestSetFilename) Explanation: Extract the dataset from the compressed .tar.gz file. This should give you a set of directories, labelled A through J. End of explanation ######################################## SKIP THIS CELL ############################################ from IPython.display import Image Image(filename='./notMNIST_large/A/Z2xlZXN0ZWFrLnR0Zg==.png') Explanation: Problem 1 Let's take a peek at some of the data to make sure it looks sensible. Each exemplar should be an image of a character A through J rendered in a different font. Display a sample of the images that we just downloaded. Hint: you can use the package IPython.display. End of explanation s_iImage_size = 28 # Pixel width and height. s_fPixel_depth = 255.0 # Number of levels per pixel. def load_letter(folder, min_num_images): Load the data for a single letter label, insuring you have at least min_num_images. image_files = os.listdir(folder) #An ndarray is a (often fixed) multidimensional container of items of the same type and size #so here, we're building a 3d array with indexes (image index, x,y), and type float32 dataset = np.ndarray(shape=(len(image_files), s_iImage_size, s_iImage_size), dtype=np.float32) image_index = 0 #for each image in the current folder (A, B, etc) print(folder) for image in os.listdir(folder): #get the full image path image_file = os.path.join(folder, image) try: #read image as a bunch of floats, and normalize those floats by using pixel_depth image_data = (ndimage.imread(image_file).astype(float) - s_fPixel_depth / 2) / s_fPixel_depth #ensure image shape is standard if image_data.shape != (s_iImage_size, s_iImage_size): raise Exception('Unexpected image shape: %s' % str(image_data.shape)) #and put it in the dataset dataset[image_index, :, :] = image_data image_index += 1 except IOError as e: print('Could not read:', image_file, ':', e, '- it\'s ok, skipping.') num_images = image_index dataset = dataset[0:num_images, :, :] if num_images < min_num_images: raise Exception('Many fewer images than expected: %d < %d' % (num_images, min_num_images)) print('Full dataset tensor:', dataset.shape) print('Mean:', np.mean(dataset)) print('Standard deviation:', np.std(dataset)) return dataset def maybe_pickle(p_strDataFolderNames, p_iMin_num_images_per_class, p_bForce=False): dataset_names = [] #data_folders are either the train or test set. folders within those are A, B, etc for strCurFolderName in p_strDataFolderNames: #we will serialize those subfolders (A, B, etc), that's what pickling is strCurSetFilename = strCurFolderName + '.pickle' #add the name of the current pickled subfolder to the list dataset_names.append(strCurSetFilename) #if the pickled folder already exists, skip if os.path.exists(strCurSetFilename) and not p_bForce: # You may override by setting force=True. print('%s already present - Skipping pickling.' % strCurSetFilename) else: #call the load_letter function def above print('Pickling %s.' % strCurSetFilename) dataset = load_letter(strCurFolderName, p_iMin_num_images_per_class) try: #and try to pickle it with open(strCurSetFilename, 'wb') as f: pickle.dump(dataset, f, pickle.HIGHEST_PROTOCOL) except Exception as e: print('Unable to save data to', set_filename, ':', e) return dataset_names s_strListPickledTrainFilenames = maybe_pickle(s_strListExtractedTrainFolderNames, 45000) s_strListPickledTestFilenames = maybe_pickle(s_strListExtractedTestFolderNames, 1800) print("\ns_strListPickledTrainFilenames: ", s_strListPickledTrainFilenames) print("\ns_strListPickledTestFilenames: ", s_strListPickledTestFilenames) Explanation: Now let's load the data in a more manageable format. Since, depending on your computer setup you might not be able to fit it all in memory, we'll load each class into a separate dataset, store them on disk and curate them independently. Later we'll merge them into a single dataset of manageable size. We'll convert the entire dataset into a 3D array (image index, x, y) of floating point values, normalized to have approximately zero mean and standard deviation ~0.5 to make training easier down the road. A few images might not be readable, we'll just skip them. End of explanation ######################################## SKIP THIS CELL ############################################ #un-serialize first sub-folder of the train set random_class_id = np.random.randint(0,s_iNum_classes) unpickled_rnd_train_set = pickle.load(open(s_strListPickledTrainFilenames[random_class_id])) #get xy array representing random image random_img_id = np.random.randint(0,unpickled_rnd_train_set.shape[0]) first_img = unpickled_rnd_train_set[random_img_id,:,:] # checking image shape, it is 28x28 pixels # print("image %d from class %d with shape %d" %(random_img_id, random_class_id, first_img.shape)) print("image ", random_img_id, " from class ", random_class_id, " with shape ", first_img.shape) # denormalization, but commented since doesn't change anything for imshow. The way i understand # this, is that in these images, the each one of the 28x28 pixels is only encoding grayscale, not # rgb. And the imshow doc says that it can handle grayscale arrays that are normalized # (http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow). # s_fPixel_depth = 255.0 # Number of levels per pixel. # first_img = first_img*s_fPixel_depth + s_fPixel_depth/2 # print(first_img[0,:]) plt.imshow(first_img) plt.show() Explanation: Problem 2 Let's verify that the data still looks good. Displaying a sample of the labels and images from the ndarray. Hint: you can use matplotlib.pyplot. End of explanation ######################################## SKIP THIS CELL ############################################ #cycle through all train and test sets and count how many examples we have? Also need to check #their mean and variance? all_counts = np.zeros(s_iNum_classes) all_means = np.zeros(s_iNum_classes) all_variances = np.zeros(s_iNum_classes) #for cur_class_id, cur_class in enumerate(unpickled_all_train_sets): for cur_class_id in range(s_iNum_classes): #we unpickle here a 3d array with shape: image_ids, xs, ys unpickled_cur_train_set = pickle.load(open(s_strListPickledTrainFilenames[cur_class_id])) print ("class ", cur_class_id) for cur_image_id in range(len(unpickled_cur_train_set)): # print ("image", cur_image_id) all_counts[cur_class_id] += 1 # cur_image = unpickled_cur_train_set() all_means[cur_class_id] += np.mean(unpickled_cur_train_set[cur_image_id]) all_variances[cur_class_id] += np.var(unpickled_cur_train_set[cur_image_id]) print ("all_counts: %d", all_counts) all_means = np.divide(all_means, s_iNum_classes) print ("mean of all_means: ", all_means) all_variances = np.divide(all_variances, s_iNum_classes) print ("mean of all_variances: ", all_variances) Explanation: Problem 3 Another check: we expect the data to be balanced across classes. Verify that. End of explanation #from p_iNb_rows and p_iImg_size: # return dataset: an empty 3d array that is [p_iNb_rows, p_iImg_size, p_iImg_size] # return labels: an empty vector that is [p_iNb_rows] def make_arrays(p_iNb_rows, p_iImg_size): if p_iNb_rows: dataset = np.ndarray((p_iNb_rows, p_iImg_size, p_iImg_size), dtype=np.float32) labels = np.ndarray(p_iNb_rows, dtype=np.int32) else: dataset, labels = None, None return dataset, labels #p_strListPickle_files is an array containing the filenames of the pickled data def merge_datasets(p_strListPickledFilenames, p_iTrainSize, p_iValidSize=0): iNum_classes = len(p_strListPickledFilenames) #make empty arrays for validation and training sets and labels valid_dataset, valid_labels = make_arrays(p_iValidSize, s_iImage_size) train_dataset, train_labels = make_arrays(p_iTrainSize, s_iImage_size) #number of items per class. // is an int division in python3, not sure in python2 iNbrOfValidItemsPerClass = p_iValidSize // iNum_classes iNbrOfTrainItemPerClass = p_iTrainSize // iNum_classes #figure out useful indexes for the loop iStartValidId, iStartTrainId = 0, 0 iEndValidId, iEndTrainId = iNbrOfValidItemsPerClass, iNbrOfTrainItemPerClass iEndListId = iNbrOfValidItemsPerClass+iNbrOfTrainItemPerClass #for each file in p_strListPickledFilenames for iPickleFileId, strPickleFilename in enumerate(p_strListPickledFilenames): try: #open the file with open(strPickleFilename, 'rb') as f: print (strPickleFilename) #unpicke 3d array for current file threeDCurLetterSet = pickle.load(f) # let's shuffle the items to have random validation and training set. # np.random.shuffle suffles only first dimension np.random.shuffle(threeDCurLetterSet) #if we asked for a validation set if valid_dataset is not None: #the first iNbrOfValidItemsPerClass items in letter_set are used for the validation set threeDValidItems = threeDCurLetterSet[:iNbrOfValidItemsPerClass, :, :] valid_dataset[iStartValidId:iEndValidId, :, :] = threeDValidItems #label all images with the current file id valid_labels[iStartValidId:iEndValidId] = iPickleFileId #update ids for the train set iStartValidId += iNbrOfValidItemsPerClass iEndValidId += iNbrOfValidItemsPerClass #the rest of the items are used for the training set threeDTrainItems = threeDCurLetterSet[iNbrOfValidItemsPerClass:iEndListId, :, :] train_dataset[iStartTrainId:iEndTrainId, :, :] = threeDTrainItems train_labels[iStartTrainId:iEndTrainId] = iPickleFileId iStartTrainId += iNbrOfTrainItemPerClass iEndTrainId += iNbrOfTrainItemPerClass except Exception as e: print('Unable to process data from', strPickleFilename, ':', e) raise return valid_dataset, valid_labels, train_dataset, train_labels #original values # s_iTrainSize = 200000 # s_iValid_size = 10000 # s_iTestSize = 10000 s_iTrainSize = 200000 s_iValid_size = 10000 s_iTestSize = 10000 #call merge_datasets on data_sets and labels s_threeDValidDataset, s_vValidLabels, s_threeDTrainDataset, s_vTrainLabels = merge_datasets(s_strListPickledTrainFilenames, s_iTrainSize, s_iValid_size) _, _, s_threeDTestDataset, s_vTestLabels = merge_datasets(s_strListPickledTestFilenames, s_iTestSize) #print shapes for data sets and their respective labels. data sets are 3d arrays with [image_id,x,y] and labels #are [image_ids] print('Training:', s_threeDTrainDataset.shape, s_vTrainLabels.shape) print('Validation:', s_threeDValidDataset.shape, s_vValidLabels.shape) print('Testing:', s_threeDTestDataset.shape, s_vTestLabels.shape) Explanation: Merge and prune the training data as needed. Depending on your computer setup, you might not be able to fit it all in memory, and you can tune s_iTrainSize as needed. The labels will be stored into a separate array of integers 0 through 9. Also create a validation dataset for hyperparameter tuning. End of explanation def randomize(p_3dDataset, p_vLabels): #with int x as parameter, np.random.permutation returns a random permutation of np.arange(x) vPermutation = np.random.permutation(p_vLabels.shape[0]) threeDShuffledDataset = p_3dDataset[vPermutation,:,:] threeDShuffledLabels = p_vLabels [vPermutation] return threeDShuffledDataset, threeDShuffledLabels s_threeDTrainDataset, s_vTrainLabels = randomize(s_threeDTrainDataset, s_vTrainLabels) s_threeDTestDataset, s_vTestLabels = randomize(s_threeDTestDataset, s_vTestLabels) s_threeDValidDataset, s_vValidLabels = randomize(s_threeDValidDataset, s_vValidLabels) print(s_threeDTrainDataset.shape) print(s_threeDTestDataset.shape) print(s_threeDValidDataset.shape) Explanation: Next, we'll randomize the data. It's important to have the labels well shuffled for the training and test distributions to match. End of explanation ######################################## SKIP THIS CELL ############################################ #cycle through train, validation, and test sets to count how many items we have for each label, and calculate #their mean and variance s_vAllShuffledMeans = np.zeros(3) s_vAllShuffledVars = np.zeros(3) for iCurTrainingImageId in range(s_threeDTrainDataset.shape[0]): s_vAllShuffledMeans[0] += np.mean(s_threeDTrainDataset[iCurTrainingImageId]) / s_threeDTrainDataset.shape[0] s_vAllShuffledVars[0] += np.var(s_threeDTrainDataset[iCurTrainingImageId]) / s_threeDTrainDataset.shape[0] print ("TRAIN mean: ", s_vAllShuffledMeans[0], "\t variance:", s_vAllShuffledVars[0]) for iCurTestImageId in range(s_threeDTestDataset.shape[0]): s_vAllShuffledMeans[1] += np.mean(s_threeDTestDataset[iCurTestImageId]) / s_threeDTestDataset.shape[0] s_vAllShuffledVars[1] += np.var(s_threeDTestDataset[iCurTestImageId]) / s_threeDTestDataset.shape[0] print ("TEST mean: ", s_vAllShuffledMeans[1], "\t variance:", s_vAllShuffledVars[1]) for iCurValidImageId in range(s_threeDValidDataset.shape[0]): s_vAllShuffledMeans[2] += np.mean(s_threeDValidDataset[iCurValidImageId]) / s_threeDValidDataset.shape[0] s_vAllShuffledVars[2] += np.var(s_threeDValidDataset[iCurValidImageId]) / s_threeDValidDataset.shape[0] print ("VALID mean: ", s_vAllShuffledMeans[2], "\t variance:", s_vAllShuffledVars[2]) Explanation: Problem 4 Convince yourself that the data is still good after shuffling! End of explanation pickle_file = 'notMNIST.pickle' try: f = open(pickle_file, 'wb') save = { 'train_dataset': s_threeDTrainDataset, 'train_labels': s_vTrainLabels, 'valid_dataset': s_threeDValidDataset, 'valid_labels': s_vValidLabels, 'test_dataset': s_threeDTestDataset, 'test_labels': s_vTestLabels, } pickle.dump(save, f, pickle.HIGHEST_PROTOCOL) f.close() except Exception as e: print('Unable to save data to', pickle_file, ':', e) raise statinfo = os.stat(pickle_file) print('Compressed pickle size:', statinfo.st_size) Explanation: Finally, let's save the data for later reuse: End of explanation ######################################## SKIP THIS CELL ############################################ # all_doubles = np.zeros(2) # for iCurTrainImageId in range(s_threeDTrainDataset.shape[0]): # if iCurTrainImageId % 10 == 0: # print (iCurTrainImageId) # for iCurTestImageId in range(s_threeDTestDataset.shape[0]): # if np.array_equal(s_threeDTrainDataset[iCurTrainImageId], s_threeDTestDataset[iCurTestImageId]): # all_doubles[0] += 1 # for iCurValidImageId in range(s_threeDValidDataset.shape[0]): # if np.array_equal(s_threeDTrainDataset[iCurTrainImageId], s_threeDValidDataset[iCurValidImageId]): # all_doubles[1] += 1 # print(all_doubles[0]) # print(all_doubles[1]) #eythian solution, with my edits all_doubles = np.zeros(2) s_threeDTrainDataset.flags.writeable=False #this is probably optional s_threeDTestDataset.flags.writeable=False dup_dict={} #using {} declares a dictionary. this dictionnary will store pairs of keys (image hash) and values (train_data image id) for idx,img in enumerate(s_threeDTrainDataset): h = hash(img.data) #hash returns a hash value for its argument. equal numerical arguments produce the same hash value #'h in dup_dict' tests whether the dictionnary contains the h key, I assume this is very fast if h in dup_dict: # and (s_threeDTrainDataset[dup_dict[h]].data == img.data): #the second part of this is probably redundant... #print ('Duplicate image: %d matches %d' % (idx, dup_dict[h])) all_doubles[0] += 1 dup_dict[h] = idx for idx,img in enumerate(s_threeDTestDataset): h = hash(img.data) if h in dup_dict: # and (s_threeDTrainDataset[dup_dict[h]].data == img.data): #vb commented this last part, it doesn't do anything #print ('Test image %d is in the training set' % idx) all_doubles[1] += 1 print(all_doubles[0]) print(all_doubles[1]) Explanation: Problem 5 By construction, this dataset might contain a lot of overlapping samples, including training data that's also contained in the validation and test set! Overlap between training and test can skew the results if you expect to use your model in an environment where there is never an overlap, but are actually ok if you expect to see training samples recur when you use it. Measure how much overlap there is between training, validation and test samples. Optional questions: - What about near duplicates between datasets? (images that are almost identical) - Create a sanitized validation and test set, and compare your accuracy on those in subsequent assignments. End of explanation ### taking inspiration from http://scikit-learn.org/stable/auto_examples/calibration/plot_compare_calibration.html#example-calibration-plot-compare-calibration-py from sklearn import datasets from sklearn.calibration import calibration_curve train_samples = 100 # number of samples used for training test_samples = 50 #number of samples for test #training patterns. x is input pattern, y is target pattern or label X_train = s_threeDTrainDataset[:train_samples] #fit function below expects to have a vector as the second dimension, not an array X_train = X_train.reshape([X_train.shape[0],X_train.shape[1]*X_train.shape[2]]) y_train = s_vTrainLabels[:train_samples] #test patterns X_test = s_threeDTestDataset[:test_samples] X_test = X_test.reshape([X_test.shape[0],X_test.shape[1]*X_test.shape[2]]) y_test = s_vTestLabels[:test_samples] # Create classifier lr = LogisticRegression() #create plots plt.figure(figsize=(10, 10)) ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2) ax2 = plt.subplot2grid((3, 1), (2, 0)) ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") #try to fit the training data lr.fit(X_train, y_train) #assess how confident (how probable it is correct) the model is at predicting test classifications prob_pos = lr.predict_proba(X_test)[:, 1] #fraction_of_positives, mean_predicted_value = calibration_curve(y_test, prob_pos, n_bins=10) #ax1.plot(mean_predicted_value, fraction_of_positives, "s-", label="%s" % (name, )) ax2.hist(prob_pos, range=(0, 1), bins=10, label='Logistic', histtype="step", lw=2) # ax1.set_ylabel("Fraction of positives") # ax1.set_ylim([-0.05, 1.05]) # ax1.legend(loc="lower right") # ax1.set_title('Calibration plots (reliability curve)') ax2.set_xlabel("Mean predicted value") ax2.set_ylabel("Count") ax2.legend(loc="upper center", ncol=2) plt.tight_layout() plt.show() ########################### SKIP; ORIGINAL LOGISTIC CODE ################################# print(__doc__) # Author: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # License: BSD Style. import numpy as np np.random.seed(0) import matplotlib.pyplot as plt from sklearn import datasets from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.svm import LinearSVC from sklearn.calibration import calibration_curve # X, y = datasets.make_classification(n_samples=100000, n_features=20, n_informative=2, n_redundant=2) train_samples = 100 # Samples used for training the models X_train = X[:train_samples] X_test = X[train_samples:] y_train = y[:train_samples] y_test = y[train_samples:] # Create classifiers lr = LogisticRegression() # gnb = GaussianNB() # svc = LinearSVC(C=1.0) # rfc = RandomForestClassifier(n_estimators=100) ############################################################################### # Plot calibration plots plt.figure(figsize=(10, 10)) ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2) ax2 = plt.subplot2grid((3, 1), (2, 0)) ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") for clf, name in [(lr, 'Logistic')]: # (gnb, 'Naive Bayes'), # (svc, 'Support Vector Classification'), # (rfc, 'Random Forest')]: clf.fit(X_train, y_train) if hasattr(clf, "predict_proba"): prob_pos = clf.predict_proba(X_test)[:, 1] else: # use decision function prob_pos = clf.decision_function(X_test) prob_pos = \ (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min()) fraction_of_positives, mean_predicted_value = \ calibration_curve(y_test, prob_pos, n_bins=10) ax1.plot(mean_predicted_value, fraction_of_positives, "s-", label="%s" % (name, )) ax2.hist(prob_pos, range=(0, 1), bins=10, label=name, histtype="step", lw=2) ax1.set_ylabel("Fraction of positives") ax1.set_ylim([-0.05, 1.05]) ax1.legend(loc="lower right") ax1.set_title('Calibration plots (reliability curve)') ax2.set_xlabel("Mean predicted value") ax2.set_ylabel("Count") ax2.legend(loc="upper center", ncol=2) plt.tight_layout() plt.show() ########################### SKIP; ORIGINAL LOGISTIC CODE FOR 10 CLASSES ################################# print(__doc__) # Author: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de> # License: BSD Style. import numpy as np np.random.seed(0) import matplotlib.pyplot as plt from sklearn import datasets from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.svm import LinearSVC from sklearn.calibration import calibration_curve X, y = datasets.make_classification(n_samples=100000, n_features=20, n_informative=2, n_redundant=2) train_samples = 100 # Samples used for training the models X_train = X[:train_samples] X_test = X[train_samples:] y_train = y[:train_samples] y_test = y[train_samples:] # Create classifiers lr = LogisticRegression() # gnb = GaussianNB() # svc = LinearSVC(C=1.0) # rfc = RandomForestClassifier(n_estimators=100) ############################################################################### # Plot calibration plots plt.figure(figsize=(10, 10)) ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2) ax2 = plt.subplot2grid((3, 1), (2, 0)) ax1.plot([0, 1], [0, 1], "k:", label="Perfectly calibrated") for clf, name in [(lr, 'Logistic')]: # (gnb, 'Naive Bayes'), # (svc, 'Support Vector Classification'), # (rfc, 'Random Forest')]: clf.fit(X_train, y_train) if hasattr(clf, "predict_proba"): prob_pos = clf.predict_proba(X_test)[:, 1] else: # use decision function prob_pos = clf.decision_function(X_test) prob_pos = (prob_pos - prob_pos.min()) / (prob_pos.max() - prob_pos.min()) fraction_of_positives, mean_predicted_value = calibration_curve(y_test, prob_pos, n_bins=10) ax1.plot(mean_predicted_value, fraction_of_positives, "s-", label="%s" % (name, )) ax2.hist(prob_pos, range=(0, 1), bins=10, label=name, histtype="step", lw=2) ax1.set_ylabel("Fraction of positives") ax1.set_ylim([-0.05, 1.05]) ax1.legend(loc="lower right") ax1.set_title('Calibration plots (reliability curve)') ax2.set_xlabel("Mean predicted value") ax2.set_ylabel("Count") ax2.legend(loc="upper center", ncol=2) plt.tight_layout() plt.show() ################# SOMEONE ELSE'S CODE ############################## import time from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier def forum(algo, ntrain, ntest): # X_train = s_threeDTrainDataset[:train_samples] # X_train = X_train.reshape([X_train.shape[0],X_train.shape[1]*X_train.shape[2]]) # y_train = s_vTrainLabels[:train_samples] wh = s_threeDTrainDataset.shape[1] * s_threeDTrainDataset.shape[2] X = s_threeDTrainDataset[:ntrain].reshape(ntrain, wh) Xtest = s_threeDTestDataset[:ntest].reshape(ntest, wh) Y = s_vTrainLabels[:ntrain] Ytest = s_vTestLabels[:ntest] t0 = time.time() algo.fit(X, Y) score = algo.score(Xtest, Ytest) * 100 elapsed = time.time() - t0 print('{} score: {:.1f}% under {:.2f}s'.format(type(algo), score, elapsed)) forum(KNeighborsClassifier(), ntrain=50000, ntest=1000) forum(LogisticRegression(C=10.0, penalty='l1', multi_class='ovr', tol=0.01), ntrain=50000, ntest=1000) Explanation: Problem 6 Let's get an idea of what an off-the-shelf classifier can give you on this data. It's always good to check that there is something to learn, and that it's a problem that is not so trivial that a canned solution solves it. Train a simple model on this data using 50, 100, 1000 and 5000 training samples. Hint: you can use the LogisticRegression model from sklearn.linear_model. Optional question: train an off-the-shelf model on all the data! End of explanation
7,341
Given the following text description, write Python code to implement the functionality described below step by step Description: Copyright 2020 The TensorFlow Authors. Step1: Integrating MinDiff with MinDiffModel <div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https Step2: First, download the data. For succinctness, the input preparation logic has been factored out into helper functions as described in the input preparation guide. You can read the full guide for details on this process. Step3: Original Model This guide uses a basic, untuned keras.Model using the Functional API to highlight using MinDiff. In a real world application, you would carefully choose the model architecture and use tuning to improve model quality before attempting to address any fairness issues. Since MinDiffModel is designed to work with most Keras Model classes, we have factored out the logic of building the model into a helper function Step4: Training with a tf.data.Dataset The equivalent training with a tf.data.Dataset would look very similar (although initialization and input randomness may yield slightly different results). Step5: Integrating MinDiff for training Once the data has been prepared, apply MinDiff to your model with the following steps Step6: Wrap it in a MinDiffModel. Step7: Compile it as you would without MinDiff. Step8: Train it with the MinDiff dataset (train_with_min_diff_ds in this case). Step9: Evaluation and Prediction with MinDiffModel Both evaluating and predicting with a MinDiffModel are similar to doing so with the original model. When calling evaluate you can pass in either the original dataset or the one containing MinDiff data. If you choose the latter, you will also get the min_diff_loss metric in addition to any other metrics being measured loss will also include the min_diff_loss. When calling evaluate you can pass in either the original dataset or the one containing MinDiff data. If you include MinDiff in the call to evaluate, two things will differ Step10: When calling predict you can technically also pass in the dataset with the MinDiff data but it will be ignored and not affect the output. Step11: Limitations of using MinDiffModel directly When using MinDiffModel as described above, most methods will use the default implementations of tf.keras.Model (exceptions listed in the API documentation). Step12: For keras.Sequential or keras.Model, this is perfectly fine since they use the same functions. Step13: However, if your model is a subclass of keras.Model, wrapping it with MinDiffModel will effectively lose the customization.
Python Code: #@title 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 # # https://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. Explanation: Copyright 2020 The TensorFlow Authors. End of explanation !pip install --upgrade tensorflow-model-remediation import tensorflow as tf tf.get_logger().setLevel('ERROR') # Avoid TF warnings. from tensorflow_model_remediation import min_diff from tensorflow_model_remediation.tools.tutorials_utils import uci as tutorials_utils Explanation: Integrating MinDiff with MinDiffModel <div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/responsible_ai/model_remediation/min_diff/guide/integrating_min_diff_with_min_diff_model"> <img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/model-remediation/blob/master/docs/min_diff/guide/integrating_min_diff_with_min_diff_model.ipynb"> <img src="https://www.tensorflow.org/images/colab_logo_32px.png">Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/model-remediation/blob/master/docs/min_diff/guide/integrating_min_diff_with_min_diff_model.ipynb"> <img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">View source on GitHub</a> </td> <td> <a target="_blank" href="https://storage.googleapis.com/tensorflow_docs/model-remediation/docs/min_diff/guide/integrating_min_diff_with_min_diff_model.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a> </td> </table></div> Introduction There are two steps to integrating MinDiff into your model: Prepare the data (covered in the input preparation guide). Alter or create a model that will integrate MinDiff during training. This guide will cover the simplest way to complete the second step: using MinDiffModel. Setup End of explanation # Original DataFrame for training, sampled at 0.3 for reduced runtimes. train_df = tutorials_utils.get_uci_data(split='train', sample=0.3) # Dataset needed to train with MinDiff. train_with_min_diff_ds = ( tutorials_utils.get_uci_with_min_diff_dataset(split='train', sample=0.3)) Explanation: First, download the data. For succinctness, the input preparation logic has been factored out into helper functions as described in the input preparation guide. You can read the full guide for details on this process. End of explanation model = tutorials_utils.get_uci_model() model.compile(optimizer='adam', loss='binary_crossentropy') df_without_target = train_df.drop(['target'], axis=1) # Drop 'target' for x. _ = model.fit( x=dict(df_without_target), # The model expects a dictionary of features. y=train_df['target'], batch_size=128, epochs=1) Explanation: Original Model This guide uses a basic, untuned keras.Model using the Functional API to highlight using MinDiff. In a real world application, you would carefully choose the model architecture and use tuning to improve model quality before attempting to address any fairness issues. Since MinDiffModel is designed to work with most Keras Model classes, we have factored out the logic of building the model into a helper function: get_uci_model. Training with a Pandas DataFrame This guide trains over a single epoch for speed, but could easily improve the model's performance by increasing the number of epochs. End of explanation model = tutorials_utils.get_uci_model() model.compile(optimizer='adam', loss='binary_crossentropy') _ = model.fit( tutorials_utils.df_to_dataset(train_df, batch_size=128), # Converted to Dataset. epochs=1) Explanation: Training with a tf.data.Dataset The equivalent training with a tf.data.Dataset would look very similar (although initialization and input randomness may yield slightly different results). End of explanation original_model = tutorials_utils.get_uci_model() Explanation: Integrating MinDiff for training Once the data has been prepared, apply MinDiff to your model with the following steps: Create the original model as you would without MinDiff. End of explanation min_diff_model = min_diff.keras.MinDiffModel( original_model=original_model, loss=min_diff.losses.MMDLoss(), loss_weight=1) Explanation: Wrap it in a MinDiffModel. End of explanation min_diff_model.compile(optimizer='adam', loss='binary_crossentropy') Explanation: Compile it as you would without MinDiff. End of explanation _ = min_diff_model.fit(train_with_min_diff_ds, epochs=1) Explanation: Train it with the MinDiff dataset (train_with_min_diff_ds in this case). End of explanation _ = min_diff_model.evaluate( tutorials_utils.df_to_dataset(train_df, batch_size=128)) # Calling with MinDiff data will include min_diff_loss in metrics. _ = min_diff_model.evaluate(train_with_min_diff_ds) Explanation: Evaluation and Prediction with MinDiffModel Both evaluating and predicting with a MinDiffModel are similar to doing so with the original model. When calling evaluate you can pass in either the original dataset or the one containing MinDiff data. If you choose the latter, you will also get the min_diff_loss metric in addition to any other metrics being measured loss will also include the min_diff_loss. When calling evaluate you can pass in either the original dataset or the one containing MinDiff data. If you include MinDiff in the call to evaluate, two things will differ: An additional metric called min_diff_loss will be present in the output. The value of the loss metric will be the sum of the original loss metric (not shown in the output) and the min_diff_loss. End of explanation _ = min_diff_model.predict( tutorials_utils.df_to_dataset(train_df, batch_size=128)) _ = min_diff_model.predict(train_with_min_diff_ds) # Identical to results above. Explanation: When calling predict you can technically also pass in the dataset with the MinDiff data but it will be ignored and not affect the output. End of explanation print('MinDiffModel.fit == keras.Model.fit') print(min_diff.keras.MinDiffModel.fit == tf.keras.Model.fit) print('MinDiffModel.train_step == keras.Model.train_step') print(min_diff.keras.MinDiffModel.train_step == tf.keras.Model.train_step) Explanation: Limitations of using MinDiffModel directly When using MinDiffModel as described above, most methods will use the default implementations of tf.keras.Model (exceptions listed in the API documentation). End of explanation print('Sequential.fit == keras.Model.fit') print(tf.keras.Sequential.fit == tf.keras.Model.fit) print('tf.keras.Sequential.train_step == keras.Model.train_step') print(tf.keras.Sequential.train_step == tf.keras.Model.train_step) Explanation: For keras.Sequential or keras.Model, this is perfectly fine since they use the same functions. End of explanation class CustomModel(tf.keras.Model): def train_step(self, **kwargs): pass # Custom implementation. print('CustomModel.train_step == keras.Model.train_step') print(CustomModel.train_step == tf.keras.Model.train_step) Explanation: However, if your model is a subclass of keras.Model, wrapping it with MinDiffModel will effectively lose the customization. End of explanation
7,342
Given the following text description, write Python code to implement the functionality described below step by step Description: 2 samples permutation test on source data with spatio-temporal clustering Tests if the source space data are significantly different between 2 groups of subjects (simulated here using one subject's data). The multiple comparisons problem is addressed with a cluster-level permutation test across space and time. Step1: Set parameters Step2: Compute statistic To use an algorithm optimized for spatio-temporal clustering, we just pass the spatial connectivity matrix (instead of spatio-temporal) Step3: Visualize the clusters
Python Code: # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import os.path as op import numpy as np from scipy import stats as stats import mne from mne import spatial_src_connectivity from mne.stats import spatio_temporal_cluster_test, summarize_clusters_stc from mne.datasets import sample print(__doc__) Explanation: 2 samples permutation test on source data with spatio-temporal clustering Tests if the source space data are significantly different between 2 groups of subjects (simulated here using one subject's data). The multiple comparisons problem is addressed with a cluster-level permutation test across space and time. End of explanation data_path = sample.data_path() stc_fname = data_path + '/MEG/sample/sample_audvis-meg-lh.stc' subjects_dir = data_path + '/subjects' src_fname = subjects_dir + '/fsaverage/bem/fsaverage-ico-5-src.fif' # Load stc to in common cortical space (fsaverage) stc = mne.read_source_estimate(stc_fname) stc.resample(50, npad='auto') # Read the source space we are morphing to src = mne.read_source_spaces(src_fname) fsave_vertices = [s['vertno'] for s in src] stc = mne.morph_data('sample', 'fsaverage', stc, grade=fsave_vertices, smooth=20, subjects_dir=subjects_dir) n_vertices_fsave, n_times = stc.data.shape tstep = stc.tstep n_subjects1, n_subjects2 = 7, 9 print('Simulating data for %d and %d subjects.' % (n_subjects1, n_subjects2)) # Let's make sure our results replicate, so set the seed. np.random.seed(0) X1 = np.random.randn(n_vertices_fsave, n_times, n_subjects1) * 10 X2 = np.random.randn(n_vertices_fsave, n_times, n_subjects2) * 10 X1[:, :, :] += stc.data[:, :, np.newaxis] # make the activity bigger for the second set of subjects X2[:, :, :] += 3 * stc.data[:, :, np.newaxis] # We want to compare the overall activity levels for each subject X1 = np.abs(X1) # only magnitude X2 = np.abs(X2) # only magnitude Explanation: Set parameters End of explanation print('Computing connectivity.') connectivity = spatial_src_connectivity(src) # Note that X needs to be a list of multi-dimensional array of shape # samples (subjects_k) x time x space, so we permute dimensions X1 = np.transpose(X1, [2, 1, 0]) X2 = np.transpose(X2, [2, 1, 0]) X = [X1, X2] # Now let's actually do the clustering. This can take a long time... # Here we set the threshold quite high to reduce computation. p_threshold = 0.0001 f_threshold = stats.distributions.f.ppf(1. - p_threshold / 2., n_subjects1 - 1, n_subjects2 - 1) print('Clustering.') T_obs, clusters, cluster_p_values, H0 = clu =\ spatio_temporal_cluster_test(X, connectivity=connectivity, n_jobs=1, threshold=f_threshold) # Now select the clusters that are sig. at p < 0.05 (note that this value # is multiple-comparisons corrected). good_cluster_inds = np.where(cluster_p_values < 0.05)[0] Explanation: Compute statistic To use an algorithm optimized for spatio-temporal clustering, we just pass the spatial connectivity matrix (instead of spatio-temporal) End of explanation print('Visualizing clusters.') # Now let's build a convenient representation of each cluster, where each # cluster becomes a "time point" in the SourceEstimate fsave_vertices = [np.arange(10242), np.arange(10242)] stc_all_cluster_vis = summarize_clusters_stc(clu, tstep=tstep, vertices=fsave_vertices, subject='fsaverage') # Let's actually plot the first "time point" in the SourceEstimate, which # shows all the clusters, weighted by duration subjects_dir = op.join(data_path, 'subjects') # blue blobs are for condition A != condition B brain = stc_all_cluster_vis.plot('fsaverage', hemi='both', colormap='mne', views='lateral', subjects_dir=subjects_dir, time_label='Duration significant (ms)') brain.save_image('clusters.png') Explanation: Visualize the clusters End of explanation
7,343
Given the following text description, write Python code to implement the functionality described below step by step Description: Application Step1: Download prediction files We release four groups of predictions Step2: Finally, load the occupations data from the U.S. Bureau of Labor Statistics, which we'll use to compute the bias correlation. Step3: Define metrics The values in preds.tsv represent binary predictions about whether each of our models predicts that the pronoun corresponds to the occupation term (0) or the other participant (1) in each Winogender example. With this, we can compute two metrics Step4: Computing the bias scores can be slow because of the grouping operations, so we preprocess all runs before running the bootstrap. This gives us a [num_runs, 60] matrix, and we can compute the final bias correlation inside the multibootstrap routine. Step5: Finally, attach these to the run info dataframe - this will make it easier to filter by row later. Step6: Plot overall scores for each group Before we introduce the multibootstrap, let's get a high-level idea of what our metrics look like by just computing the mean scores for each group Step7: Note that accuracy is very similar across all groups, while - as we might expect - the bias correlation (bias_r) decreases significantly for the CDA runs. Step8: You can also check how much this varies by pretraining seed. As it turns out, not a lot. Here's a plot showing this for the base runs Step9: As a quick check, we can permute the seeds and see if much changes about our estimate Step10: Figure 5 (Appendix) Step11: Figure 3 Step12: Appendix D Step13: Figure 6 Step14: Now we can also use the multibootstrap as a statistical test to check for differences between these seeds. We'll compare seed 0 to seed 1, and do an unpaired analysis Step15: Section 4.1 / Table 1 Step16: Plot result distribution It can also be illustrative to look directly at the distribution of samples Step17: Section 4.2 / Table 2 Step18: Do we actually need to do the full multiboostrap, where we sample over both seeds and examples simultaneously? We can check this with ablations where we sample over one axis only
Python Code: #@title Import libraries and multibootstrap code import re import os import numpy as np import pandas as pd import sklearn.metrics import scipy.stats from tqdm.notebook import tqdm # for progress indicator import multibootstrap #@title Import and configure plotting libraries import matplotlib from matplotlib import pyplot import seaborn as sns sns.set_style('white') %config InlineBackend.figure_format = 'retina' # make matplotlib plots look better from IPython.display import display Explanation: Application: Gender Bias in Coreference Systems This notebook walks through the analysis in Section 4 of the paper. We'll look at accuracy and bias correlation metrics on the Winogender dataset of Rudinger et al. 2018, and show how the multibootstrap can be used in two different ways: A paired analysis of an intervention (incremental CDA) applied to pretrained checkpoints. An unpaired analysis comparing to a new set of checkpoints trained with a different procedure (CDA full). This notebook will download pre-computed predictions, which are exactly the predictions used in the paper; the cells below should allow you to directly reproduce Figure 3, Table 1, and Table 2 from Section 4, as well as Figure 5, Figure 6, and Table 4 from Appendix D. Import packages End of explanation #@title Download predictions and metadata scratch_dir = "/tmp/multiberts_coref" if not os.path.isdir(scratch_dir): os.mkdir(scratch_dir) preds_root = "https://storage.googleapis.com/multiberts/public/example-predictions/coref" GROUP_NAMES = [ 'base', 'base_extra_seeds', 'cda_intervention-50k', 'from_scratch' ] for name in GROUP_NAMES: !mkdir -p $scratch_dir/$name for fname in ['label_info.tsv', 'preds.tsv', 'run_info.tsv']: !curl -s -O $preds_root/$name/$fname --output-dir $scratch_dir/$name # Fetch Winogender occupations data from official repo https://github.com/rudinger/winogender-schemas !curl -s -O https://raw.githubusercontent.com/rudinger/winogender-schemas/master/data/occupations-stats.tsv \ --output-dir $scratch_dir !ls $scratch_dir/** #@title Load run information data_root = scratch_dir all_run_info = [] for group_name in GROUP_NAMES: run_info_path = os.path.join(data_root, group_name, "run_info.tsv") run_info = pd.read_csv(run_info_path, sep='\t', index_col=0) run_info['group_name'] = group_name all_run_info.append(run_info) run_info = pd.concat(all_run_info, axis=0, ignore_index=True) run_info # Count the number of runs in each group run_info.groupby(by='group_name').apply(len) #@title Load predictions all_preds = [] for group_name in GROUP_NAMES: preds_path = os.path.join(data_root, group_name, "preds.tsv") all_preds.append(np.loadtxt(preds_path)) preds = np.concatenate(all_preds, axis=0) preds.shape #@title Load label info label_info_path = os.path.join(data_root, GROUP_NAMES[0], "label_info.tsv") label_info = pd.read_csv(label_info_path, sep='\t', index_col=0) label_info Explanation: Download prediction files We release four groups of predictions: base: the base MultiBERTs models (bert-base-uncased), with 5 coreference runs for each of 25 pretraining checkpoints. cda_intervention-50k: as above, but with 50k steps of CDA applied to each checkpoint. 5 coreference runs for each of 25 pretraining checkpoints, paired with base. from_scratch: trained from-scratch using CDA data. 5 coreference runs for each of 25 pretraining checkpoints, which are not paired with the above. base_extra_seeds: 25 coreference runs for each of the first five pretraining seeds from base; used in Figure 6. For each group, there are three files: * run_info.tsv: run information, with columns pretrain_seed and finetune_seed * label_info.tsv : labels and other metadata for each instance. 720 rows, one for each Winogender example. * preds.tsv: predictions on each instance, with rows aligned to those of run_info.tsv and 720 columns which align to the rows of label_info.tsv. The values in preds.tsv represent the index of the predicted referent, so for Winogender this means: - 0 is the occupation term - 1 is the other_participant You can also browse these files manually here: https://console.cloud.google.com/storage/browser/multiberts/public/example-predictions/coref End of explanation #@title Load occupations data occupation_tsv_path = os.path.join(data_root, "occupations-stats.tsv") # Link to BLS data occupation_data = pd.read_csv(occupation_tsv_path, sep="\t").set_index("occupation") occupation_pf = (occupation_data['bls_pct_female'] / 100.0).sort_index() occupation_pf Explanation: Finally, load the occupations data from the U.S. Bureau of Labor Statistics, which we'll use to compute the bias correlation. End of explanation #@title Define metrics, test on one run def get_accuracy(answers, binary_preds): return np.mean(answers == binary_preds) def get_bias_score(preds_row): df = label_info.copy() df['pred_occupation'] = (preds_row == 0) m_pct = df[df["gender"] == "MASCULINE"].groupby(by="occupation")['pred_occupation'].agg('mean') f_pct = df[df["gender"] == "FEMININE"].groupby(by="occupation")['pred_occupation'].agg('mean') return (f_pct - m_pct).sort_index() # Ensure this aligns with result of get_bias_score sorted_occupations = sorted(list(label_info.occupation.unique())) pf_bls = np.array([occupation_pf[occ] for occ in sorted_occupations]) def get_bias_corr_and_slope(pf_bls, bias_scores): lr = scipy.stats.linregress(pf_bls, bias_scores) return (lr.rvalue, lr.slope) def get_bias_corr(pf_bls, bias_scores): return get_bias_corr_and_slope(pf_bls, bias_scores)[0] def get_bias_slope(pf_bls, bias_scores): return get_bias_corr_and_slope(pf_bls, bias_scores)[1] print("Accuracy:" , get_accuracy(label_info['answer'], preds[0])) print("Bias r, slope:", get_bias_corr_and_slope(pf_bls, get_bias_score(preds[0]))) Explanation: Define metrics The values in preds.tsv represent binary predictions about whether each of our models predicts that the pronoun corresponds to the occupation term (0) or the other participant (1) in each Winogender example. With this, we can compute two metrics: - Accuracy against binary labels (whether the pronoun should refer to the occupation term, the answer column in label_info). For this, we'll run bootstrap over all 720 examples. - Correlation of bias score against each occupation's P(female), according to the U.S. Bureau of Labor Statistics. This is done as in Webster et al. 2020 and Rudinger et al. 2018: for each profession, we compute the fraction of time when female pronouns resolve to it, the fraction of time that male pronouns resolve to it, and take the bias score to be the difference of these two quantities. For this, we'll aggregate to the 60 occupations, then run bootstrap over the set of occupations. These will be used inside the bootstrap, so get_accuracy(), get_bias_corr(), and get_bias_slope() should all take two arguments, aligned lists of labels and predictions. End of explanation bias_scores = np.stack([get_bias_score(p) for p in preds], axis=0) bias_scores.shape Explanation: Computing the bias scores can be slow because of the grouping operations, so we preprocess all runs before running the bootstrap. This gives us a [num_runs, 60] matrix, and we can compute the final bias correlation inside the multibootstrap routine. End of explanation run_info['coref_preds'] = list(preds) run_info['bias_scores'] = list(bias_scores) Explanation: Finally, attach these to the run info dataframe - this will make it easier to filter by row later. End of explanation run_info['accuracy'] = [get_accuracy(label_info['answer'], p) for p in preds] rs, slopes = zip(*[get_bias_corr_and_slope(pf_bls, bs) for bs in bias_scores]) run_info['bias_r'] = rs run_info['bias_slope'] = slopes run_info.groupby(by='group_name')[['accuracy', 'bias_r']].agg('mean') Explanation: Plot overall scores for each group Before we introduce the multibootstrap, let's get a high-level idea of what our metrics look like by just computing the mean scores for each group: End of explanation # Accuracy across runs data = run_info[run_info.group_name == 'base'] desc = data.groupby(by='pretrain_seed').agg(dict(accuracy='mean')).describe() print(f"{desc.accuracy['mean']:.1%} +/- {desc.accuracy['std']:.1%}") Explanation: Note that accuracy is very similar across all groups, while - as we might expect - the bias correlation (bias_r) decreases significantly for the CDA runs. End of explanation #@title Accuracy variation by pretrain run fig = pyplot.figure(figsize=(15, 5)) ax = fig.gca() sns.boxplot(ax=ax, x='pretrain_seed', y='accuracy', data=run_info[run_info.group_name == 'base']) ax.set_title("Accuracy variation by pretrain seed, base") ax.set_ylim(0, 1.0) ax.axhline(0) Explanation: You can also check how much this varies by pretraining seed. As it turns out, not a lot. Here's a plot showing this for the base runs: End of explanation # Accuracy across runs - randomized seed baseline rng = np.random.RandomState(42) data = run_info[run_info.group_name == 'base'].copy() bs = data.accuracy.to_numpy() data['accuracy_bs'] = rng.choice(bs, size=len(bs)) desc = data.groupby(by='pretrain_seed').agg(dict(accuracy_bs='mean')).describe() print(f"With replacement: {desc.accuracy_bs['mean']:.1%} +/- {desc.accuracy_bs['std']:.1%}") rng = np.random.RandomState(42) data = run_info[run_info.group_name == 'base'].copy() bs = data.accuracy.to_numpy() rng.shuffle(bs) data['accuracy_bs'] = bs desc = data.groupby(by='pretrain_seed').agg(dict(accuracy_bs='mean')).describe() print(f"Without replacement: {desc.accuracy_bs['mean']:.1%} +/- {desc.accuracy_bs['std']:.1%}") Explanation: As a quick check, we can permute the seeds and see if much changes about our estimate: End of explanation fig = pyplot.figure(figsize=(15, 7)) ax = fig.gca() base = sns.boxplot(ax=ax, x='pretrain_seed', y='bias_r', data=run_info[run_info.group_name == 'base'], palette=['darkslategray']) ax.set_title("Winogender bias correlation (r) by pretrain seed") ax.set_ylim(-0.2, 1.0) ax.axhline(0) legend_elements = [matplotlib.patches.Patch(facecolor='darkslategray', label='Base')] ax.legend(handles=legend_elements, loc='upper right', fontsize=14) ax.title.set_fontsize(16) ax.set_xlabel("Pretraining Seed", fontsize=14) ax.tick_params(axis='x', labelsize=14) ax.set_ylabel("Bias correlation (r)", fontsize=14) ax.tick_params(axis='y', labelsize=14) # Expected range of accuracy if we randomly sampled data import scipy.stats [n/720.0 - 0.624 for n in scipy.stats.binom.interval(0.682, 720, 0.624)] Explanation: Figure 5 (Appendix): Bias correlation for each pre-training seed Let's do the same as above, but for bias correlation. Again, this is on the whole run - no bootstrap yet - but should give us a sense of the variation you'd expect if you were to run this experiment ad-hoc on different pretraining seeds. As above, we'll just show the base runs: End of explanation expt_group = "cda_intervention-50k" fig = pyplot.figure(figsize=(15, 7)) ax = fig.gca() base = sns.boxplot(ax=ax, x='pretrain_seed', y='bias_r', data=run_info[run_info.group_name == 'base'], palette=['darkslategray']) expt = sns.boxplot(ax=ax, x='pretrain_seed', y='bias_r', data=run_info[run_info.group_name == expt_group], palette=['lightgray']) ax.set_title("Winogender bias correlation (r) by pretrain seed") ax.set_ylim(-0.2, 1.0) ax.axhline(0) legend_elements = [matplotlib.patches.Patch(facecolor='darkslategray', label='Base'), matplotlib.patches.Patch(facecolor='lightgray', label='CDA-incr')] ax.legend(handles=legend_elements, loc='upper right', fontsize=14) ax.title.set_fontsize(16) ax.set_xlabel("Pretraining Seed", fontsize=14) ax.tick_params(axis='x', labelsize=14) ax.set_ylabel("Bias correlation (r)", fontsize=14) ax.tick_params(axis='y', labelsize=14) Explanation: Figure 3: Bias correlation by pretrain seed, base and CDA intervention Now let's compare the base runs to running CDA for 50k steps. Again, no bootstrap yet - just plotting scores on full runs, to get a sense of how much difference we might expect to see if we did this ad-hoc and measured the effect size of CDA using just a single pretraining run. End of explanation data = run_info[run_info.group_name == 'base'].copy() bs = data.bias_r.to_numpy() for i in range (5): rng = np.random.RandomState(i) data[f'bias_r_bs_{i}'] = rng.choice(bs, size=len(bs)) data.groupby(by='pretrain_seed').agg('mean').describe().loc[['mean', 'std']] Explanation: Appendix D: Cross-Seed Variation You might ask: how much of this variation is actually due to the coreference task training? We can see decently large error bars for each pretraining seed above, and we only had five coreference runs each. One simple test is to ignore the pretraining seed. We'll create groups by randomly sampling (with replacement) five runs from the set of runs we have, then looking at the variance in the metrics. We can see that for bias_r, the variance is about 4x as high when using the real seeds (stdev = 0.097 vs 0.049), suggesting that most of the variation does in fact come from pretraining variation. End of explanation fig = pyplot.figure(figsize=(8, 7)) ax = fig.gca() sns.boxplot(ax=ax, x='pretrain_seed', y='bias_r', data=run_info[run_info.group_name == 'base_extra_seeds']) ax.set_title("Bias variation by pretrain seed, base w/extra seeds") ax.set_ylim(-0.2, 1.0) ax.axhline(0) ax.title.set_fontsize(16) ax.set_xlabel("Pretraining Seed", fontsize=14) ax.tick_params(axis='x', labelsize=14) ax.set_ylabel("Bias correlation (r)", fontsize=14) #ax.tick_params(axis='y', labelsize=14) Explanation: Figure 6: Extra task runs Another way to test this is to look at the base_extra_seeds runs, where we ran 5 different pretraining seeds with 25 task runs. This gives us a better estimate of the mean for each pretraining seed. End of explanation #@title Bootstrap to test if seed 1 is different from seed 0 num_bootstrap_samples = 1000 #@param {type: "integer"} rseed=42 mask = (run_info.group_name == 'base_extra_seeds') mask &= (run_info.pretrain_seed == 0) | (run_info.pretrain_seed == 1) selected_runs = run_info[mask].copy() # Set intervention and seed columns selected_runs['intervention'] = (selected_runs.pretrain_seed == 1) selected_runs['seed'] = selected_runs.pretrain_seed print("Available runs:", len(selected_runs)) ## # Compute bias r print("Computing bias r") labels = pf_bls.copy() print("Labels:", labels.dtype, labels.shape) preds = np.stack(selected_runs.bias_scores) print("Preds:", preds.dtype, preds.shape) metric = get_bias_corr samples = multibootstrap.multibootstrap(selected_runs, preds, labels, metric, nboot=num_bootstrap_samples, paired_seeds=False, rng=rseed, progress_indicator=tqdm) multibootstrap.report_ci(samples, c=0.95, expect_negative_effect=False); Explanation: Now we can also use the multibootstrap as a statistical test to check for differences between these seeds. We'll compare seed 0 to seed 1, and do an unpaired analysis: End of explanation num_bootstrap_samples = 1000 #@param {type: "integer"} rseed=42 expt_group = "cda_intervention-50k" mask = (run_info.group_name == 'base') mask |= (run_info.group_name == expt_group) selected_runs = run_info[mask].copy() # Set intervention and seed columns selected_runs['intervention'] = selected_runs.group_name == expt_group selected_runs['seed'] = selected_runs.pretrain_seed print("Available runs:", len(selected_runs)) all_samples = {} ## # Compute accuracy print("Computing accuracy") labels = np.array(label_info['answer']) print("Labels:", labels.dtype, labels.shape) preds = np.stack(selected_runs.coref_preds) print("Preds:", preds.dtype, preds.shape) metric = get_accuracy samples = multibootstrap.multibootstrap(selected_runs, preds, labels, metric, nboot=num_bootstrap_samples, paired_seeds=True, rng=rseed, progress_indicator=tqdm) all_samples['accuracy'] = samples multibootstrap.report_ci(all_samples['accuracy'], c=0.95, expect_negative_effect=True); print() ## # Compute bias r print("Computing bias r") labels = pf_bls.copy() print("Labels:", labels.dtype, labels.shape) preds = np.stack(selected_runs.bias_scores) print("Preds:", preds.dtype, preds.shape) metric = get_bias_corr samples = multibootstrap.multibootstrap(selected_runs, preds, labels, metric, nboot=num_bootstrap_samples, paired_seeds=True, rng=rseed, progress_indicator=tqdm) all_samples['bias_r'] = samples multibootstrap.report_ci(all_samples['bias_r'], c=0.95, expect_negative_effect=True); Explanation: Section 4.1 / Table 1: Paired analysis: base vs. CDA intervention We've seen how much variation there can be across pretraining checkpoints, so let's use the multibootstrap to help us get a better estimate of the effectiveness of CDA. Here, we'll look at CDA for 50k steps as an intervention on the base checkpoints, and so we'll perform a paired analysis where we sample the same pretraining seeds from both sides. base (L) is MultiBERTs following the original BERT recipe, and expt (L') has additional steps with counterfactual data applied to these same checkpoints. We have 25 pretraining seeds on base and the same 25 pretraining seeds on expt. End of explanation #@title Bias r columns = ['Base', 'CDA intervention'] var_name = 'Group Name' val_name = "Bias Correlation" samples = all_samples['bias_r'] fig, axs = pyplot.subplots(1, 2, gridspec_kw=dict(width_ratios=[2, 1]), figsize=(15, 7)) bdf = pd.DataFrame(samples, columns=columns).melt(var_name=var_name, value_name=val_name) bdf['x'] = 0 fig = pyplot.figure(figsize=(10, 7)) ax = axs[0] sns.violinplot(ax=ax, x=var_name, y=val_name, data=bdf, inner='quartile') ax.set_title("MultiBERTs CDA intervention - bias r") ax.axhline(0) var_name = 'Pretraining Steps' val_name = "Accuracy delta" bdf = pd.DataFrame(samples, columns=columns) bdf['deltas'] = bdf['CDA intervention'] - bdf['Base'] bdf = bdf.drop(axis=1, labels=columns).melt(var_name=var_name, value_name=val_name) bdf['x'] = 0 ax = axs[1] sns.violinplot(ax=ax, x=var_name, y=val_name, data=bdf, inner='quartile', palette='gray') ax.set_title("MultiBERTs CDA intervention - bias r deltas") ax.axhline(0) multibootstrap.report_ci(samples, c=0.95, expect_negative_effect=True); Explanation: Plot result distribution It can also be illustrative to look directly at the distribution of samples: End of explanation num_bootstrap_samples = 1000 #@param {type: "integer"} rseed=42 base_group = "cda_intervention-50k" expt_group = "from_scratch" mask = (run_info.group_name == base_group) mask |= (run_info.group_name == expt_group) selected_runs = run_info[mask].copy() # Set intervention and seed columns selected_runs['intervention'] = selected_runs.group_name == expt_group selected_runs['seed'] = selected_runs.pretrain_seed print("Available runs:", len(selected_runs)) all_samples = {} ## # Compute accuracy print("Computing accuracy") labels = np.array(label_info['answer']) print("Labels:", labels.dtype, labels.shape) preds = np.stack(selected_runs.coref_preds) print("Preds:", preds.dtype, preds.shape) metric = get_accuracy samples = multibootstrap.multibootstrap(selected_runs, preds, labels, metric, nboot=num_bootstrap_samples, paired_seeds=False, rng=rseed, progress_indicator=tqdm) all_samples['accuracy'] = samples multibootstrap.report_ci(all_samples['accuracy'], c=0.95, expect_negative_effect=True); print() ## # Compute bias r print("Computing bias r") labels = pf_bls.copy() print("Labels:", labels.dtype, labels.shape) preds = np.stack(selected_runs.bias_scores) print("Preds:", preds.dtype, preds.shape) metric = get_bias_corr samples = multibootstrap.multibootstrap(selected_runs, preds, labels, metric, nboot=num_bootstrap_samples, paired_seeds=False, rng=rseed, progress_indicator=tqdm) all_samples['bias_r'] = samples multibootstrap.report_ci(all_samples['bias_r'], c=0.95, expect_negative_effect=True); #@title Bias r columns = ['CDA intervention', 'CDA from-scratch'] var_name = 'Group Name' val_name = "Bias Correlation" samples = all_samples['bias_r'] fig, axs = pyplot.subplots(1, 2, gridspec_kw=dict(width_ratios=[2, 1]), figsize=(15, 7)) bdf = pd.DataFrame(samples, columns=columns).melt(var_name=var_name, value_name=val_name) bdf['x'] = 0 ax = axs[0] sns.violinplot(ax=ax, x=var_name, y=val_name, data=bdf, inner='quartile') ax.set_title("MultiBERTs CDA intervention vs. from-scratch - bias r") ax.axhline(0) var_name = 'Pretraining Steps' val_name = "Accuracy delta" bdf = pd.DataFrame(samples, columns=columns) bdf['deltas'] = bdf['CDA from-scratch'] - bdf['CDA intervention'] bdf = bdf.drop(axis=1, labels=columns).melt(var_name=var_name, value_name=val_name) bdf['x'] = 0 ax = axs[1] sns.violinplot(ax=ax, x=var_name, y=val_name, data=bdf, inner='quartile', palette='gray') ax.set_title("MultiBERTs CDA intervention vs. from-scratch - bias r deltas") ax.axhline(0) multibootstrap.report_ci(samples, c=0.95, expect_negative_effect=True); Explanation: Section 4.2 / Table 2: Unpaired analysis: CDA intervention vs. CDA from-scratch Here, we'll compare our CDA 50k intervention to a set of models trained from-scratch with CDA data. base (L) is the intevention CDA above, and expt (L') is a similar setup but pretraining from scratch with the counterfactually-augmented data. We have 25 pretraining seeds on base and 25 pretraining seeds on expt, but these are independent runs so we'll do an unpaired analysis. End of explanation #@title As above, but sample seeds only rseed=42 metric = get_bias_corr samples = multibootstrap.multibootstrap(selected_runs, preds, labels, metric, nboot=num_bootstrap_samples, rng=rseed, paired_seeds=False, sample_examples=False, progress_indicator=tqdm) columns = ['CDA intervention', 'CDA from-scratch'] var_name = 'Group Name' val_name = "Bias Correlation" fig, axs = pyplot.subplots(1, 2, gridspec_kw=dict(width_ratios=[2, 1]), figsize=(15, 7)) bdf = pd.DataFrame(samples, columns=columns).melt(var_name=var_name, value_name=val_name) bdf['x'] = 0 ax = axs[0] sns.violinplot(ax=ax, x=var_name, y=val_name, data=bdf, inner='quartile') ax.set_title("MultiBERTs CDA intervention vs. from-scratch - bias r") ax.axhline(0) var_name = 'Pretraining Steps' val_name = "Accuracy delta" bdf = pd.DataFrame(samples, columns=columns) bdf['deltas'] = bdf['CDA from-scratch'] - bdf['CDA intervention'] bdf = bdf.drop(axis=1, labels=columns).melt(var_name=var_name, value_name=val_name) bdf['x'] = 0 ax = axs[1] sns.violinplot(ax=ax, x=var_name, y=val_name, data=bdf, inner='quartile', palette='gray') ax.set_title("MultiBERTs CDA intervention vs. from-scratch - bias r deltas") ax.axhline(0) multibootstrap.report_ci(samples, c=0.95, expect_negative_effect=True); #@title As above, but sample examples only rseed=42 metric = get_bias_corr samples = multibootstrap.multibootstrap(selected_runs, preds, labels, metric, nboot=num_bootstrap_samples, rng=rseed, paired_seeds=False, sample_seeds=False, progress_indicator=tqdm) columns = ['CDA intervention', 'CDA from-scratch'] var_name = 'Group Name' val_name = "Bias Correlation" fig, axs = pyplot.subplots(1, 2, gridspec_kw=dict(width_ratios=[2, 1]), figsize=(15, 7)) bdf = pd.DataFrame(samples, columns=columns).melt(var_name=var_name, value_name=val_name) bdf['x'] = 0 ax = axs[0] sns.violinplot(ax=ax, x=var_name, y=val_name, data=bdf, inner='quartile') ax.set_title("MultiBERTs CDA intervention vs. from-scratch - bias r") ax.axhline(0) var_name = 'Pretraining Steps' val_name = "Accuracy delta" bdf = pd.DataFrame(samples, columns=columns) bdf['deltas'] = bdf['CDA from-scratch'] - bdf['CDA intervention'] bdf = bdf.drop(axis=1, labels=columns).melt(var_name=var_name, value_name=val_name) bdf['x'] = 0 ax = axs[1] sns.violinplot(ax=ax, x=var_name, y=val_name, data=bdf, inner='quartile', palette='gray') ax.set_title("MultiBERTs CDA intervention vs. from-scratch - bias r deltas") ax.axhline(0) multibootstrap.report_ci(samples, c=0.95, expect_negative_effect=True); Explanation: Do we actually need to do the full multiboostrap, where we sample over both seeds and examples simultaneously? We can check this with ablations where we sample over one axis only: Seeds only (sample_examples=False) Examples only (sample_seeds=False) End of explanation
7,344
Given the following text description, write Python code to implement the functionality described below step by step Description: Solving convection-coupled melting with adaptive mixed finite elements This Jupyter notebook shows how to solve the convection-coupled melting benchmark with the general approach of [5], using mixed finite elements in FEniCS with goal-oriented adaptive mesh refinement (AMR) as presented in [6]. |Nomenclature|| |------------|-| |$\mathbf{x}$| point in the spatial domain| |$t$| time | |$p = p(\mathbf{x},t)$| pressure field | |$\mathbf{u} = \mathbf{u}(\mathbf{x},t)$| velocity vector field | |$T = T(\mathbf{x},t)$| temperature field | |$\phi$ | solid volume fraction | |$()_t = \frac{\partial}{\partial t}()$| time derivative | |$T_r$| central temperature of the regularization | |$r$| smoothing parameter of the regularization | |$\mu$| constant dynamic viscosity of the fluid| |$\mathbf{f}_B(T)$| temperature-dependent buoyancy force| |$\mathrm{Pr}$ | Prandtl number| |$\mathrm{Ra}$ | Rayleigh number| |$\mathrm{Ste}$| Stefan number| |$\Omega$| spatial domain | |$\mathbf{w} = \begin{pmatrix} p \ \mathbf{u} \ T \end{pmatrix}$| system solution| |$\mathbf{W}$| mixed finite element function space | |$\boldsymbol{\psi} = \begin{pmatrix} \psi_p \ \boldsymbol{\psi}_u \ \psi_T \end{pmatrix} $| mixed finite element basis functions| |$\gamma$| penalty method stabilization parameter| |$T_h$| hot boundary temperature | |$T_c$| cold boundary temperature | |$\Delta t$| time step size | |$\Omega_h$| discrete spatial domain, i.e. the mesh | |$M$| goal functional | |$\epsilon_M$| error tolerance for goal-oriented AMR | Governing equations To model convection-coupled melting, we employ the system composed of the unsteady incompressible Navier-Stokes-Boussinesq equations and a enthalpy convection-diffusion equation, scaled for unit Reynolds Number as explained in [5], as \begin{align} \nabla \cdot \mathbf{u} &= 0 \ \mathbf{u}_t + \left( \mathbf{u}\cdot\nabla \right)\mathbf{u} + \nabla p - 2\nabla \cdot \left(\mu(\phi)\mathbf{D}(\mathbf{u})\right) + \mathbf{f}_B(T) &= 0 \ T_t + \mathbf{u}\cdot\nabla T - \frac{1}{\mathrm{Pr}}\Delta T - \frac{1}{\mathrm{Ste}}\phi_t &= 0 \end{align} where $\mathbf{D}(\mathbf{u}) = \mathrm{sym}(\mathbf{u}) = \frac{1}{2}\left(\nabla \mathbf{u} + \left( \nabla \mathbf{u} \right)^{\mathrm{T}} \right)$ is the Newtonian fluid's rate of strain tensor and the regularized semi-phase-field (representing the solid volume fraction) is \begin{align} \phi(T) = \frac{1}{2}\left(1 + \tanh{\frac{T_r - T}{r}} \right) \end{align} Python packages Import the Python packages for use in this notebook. We use the finite element method library FEniCS. Step1: |Note| |----| | This Jupyter notebook server is using FEniCS 2017.2.0 from ppa Step2: Tell this notebook to embed graphical outputs from matplotlib, includings those made by fenics.plot. Step3: Initial mesh Define a coarse mesh on the unit square and refine it near the hot wall where there will be an initial layer of melt. Step4: Let's look at the mesh. Step5: Mixed finite element function space, test functions, and solution functions Make the mixed finite element. We choose pressure and velocity subspaces analagous to the Taylor-Hood (i.e. P2P1) mixed element, but we extend this further with a P1 element for the temperature. Step6: |Note| |----| |fenics.FiniteElement requires the mesh.ufl_cell() argument to determine some aspects of the domain (e.g. that the spatial domain is two-dimensional).| Make the mixed finite element function space $\mathbf{W}$, which enumerates the mixed element basis functions on each cell of the mesh. Step7: Make the test functions $\psi_p$, $\boldsymbol{\psi}_u$, and $\psi_T$. Step8: Make the system solution function $\mathbf{w} \in \mathbf{W}$ and obtain references to its components $p$, $\mathbf{u}$, and $T$. Step9: Benchmark parameters Set constant Prandtl, Rayleigh, and Stefan numbers for the convection-coupled melting benchmark in [5] and [6]. For each we define a fenics.Constant for use in the variational form so that FEniCS can more efficiently compile the finite element code. Step10: Define the idealized linear Boussinesq buoyancy, scaled according to [5], \begin{align} \mathbf{f}_B(T) = \frac{\mathrm{Ra}}{\mathrm{Pr}} T\begin{pmatrix} 0 \ -1 \end{pmatrix}. \end{align} Step11: Set the regularized semi-phase-field with a central temperature $T_r$ and smoothing parameter $r$. Step12: Set the phase-dependent dynamic viscosity Step13: Furthermore the benchmark problem involves hot and cold walls with constant temperatures $T_h$ and $T_c$, respectively. Step14: Time discretization To solve the initial value problem, we will prescribe the initial values, and then take discrete steps forward in time which solve the governing equations. We set the initial values such that a small layer of melt already exists touching the hot wall. \begin{align} p^0 &= 0 \ \mathbf{u}^0 &= \mathbf{0} \ T^0 &= \begin{cases} T_h, && x_0 < x_{m,0} \ T_c, && \mathrm{otherwise} \end{cases} \end{align} Interpolate these values to create the initial solution function. Step15: Let's look at the initial values now. Step16: For the time derivative terms $\mathbf{u}_t$, $T_t$, and $\phi_t$, we apply the first-order implicit Euler finite difference time discretization, i.e. \begin{align} \mathbf{u}_t = \frac{\mathbf{u}^{n+1} - \mathbf{u}^n}{\Delta t} \ T_t = \frac{T^{n+1} - T^n}{\Delta t} \ \phi_t = \frac{\phi^{n+1} - \phi^n}{\Delta t} \end{align} |Note| |----| |For our implementation, we will use the shorthand $\mathbf{w} = \mathbf{w}^{n+1}$| Choose a time step size and set the time derivative terms. Step17: Nonlinear variational form We can write the nonlinear system of equations as \begin{align} \mathbf{F}(\mathbf{w}) = \mathbf{0} \end{align} To obtain the finite element weak form, we follow the standard Ritz-Galerkin method extended for mixed finite elements [1]. Therefore, we multiply the system from the left by test functions $\boldsymbol{\psi}$ from the mixed finite element function space $\mathbf{W}$ and integrate over the spatial domain $\Omega$. This gives us the variational problem Step18: Define the nonlinear variational form $\mathcal{F}$. Step19: We add a penalty method stabilization term $-\gamma(\psi_p,p)$, setting the stabilization parameter $\gamma = 10^{-7}$ as done in [5]. |Note| |----| |One can solve the incompressible Navier-Stokes equation either with P2P1 elements, or with the penalty method and P1P1 elements. Neither of these approaches works alone when also coupling the temperature convection-diffusion equation with Boussinesq buoyancy; but applying both stabilization methods together does work.| Step20: Linearization Notice that $\mathcal{F}$ is a nonlinear variational form. FEniCS will solve the nonlinear problem using Newton's method. This requires computing the Jacobian (formally the Gâteaux derivative) of the nonlinear variational form, yielding a a sequence of linearized problems whose solutions may converge to approximate the nonlinear solution. We could manually define the Jacobian; but thankfully FEniCS can do this for us. |Note| |----| |When solving linear variational problems in FEniCS, one defines the linear variational form using fenics.TrialFunction instead of fenics.Function (while both approaches will need fenics.TestFunction). When solving nonlinear variational problems with FEniCS, we only need fenics.TrialFunction to define the linearized problem, since it is the linearized problem which will be assembled into a linear system and solved.| Step21: Boundary conditions We need boundary conditions before we can define a nonlinear variational problem (i.e. in this case a boundary value problem). We physically consider no slip velocity boundary conditions for all boundaries. These manifest as homogeneous Dirichlet boundary conditions. For the temperature boundary conditions, we consider a constant hot temperature on the left wall, a constant cold temperature on the right wall, and adiabatic (i.e. zero heat transfer) conditions on the top and bottom walls. Because the problem's geometry is simple, we can identify the boundaries with the following piece-wise function. \begin{align} T(\mathbf{x}) &= \begin{cases} T_h , && x_0 = 0 \ T_c , && x_0 = 1 \end{cases} \end{align} Step22: Define the boundary conditions on the appropriate subspaces. Step23: Nonlinear variational problem Now we have everything we need to define the variational problem. Step24: Goal-oriented adaptive mesh refinement (AMR) We wish to solve the problem with adaptive mesh refinement (AMR). For this it helps to explain that we have already defined the discrete nonlinear variational problem using FEniCS Step25: Let's set the tolerance somewhat arbitrarily. For real problems of scientific or engineering interest, one might have accuracy requirements which could help drive this decision. Step26: The benchmark solution Finally we instantiate the adaptive solver with our problem and goal Step27: set the Newton solver's initial guess based on the initial values Step28: and solve the problem to the prescribed tolerance. Step29: |Note| |----| |solver.solve will modify the solution w, which means that u and p will also be modified.| Now plot the solid volume fraction, velocity field, and adapted mesh. Step30: Let's run a few more time steps.
Python Code: import fenics Explanation: Solving convection-coupled melting with adaptive mixed finite elements This Jupyter notebook shows how to solve the convection-coupled melting benchmark with the general approach of [5], using mixed finite elements in FEniCS with goal-oriented adaptive mesh refinement (AMR) as presented in [6]. |Nomenclature|| |------------|-| |$\mathbf{x}$| point in the spatial domain| |$t$| time | |$p = p(\mathbf{x},t)$| pressure field | |$\mathbf{u} = \mathbf{u}(\mathbf{x},t)$| velocity vector field | |$T = T(\mathbf{x},t)$| temperature field | |$\phi$ | solid volume fraction | |$()_t = \frac{\partial}{\partial t}()$| time derivative | |$T_r$| central temperature of the regularization | |$r$| smoothing parameter of the regularization | |$\mu$| constant dynamic viscosity of the fluid| |$\mathbf{f}_B(T)$| temperature-dependent buoyancy force| |$\mathrm{Pr}$ | Prandtl number| |$\mathrm{Ra}$ | Rayleigh number| |$\mathrm{Ste}$| Stefan number| |$\Omega$| spatial domain | |$\mathbf{w} = \begin{pmatrix} p \ \mathbf{u} \ T \end{pmatrix}$| system solution| |$\mathbf{W}$| mixed finite element function space | |$\boldsymbol{\psi} = \begin{pmatrix} \psi_p \ \boldsymbol{\psi}_u \ \psi_T \end{pmatrix} $| mixed finite element basis functions| |$\gamma$| penalty method stabilization parameter| |$T_h$| hot boundary temperature | |$T_c$| cold boundary temperature | |$\Delta t$| time step size | |$\Omega_h$| discrete spatial domain, i.e. the mesh | |$M$| goal functional | |$\epsilon_M$| error tolerance for goal-oriented AMR | Governing equations To model convection-coupled melting, we employ the system composed of the unsteady incompressible Navier-Stokes-Boussinesq equations and a enthalpy convection-diffusion equation, scaled for unit Reynolds Number as explained in [5], as \begin{align} \nabla \cdot \mathbf{u} &= 0 \ \mathbf{u}_t + \left( \mathbf{u}\cdot\nabla \right)\mathbf{u} + \nabla p - 2\nabla \cdot \left(\mu(\phi)\mathbf{D}(\mathbf{u})\right) + \mathbf{f}_B(T) &= 0 \ T_t + \mathbf{u}\cdot\nabla T - \frac{1}{\mathrm{Pr}}\Delta T - \frac{1}{\mathrm{Ste}}\phi_t &= 0 \end{align} where $\mathbf{D}(\mathbf{u}) = \mathrm{sym}(\mathbf{u}) = \frac{1}{2}\left(\nabla \mathbf{u} + \left( \nabla \mathbf{u} \right)^{\mathrm{T}} \right)$ is the Newtonian fluid's rate of strain tensor and the regularized semi-phase-field (representing the solid volume fraction) is \begin{align} \phi(T) = \frac{1}{2}\left(1 + \tanh{\frac{T_r - T}{r}} \right) \end{align} Python packages Import the Python packages for use in this notebook. We use the finite element method library FEniCS. End of explanation import matplotlib Explanation: |Note| |----| | This Jupyter notebook server is using FEniCS 2017.2.0 from ppa:fenics-packages/fenics, installed via apt on Ubuntu 16.04.| FEniCS has convenient plotting features that don't require us to import matplotlib; but using matplotlib directly will allow us to annotate the plots. End of explanation %matplotlib inline Explanation: Tell this notebook to embed graphical outputs from matplotlib, includings those made by fenics.plot. End of explanation N = 1 mesh = fenics.UnitSquareMesh(N, N) class HotWall(fenics.SubDomain): def inside(self, x, on_boundary): return on_boundary and fenics.near(x[0], 0.) hot_wall = HotWall() initial_hot_wall_refinement_cycles = 6 for cycle in range(initial_hot_wall_refinement_cycles): edge_markers = fenics.MeshFunction("bool", mesh, 1, False) hot_wall.mark(edge_markers, True) fenics.adapt(mesh, edge_markers) mesh = mesh.child() Explanation: Initial mesh Define a coarse mesh on the unit square and refine it near the hot wall where there will be an initial layer of melt. End of explanation fenics.plot(mesh) matplotlib.pyplot.title("Initial Mesh") matplotlib.pyplot.xlabel("$x$") matplotlib.pyplot.ylabel("$y$") Explanation: Let's look at the mesh. End of explanation P1 = fenics.FiniteElement('P', mesh.ufl_cell(), 1) P2 = fenics.VectorElement('P', mesh.ufl_cell(), 2) mixed_element = fenics.MixedElement([P1, P2, P1]) Explanation: Mixed finite element function space, test functions, and solution functions Make the mixed finite element. We choose pressure and velocity subspaces analagous to the Taylor-Hood (i.e. P2P1) mixed element, but we extend this further with a P1 element for the temperature. End of explanation W = fenics.FunctionSpace(mesh, mixed_element) Explanation: |Note| |----| |fenics.FiniteElement requires the mesh.ufl_cell() argument to determine some aspects of the domain (e.g. that the spatial domain is two-dimensional).| Make the mixed finite element function space $\mathbf{W}$, which enumerates the mixed element basis functions on each cell of the mesh. End of explanation psi_p, psi_u, psi_T = fenics.TestFunctions(W) Explanation: Make the test functions $\psi_p$, $\boldsymbol{\psi}_u$, and $\psi_T$. End of explanation w = fenics.Function(W) p, u, T = fenics.split(w) Explanation: Make the system solution function $\mathbf{w} \in \mathbf{W}$ and obtain references to its components $p$, $\mathbf{u}$, and $T$. End of explanation prandtl_number = 56.2 Pr = fenics.Constant(prandtl_number) rayleigh_number = 3.27e5 Ra = fenics.Constant(rayleigh_number) stefan_number = 0.045 Ste = fenics.Constant(stefan_number) Explanation: Benchmark parameters Set constant Prandtl, Rayleigh, and Stefan numbers for the convection-coupled melting benchmark in [5] and [6]. For each we define a fenics.Constant for use in the variational form so that FEniCS can more efficiently compile the finite element code. End of explanation f_B = Ra/Pr*T*fenics.Constant((0., -1.)) Explanation: Define the idealized linear Boussinesq buoyancy, scaled according to [5], \begin{align} \mathbf{f}_B(T) = \frac{\mathrm{Ra}}{\mathrm{Pr}} T\begin{pmatrix} 0 \ -1 \end{pmatrix}. \end{align} End of explanation regularization_central_temperature = 0.01 T_r = fenics.Constant(regularization_central_temperature) regularization_smoothing_parameter = 0.025 r = fenics.Constant(regularization_smoothing_parameter) tanh = fenics.tanh def phi(T): return 0.5*(1. + tanh((T_r - T)/r)) Explanation: Set the regularized semi-phase-field with a central temperature $T_r$ and smoothing parameter $r$. End of explanation liquid_dynamic_viscosity = 1. mu_L = fenics.Constant(liquid_dynamic_viscosity) solid_dynamic_viscosity = 1.e8 mu_S = fenics.Constant(solid_dynamic_viscosity) def mu(phi): return mu_L + (mu_S - mu_L)*phi Explanation: Set the phase-dependent dynamic viscosity End of explanation hot_wall_temperature = 1. T_h = fenics.Constant(hot_wall_temperature) cold_wall_temperature = -0.01 T_c = fenics.Constant(cold_wall_temperature) Explanation: Furthermore the benchmark problem involves hot and cold walls with constant temperatures $T_h$ and $T_c$, respectively. End of explanation initial_melt_thickness = 1./2.**(initial_hot_wall_refinement_cycles - 1) w_n = fenics.interpolate( fenics.Expression(("0.", "0.", "0.", "(T_h - T_c)*(x[0] < x_m0) + T_c"), T_h = hot_wall_temperature, T_c = cold_wall_temperature, x_m0 = initial_melt_thickness, element = mixed_element), W) p_n, u_n, T_n = fenics.split(w_n) Explanation: Time discretization To solve the initial value problem, we will prescribe the initial values, and then take discrete steps forward in time which solve the governing equations. We set the initial values such that a small layer of melt already exists touching the hot wall. \begin{align} p^0 &= 0 \ \mathbf{u}^0 &= \mathbf{0} \ T^0 &= \begin{cases} T_h, && x_0 < x_{m,0} \ T_c, && \mathrm{otherwise} \end{cases} \end{align} Interpolate these values to create the initial solution function. End of explanation fenics.plot(T_n) matplotlib.pyplot.title("$T^0$") matplotlib.pyplot.xlabel("$x$") matplotlib.pyplot.ylabel("$y$") Explanation: Let's look at the initial values now. End of explanation timestep_size = 10. Delta_t = fenics.Constant(timestep_size) u_t = (u - u_n)/Delta_t T_t = (T - T_n)/Delta_t phi_t = (phi(T) - phi(T_n))/Delta_t Explanation: For the time derivative terms $\mathbf{u}_t$, $T_t$, and $\phi_t$, we apply the first-order implicit Euler finite difference time discretization, i.e. \begin{align} \mathbf{u}_t = \frac{\mathbf{u}^{n+1} - \mathbf{u}^n}{\Delta t} \ T_t = \frac{T^{n+1} - T^n}{\Delta t} \ \phi_t = \frac{\phi^{n+1} - \phi^n}{\Delta t} \end{align} |Note| |----| |For our implementation, we will use the shorthand $\mathbf{w} = \mathbf{w}^{n+1}$| Choose a time step size and set the time derivative terms. End of explanation dx = fenics.dx(metadata={'quadrature_degree': 8}) Explanation: Nonlinear variational form We can write the nonlinear system of equations as \begin{align} \mathbf{F}(\mathbf{w}) = \mathbf{0} \end{align} To obtain the finite element weak form, we follow the standard Ritz-Galerkin method extended for mixed finite elements [1]. Therefore, we multiply the system from the left by test functions $\boldsymbol{\psi}$ from the mixed finite element function space $\mathbf{W}$ and integrate over the spatial domain $\Omega$. This gives us the variational problem: Find $\mathbf{w} \in \mathbf{W}$ such that \begin{align} \mathcal{F}(\boldsymbol{\psi};\mathbf{w}) = \int_\Omega \boldsymbol{\psi}^\mathrm{T} \mathbf{F}(\mathbf{w}) d\mathbf{x} = 0 \quad \forall \boldsymbol{\psi} \in \mathbf{W} \end{align} Integrating $\mathcal{F}$ by parts yields \begin{align} \mathcal{F}(\boldsymbol{\psi};\mathbf{w}) = -(\psi_p,\nabla\cdot\mathbf{u}) \ + (\boldsymbol{\psi}_u, \mathbf{u}_t + \nabla\mathbf{u}\cdot\mathbf{u} + \mathbf{f}_B(T)) -(\nabla\cdot\boldsymbol{\psi}_u,p) + 2\mu(\mathbf{D}(\boldsymbol{\psi}_u),\mathbf{D}(\mathbf{u})) \ + (\psi_T,T_t - \frac{1}{Ste}\phi_t) + (\nabla \psi_T, \frac{1}{\mathrm{Pr}}\nabla T - T\mathbf{u}) \end{align} |Note| |----| |We denote integrating inner products over the domain as $(v,u) = \int_\Omega v u d \mathbf{x}$ or $(\mathbf{v},\mathbf{u}) = \int_\Omega \mathbf{v} \cdot \mathbf{u} d \mathbf{x}$.| By default FEniCS will numerically integrate with an exact quadrature rule. For this particular problem, this yields a large enough number of quadrature points that FEniCS throws a warning. Let's choose a lower degree quadrature, which will greatly speed up the finite element matrix assembly. End of explanation inner, dot, grad, div, sym = \ fenics.inner, fenics.dot, fenics.grad, fenics.div, fenics.sym mass = -psi_p*div(u) momentum = dot(psi_u, u_t + dot(grad(u), u) + f_B) - div(psi_u)*p \ + 2.*mu(phi(T))*inner(sym(grad(psi_u)), sym(grad(u))) enthalpy = psi_T*(T_t - 1./Ste*phi_t) + dot(grad(psi_T), 1./Pr*grad(T) - T*u) F = (mass + momentum + enthalpy)*dx Explanation: Define the nonlinear variational form $\mathcal{F}$. End of explanation penalty_stabilization_parameter = 1.e-7 gamma = fenics.Constant(penalty_stabilization_parameter) F += -psi_p*gamma*p*dx Explanation: We add a penalty method stabilization term $-\gamma(\psi_p,p)$, setting the stabilization parameter $\gamma = 10^{-7}$ as done in [5]. |Note| |----| |One can solve the incompressible Navier-Stokes equation either with P2P1 elements, or with the penalty method and P1P1 elements. Neither of these approaches works alone when also coupling the temperature convection-diffusion equation with Boussinesq buoyancy; but applying both stabilization methods together does work.| End of explanation JF = fenics.derivative(F, w, fenics.TrialFunction(W)) Explanation: Linearization Notice that $\mathcal{F}$ is a nonlinear variational form. FEniCS will solve the nonlinear problem using Newton's method. This requires computing the Jacobian (formally the Gâteaux derivative) of the nonlinear variational form, yielding a a sequence of linearized problems whose solutions may converge to approximate the nonlinear solution. We could manually define the Jacobian; but thankfully FEniCS can do this for us. |Note| |----| |When solving linear variational problems in FEniCS, one defines the linear variational form using fenics.TrialFunction instead of fenics.Function (while both approaches will need fenics.TestFunction). When solving nonlinear variational problems with FEniCS, we only need fenics.TrialFunction to define the linearized problem, since it is the linearized problem which will be assembled into a linear system and solved.| End of explanation hot_wall = "near(x[0], 0.)" cold_wall = "near(x[0], 1.)" adiabatic_walls = "near(x[1], 0.) | near(x[1], 1.)" walls = hot_wall + " | " + cold_wall + " | " + adiabatic_walls Explanation: Boundary conditions We need boundary conditions before we can define a nonlinear variational problem (i.e. in this case a boundary value problem). We physically consider no slip velocity boundary conditions for all boundaries. These manifest as homogeneous Dirichlet boundary conditions. For the temperature boundary conditions, we consider a constant hot temperature on the left wall, a constant cold temperature on the right wall, and adiabatic (i.e. zero heat transfer) conditions on the top and bottom walls. Because the problem's geometry is simple, we can identify the boundaries with the following piece-wise function. \begin{align} T(\mathbf{x}) &= \begin{cases} T_h , && x_0 = 0 \ T_c , && x_0 = 1 \end{cases} \end{align} End of explanation W_u = W.sub(1) W_T = W.sub(2) boundary_conditions = [ fenics.DirichletBC(W_u, (0., 0.), walls), fenics.DirichletBC(W_T, hot_wall_temperature, hot_wall), fenics.DirichletBC(W_T, cold_wall_temperature, cold_wall)] Explanation: Define the boundary conditions on the appropriate subspaces. End of explanation problem = fenics.NonlinearVariationalProblem(F, w, boundary_conditions, JF) Explanation: Nonlinear variational problem Now we have everything we need to define the variational problem. End of explanation M = phi_t*dx Explanation: Goal-oriented adaptive mesh refinement (AMR) We wish to solve the problem with adaptive mesh refinement (AMR). For this it helps to explain that we have already defined the discrete nonlinear variational problem using FEniCS: Find $\mathbf{w}_h \in \mathbf{W}_h \subset \mathbf{W}(\Omega)$ such that \begin{align} \mathcal{F}(\boldsymbol{\psi}_h;\mathbf{w}_h) = 0 \quad \forall \boldsymbol{\psi}_h \in \mathbf{W}_h \subset \mathbf{W} \end{align} Given this, goal-oriented AMR poses the problem: Find $\mathbf{W}_h \subset \mathbf{W}(\Omega)$ and $\mathbf{w}_h \in \mathbf{W}_h$ such that \begin{align} \left| M(\mathbf{w}) - M(\mathbf{w}_h) \right| < \epsilon_M \end{align} where $M$ is some goal functional of the solution which we integrate over the domain, and where $\epsilon_M$ is a prescribed tolerance. Note that since we do not know the exact solution $\mathbf{w}$, this method requires an error estimator. This is detailed in [2]. For our purposes, we only need to define $M$ and $\epsilon_M$. We choose a goal analagous to the melting rate. \begin{align} M = \int_\Omega \phi_t \hspace{1mm} d\mathbf{x} \end{align} End of explanation epsilon_M = 4.e-5 Explanation: Let's set the tolerance somewhat arbitrarily. For real problems of scientific or engineering interest, one might have accuracy requirements which could help drive this decision. End of explanation solver = fenics.AdaptiveNonlinearVariationalSolver(problem, M) Explanation: The benchmark solution Finally we instantiate the adaptive solver with our problem and goal End of explanation w.leaf_node().vector()[:] = w_n.leaf_node().vector() Explanation: set the Newton solver's initial guess based on the initial values End of explanation solver.solve(epsilon_M) Explanation: and solve the problem to the prescribed tolerance. End of explanation def plot(w): p, u, T = fenics.split(w.leaf_node()) fenics.plot(phi(T)) matplotlib.pyplot.title("Solid volume fraction") matplotlib.pyplot.xlabel("$x$") matplotlib.pyplot.ylabel("$y$") matplotlib.pyplot.show() fenics.plot(u) matplotlib.pyplot.title("Velocity vector field") matplotlib.pyplot.xlabel("$x$") matplotlib.pyplot.ylabel("$y$") matplotlib.pyplot.show() fenics.plot(mesh.leaf_node()) matplotlib.pyplot.title("Adapted mesh") matplotlib.pyplot.xlabel("$x$") matplotlib.pyplot.ylabel("$y$") matplotlib.pyplot.show() plot(w) Explanation: |Note| |----| |solver.solve will modify the solution w, which means that u and p will also be modified.| Now plot the solid volume fraction, velocity field, and adapted mesh. End of explanation for timestep in range(5): w_n.leaf_node().vector()[:] = w.leaf_node().vector() solver.solve(epsilon_M) plot(w) Explanation: Let's run a few more time steps. End of explanation
7,345
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Collaborative-Filtering-for-Implicit-Feedback-Datasets" data-toc-modified-id="Collaborative-Filtering-for-Implicit-Feedback-Datasets-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Collaborative Filtering for Implicit Feedback Datasets</a></span><ul class="toc-item"><li><span><a href="#Formulation" data-toc-modified-id="Formulation-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Formulation</a></span></li><li><span><a href="#Alternating-Least-Squares" data-toc-modified-id="Alternating-Least-Squares-1.2"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Alternating Least Squares</a></span></li><li><span><a href="#Implementation" data-toc-modified-id="Implementation-1.3"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>Implementation</a></span></li></ul></li><li><span><a href="#Ranking-Metrics" data-toc-modified-id="Ranking-Metrics-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Ranking Metrics</a></span><ul class="toc-item"><li><span><a href="#Mean-Average-Precision" data-toc-modified-id="Mean-Average-Precision-2.1"><span class="toc-item-num">2.1&nbsp;&nbsp;</span>Mean Average Precision</a></span></li><li><span><a href="#NDCG" data-toc-modified-id="NDCG-2.2"><span class="toc-item-num">2.2&nbsp;&nbsp;</span>NDCG</a></span></li></ul></li><li><span><a href="#Reference" data-toc-modified-id="Reference-3"><span class="toc-item-num">3&nbsp;&nbsp;</span>Reference</a></span></li></ul></div> Step2: Collaborative Filtering for Implicit Feedback Datasets One common scenario in real-world recommendation system is we only have implicit instead of explicit user-item interaction data. To elaborate on this a little bit more, a user may be searching for an item on the web, or listening to songs. Unlike a rating data, where we have direct access to the user's preference towards an item, these type of actions do not explicitly state or quantify any preference of the user for the item, but instead gives us implicit confidence about the user's opinion. Even when we do have explicit data, it might still be a good idea to incorporate implicit data into the model. Consider, for example, listening to songs. When users listen to music on a streaming service, they might rarely ever rate a song that he/she like or dislike. But more often they skip a song, or listen only halfway through it if they dislike it. If the user really liked a song, they will often come back and listen to it. So, to infer a user's musical taste profile, their listens, repeat listens, skips and fraction of tracks listened to, etc. might be far more valuable signals than explicit ratings. Formulation Recall from the previous notebook that the loss function for training the recommendation model on explicit feedback data was Step4: The following train and test set split function is assuming that you're doing a train/test split using the current dataset. Though it's probably better to use time to perform the train/test split. For example, using the year 2016's data as training and the 1 first month of 2017's data as testing. Step5: The following implementation uses some tricks to speed up the procedure. First of all, when we need to solve $Ax = b$ where $A$ is an $n \times n$ matrix, a lot of books might write the solution as $x = A^{-1} b$, however, in practice there is hardly ever a good reason to calculate that it that way as solving the equation $Ax = b$ is faster than finding $A^{-1}$. The next one is the idea of computing matrix product $X^T X$ using a outer product of each row. Step11: The reason why this can speed things up is that the matrix product is now the sum of the outer products of the rows, where each row's computation is independent of another can be computed in the parallelized fashion then added back together! Last but not least, is exploiting the property of scipy's Compressed Sparse Row Matrix to access the non-zero elements. For those that are unfamiliar with it, the following link has a pretty decent quick introduction. Blog Step13: Ranking Metrics Now that we've built our recommendation engine, the next important thing to do is to evaluate our model's offline performance. Let's say that there are some users and some items, like movies, songs or jobs. Each user might be interested in some items. The client asks us to recommend a few items (the number is x) for each user. In other words, what we're after is the top-N recommendation for each user and after recommending these items to the user, we need a way to measure whether the recommendation is useful or not. One key thing to note is that metrics such as RMSE might not be the best at assessing the quality of recommendations because the training focused on items with the most ratings, achieving a good fit for those. The items with few ratings don't mean much in terms of their impact on the loss. As a result, predictions for them will be off. Long story short, we need metrics specifically crafted for ranking evaluation and the two most popular ranking metrics are MAP (Mean Average Precision) and NDCG (Normalized Discounted Cumulative Gain). The main difference between the two is that MAP assumes binary relevance (an item is either of interest or not, e.g. a user clicked a link, watched a video, purchased a product), while NDCG can be used in any case where we can assign relevance score to a recommended item (binary, integer or real). The relationship is just like classification and regression. Mean Average Precision For this section of the content, a large portion is based on the excellent blog post at the following link. Blog Step15: After computing the average precision for this individual user, we then compute this for every single user and take the mean of these values, then that would essentially be our MAP@k, mean average precision at k. For this metric, the bigger the better. Step17: Note that it's normal for this metric to be low. We can compare this metric with a baseline to get a sense of how well the algorithm is performing. And a nice baseline for recommendation engine is to simply recommend every user the most popular items (items that has the most user interaction) NDCG Suppose that on a four-point scale, we give a 0 score for an irrelevant result, 1 for a partially relevant, 2 for relevant, and 3 for perfect. Suppose also that a query is judged by one of our judges, and the first four results that the search engine returns are assessed as relevant (2), irrelevant (0), perfect (3), and relevant (2) by a judge. The idea behind NDCG is Step19: There's an alternative formulation of DCG that places stronger emphasis on retrieving relevant documents Step21: The final touch to this metric is Normalized (N). It's not fair to compare DCG values across queries because some queries are easier than others or result lists vary in length depending on the query, so we normalize them by Step25: The next section modifies the function API a little bit so it becomes more suitable for evaluating the recommendation engine.
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', 'notebook_format')) from formats import load_style load_style(css_style = 'custom2.css', plot_style = False) os.chdir(path) # 1. magic to print version # 2. magic so that the notebook will reload external python modules %load_ext watermark %load_ext autoreload %autoreload 2 import numpy as np import pandas as pd from math import ceil from tqdm import trange from subprocess import call from scipy.sparse import csr_matrix, dok_matrix %watermark -a 'Ethen' -d -t -v -p numpy,pandas,sklearn,tqdm,scipy Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Collaborative-Filtering-for-Implicit-Feedback-Datasets" data-toc-modified-id="Collaborative-Filtering-for-Implicit-Feedback-Datasets-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Collaborative Filtering for Implicit Feedback Datasets</a></span><ul class="toc-item"><li><span><a href="#Formulation" data-toc-modified-id="Formulation-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Formulation</a></span></li><li><span><a href="#Alternating-Least-Squares" data-toc-modified-id="Alternating-Least-Squares-1.2"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Alternating Least Squares</a></span></li><li><span><a href="#Implementation" data-toc-modified-id="Implementation-1.3"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>Implementation</a></span></li></ul></li><li><span><a href="#Ranking-Metrics" data-toc-modified-id="Ranking-Metrics-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Ranking Metrics</a></span><ul class="toc-item"><li><span><a href="#Mean-Average-Precision" data-toc-modified-id="Mean-Average-Precision-2.1"><span class="toc-item-num">2.1&nbsp;&nbsp;</span>Mean Average Precision</a></span></li><li><span><a href="#NDCG" data-toc-modified-id="NDCG-2.2"><span class="toc-item-num">2.2&nbsp;&nbsp;</span>NDCG</a></span></li></ul></li><li><span><a href="#Reference" data-toc-modified-id="Reference-3"><span class="toc-item-num">3&nbsp;&nbsp;</span>Reference</a></span></li></ul></div> End of explanation file_dir = 'ml-100k' file_path = os.path.join(file_dir, 'u.data') if not os.path.isdir(file_dir): call(['curl', '-O', 'http://files.grouplens.org/datasets/movielens/' + file_dir + '.zip']) call(['unzip', file_dir + '.zip']) names = ['user_id', 'item_id', 'rating', 'timestamp'] df = pd.read_csv(file_path, sep = '\t', names = names) print('data dimension: \n', df.shape) df.head() def create_matrix(data, user_col, item_col, rating_col): creates the sparse user-item interaction matrix Parameters ---------- data : DataFrame implicit rating data user_col : str user column name item_col : str item column name ratings_col : str implicit rating column name Returns ------- ratings : scipy sparse csr_matrix [n_users, n_items] user/item ratings matrix data : DataFrame the implict rating data that retains only the positive feedback (if specified to do so) # map each item and user to a unique numeric value for col in (item_col, user_col): data[col] = data[col].astype('category') # create a sparse matrix of using the (rating, (rows, cols)) format rows = data[user_col].cat.codes cols = data[item_col].cat.codes rating = data[rating_col] ratings = csr_matrix((rating, (rows, cols))) ratings.eliminate_zeros() return ratings, data user_col = 'user_id' item_col = 'item_id' rating_col = 'rating' X, df = create_matrix(df, user_col, item_col, rating_col) X Explanation: Collaborative Filtering for Implicit Feedback Datasets One common scenario in real-world recommendation system is we only have implicit instead of explicit user-item interaction data. To elaborate on this a little bit more, a user may be searching for an item on the web, or listening to songs. Unlike a rating data, where we have direct access to the user's preference towards an item, these type of actions do not explicitly state or quantify any preference of the user for the item, but instead gives us implicit confidence about the user's opinion. Even when we do have explicit data, it might still be a good idea to incorporate implicit data into the model. Consider, for example, listening to songs. When users listen to music on a streaming service, they might rarely ever rate a song that he/she like or dislike. But more often they skip a song, or listen only halfway through it if they dislike it. If the user really liked a song, they will often come back and listen to it. So, to infer a user's musical taste profile, their listens, repeat listens, skips and fraction of tracks listened to, etc. might be far more valuable signals than explicit ratings. Formulation Recall from the previous notebook that the loss function for training the recommendation model on explicit feedback data was: $$ \begin{align} L_{explicit} &= \sum\limits_{u,i \in S}( r_{ui} - x_{u} y_{i}^{T} )^{2} + \lambda \big( \sum\limits_{u} \left\Vert x_{u} \right\Vert^{2} + \sum\limits_{i} \left\Vert y_{i} \right\Vert^{2} \big) \end{align} $$ Where: $r_{ui}$ is the true rating given by user $u$ to the item $i$ $x_u$ and $y_i$ are user u's and item i's latent factors, both are $1×d$ dimensional, where $d$ the number of latent factors that the user can specify $S$ was the set of all user-item ratings $\lambda$ controls the regularization strength that prevents overfitting the user and item vectors To keep it concrete, let's assume we're working music data and the value of our $r_{ui}$ will consists of implicit ratings that counts the number of times a user has listened to a song (song listen count). Then new formulation becomes: $$ \begin{align} L_{implicit} &= \sum\limits_{u,i} c_{ui}( p_{ui} - x_{u} y_{i}^{T} )^2 + \lambda \big( \sum\limits_{u} \left\Vert x_{u} \right\Vert^{2} + \sum\limits_{i} \left\Vert y_{i} \right\Vert^{2} \big) \end{align} $$ Recall that with implicit feedback, we do not have ratings anymore; rather, we have users' preferences for items. Therefore, in the new loss function, the ratings $r_{ui}$ has been replaced with a preference $p_{ui}$ indicating the preference of user $u$ to item $i$. $p_{ui}$ is a set of binary variables and is computed by binarizing $r_{ui}$. $$ \begin{align} p_{ui} &= \begin{cases} 1 &\mbox{if } r_{ui} > 0 \ 0 & \mbox{otherwise} \end{cases} \end{align} $$ We make the assumption that if a user has interacted at all with an item ($r_{ui} > 0$), then we set $p_{ui} = 1$ to indicate that user $u$ has a liking/preference for item $i$. Otherwise, we set $p_{ui} = 0$. However, these assumptions comes with varying degrees of confidence. First of all, when $p_{ui} = 0$, we assume that it should be associated with a lower confidence, as there are many reasons beyond disliking the item as to why the user has not interacted with it. e.g. Unaware of it's existence. On the other hand, as the number of implicit feedback, $r_{ui}$, grows, we have a stronger indication that the user does indeed like the item (regardless of whether he/she if buying a gift for someone else). So to measure the level of confidence mentioned above, we introduce another set of variables $c_{ui}$ that measures our confidence in observing $p_{ui}$: $$ \begin{align} c_{ui} = 1 + \alpha r_{ui} \end{align} $$ Where the 1 ensures we have some minimal confidence for every user-item pair, and as we observe more and more implicit feedback (as $r_{ui}$ gets larger and larger), our confidence in $p_{ui} = 1$ increases accordingly. The term $\alpha$ is a parameter that we have to specify to control the rate of the increase. This formulation makes intuitive sense when we look back at the $c_{ui}( p_{ui} - x_{u} y_{i}^{T} )^2$ term in the loss function. A larger $c_{ui}$ means that the prediction $x_{u} y_{i}^{T}$ has to be that much closer to $p_{ui}$ so that term will not contribute too much to the total loss. The implementation in the later section will be based on the formula above, but note that there are many ways in which we can tune the formulation above. For example, we can derive $p_{ui}$ from $r_{ui}$ differently. So instead of setting the binary cutoff at 0, we can set it at another threshold that we feel is appropriate for the domain. Similarly, there are many ways to transform $r_{ui}$ into the confidence level $c_{ui}$. e.g. we can use: $$ \begin{align} c_{ui} = 1 + \alpha log \left( 1 + r_{ui} / \epsilon \right) \end{align} $$ Regardless of the scheme, it's important to realize that we are transforming the raw observation $r_{ui}$ into two distinct representation, the preference $p_{ui}$ and the confidence levels of the preference $c_{ui}$. Alternating Least Squares Let's assume we have $m$ users and $n$ items. Now, to solve for the loss function above, we start by treating $y_i$ as constant and solve the loss function with respect to $x_u$. To do this, we rewrite and expand the first term in the loss function (excluding the regularization terms), $\sum\limits_{u,i} c_{ui}( p_{ui} - x_{u} y_{i}^{T} )^2$ part as: $$ \begin{align} \sum\limits_{u,i} c_{ui}( p_{ui} - x_{u} y_{i}^{T} )^2 &= \sum_u c_u( p_u^T - x_u Y^T )^2 \ &= \sum_u p_u^T C^u p_u - 2 x_u Y^T C^u p_u + x_u Y^T C^u Y x_u^T \end{align} $$ Where: $Y \in \mathbb{R}^{n \times d}$ represents all item row vectors vertically stacked on each other $p_u \in \mathbb{R^{n \times 1}}$ contains element all of the preferences of the user The diagonal matrix $C^u \in \mathbb{R^{n \times n}}$ consists of $c_{ui}$ in row/column $i$, which is the user's confidence across all the items. e.g. if $u = 0$ then the matrix for user $u_0$ will look like: $$ \begin{align} {C}^{u_0} = \begin{bmatrix} c_{u_{01}} & 0 & 0 & 0 & ... & 0 \ 0 & c_{u_{02}} & 0 & 0 & ... &0\ ... \ ... \ 0 & 0 & 0 & 0 & ... & c_{u_{0n}}\end{bmatrix} \end{align} $$ The formula above can also be used to monitor the loss function at each iteration. If we set $A = Y^T C^u Y$ and $b = Y^T C^u$, the last two terms can be rewritten as $(A x_u^T - 2b p_u) x_u$. As for the first term $p_u^T C^u p_u$ we can leverage the fact that $p_u$ is 1 for all positive items, and just sum the confidence term $C^u$. Now for the derivation of the partial derivative. $$ \begin{align} \frac{\partial L_{implicit}}{\partial x_u} &= -2 Y^T C^u p_u + 2 Y^T C^u Y x_u + 2 \lambda x_u = 0 \ &= (Y^T C^u Y + \lambda I)x_u = Y^T C^u p_{u} \ &= x_u = (Y^T C^u Y + \lambda I)^{-1} Y^T C^u p_u \end{align} $$ The main computational bottleneck in the expression above is the need to compute $Y^T C^u Y$ for every user. Speedup can be obtained by re-writing the expression as: $$ \begin{align} {Y}^T {C}^{u} {Y} &= Y^T Y + {Y}^T \left( C^u - I \right) Y \end{align} $$ Now the term $Y^T Y$ becomes independent of each user and can be computed independently, next notice $\left(C^u - I \right)$ has only $n_u$ non-zero elements, where $n_u$ is the number of items for which $r_{ui} > 0$. Similarly, $C^u p_u$ contains only $n_u$ non-zero elements since $p_u$ is a binary transformation of $r_{ui}$. Thus the final formulation becomes: $$ \begin{align} \frac{\partial L_{implicit}}{\partial x_u} &= x_u = (Y^T Y + Y^T \left( C^u - I \right) Y + \lambda I)^{-1} Y^T C^u p_u \end{align} $$ After solving for $x_u$ the same procedure can be carried out to solve for $y_i$ giving a similar expression: $$ \begin{align} \frac{\partial L_{implicit}}{\partial y_i} &= y_i = (X^T X + X^T \left( C^i - I \right) X + \lambda I)^{-1} X^T C^i p_i \end{align} $$ Implementation We'll use the same movielens dataset like the previous notebook. The movielens data is not an implicit feedback dataset as the user did provide explicit ratings, but we will use it for now to test out our implementation. The overall preprocessing procedure of loading the data and doing the train/test split is the same as the previous notebook. But here we'll do it in a sparse matrix fashion. End of explanation def create_train_test(ratings, test_size = 0.2, seed = 1234): split the user-item interactions matrix into train and test set by removing some of the interactions from every user and pretend that we never seen them Parameters ---------- ratings : scipy sparse csr_matrix The user-item interactions matrix test_size : float between 0.0 and 1.0, default 0.2 Proportion of the user-item interactions for each user in the dataset to move to the test set; e.g. if set to 0.2 and a user has 10 interactions, then 2 will be moved to the test set seed : int, default 1234 Seed for reproducible random splitting the data into train/test set Returns ------- train : scipy sparse csr_matrix Training set test : scipy sparse csr_matrix Test set assert test_size < 1.0 and test_size > 0.0 # Dictionary Of Keys based sparse matrix is more efficient # for constructing sparse matrices incrementally compared with csr_matrix train = ratings.copy().todok() test = dok_matrix(train.shape) # 1. for all the users assign randomly chosen interactions # to the test and assign those interactions to zero in the training; # when computing the interactions to go into the test set, # remember to round up the numbers (e.g. a user has 4 ratings, if the # test_size is 0.2, then 0.8 ratings will go to test, thus we need to # round up to ensure the test set gets at least 1 rating); # 2. note that we can easily the parallelize the for loop if we were to # aim for a more efficient implementation rstate = np.random.RandomState(seed) for u in range(ratings.shape[0]): split_index = ratings[u].indices n_splits = ceil(test_size * split_index.shape[0]) test_index = rstate.choice(split_index, size = n_splits, replace = False) test[u, test_index] = ratings[u, test_index] train[u, test_index] = 0 train, test = train.tocsr(), test.tocsr() return train, test seed = 1234 test_size = 0.2 X_train, X_test = create_train_test(X, test_size, seed) X_train Explanation: The following train and test set split function is assuming that you're doing a train/test split using the current dataset. Though it's probably better to use time to perform the train/test split. For example, using the year 2016's data as training and the 1 first month of 2017's data as testing. End of explanation # example matrix X = np.array([[9, 3, 5], [4, 1, 2]]).T X # normal matrix product X.T.dot(X) # intialize an empty array end_result = np.zeros((2, 2)) # loop through each row add up the outer product for i in range(X.shape[0]): out = np.outer(X[i], X[i]) end_result += out print('row:\n', X[i]) print('outer product of row:\n', out) end_result Explanation: The following implementation uses some tricks to speed up the procedure. First of all, when we need to solve $Ax = b$ where $A$ is an $n \times n$ matrix, a lot of books might write the solution as $x = A^{-1} b$, however, in practice there is hardly ever a good reason to calculate that it that way as solving the equation $Ax = b$ is faster than finding $A^{-1}$. The next one is the idea of computing matrix product $X^T X$ using a outer product of each row. End of explanation class ALSWR: Alternating Least Squares with Weighted Regularization for implicit feedback Parameters ---------- n_iters : int number of iterations to train the algorithm n_factors : int number/dimension of user and item latent factors alpha : int scaling factor that indicates the level of confidence in preference reg : int regularization term for the user and item latent factors seed : int seed for the randomly initialized user, item latent factors Reference --------- Y. Hu, Y. Koren, C. Volinsky Collaborative Filtering for Implicit Feedback Datasets http://yifanhu.net/PUB/cf.pdf def __init__(self, n_iters, n_factors, alpha, reg, seed): self.reg = reg self.seed = seed self.alpha = alpha self.n_iters = n_iters self.n_factors = n_factors def fit(self, ratings): ratings : scipy sparse csr_matrix [n_users, n_items] sparse matrix of user-item interactions # the original confidence vectors should include a + 1, # but this direct addition is not allowed when using sparse matrix, # thus we'll have to deal with this later in the computation Cui = ratings.copy().tocsr() Cui.data *= self.alpha Ciu = Cui.T.tocsr() self.n_users, self.n_items = Cui.shape # initialize user latent factors and item latent factors # randomly with a specified set seed rstate = np.random.RandomState(self.seed) self.user_factors = rstate.normal(size = (self.n_users, self.n_factors)) self.item_factors = rstate.normal(size = (self.n_items, self.n_factors)) for _ in trange(self.n_iters, desc = 'training progress'): self._als_step(Cui, self.user_factors, self.item_factors) self._als_step(Ciu, self.item_factors, self.user_factors) return self def _als_step(self, Cui, X, Y): when solving the user latent vectors, the item vectors will be fixed and vice versa # the variable name follows the notation when holding # the item vector Y constant and solving for user vector X # YtY is a d * d matrix that is computed # independently of each user YtY = Y.T.dot(Y) data = Cui.data indptr, indices = Cui.indptr, Cui.indices # for every user build up A and b then solve for Ax = b, # this for loop is the bottleneck and can be easily parallized # as each users' computation is independent of one another for u in range(self.n_users): # initialize a new A and b for every user b = np.zeros(self.n_factors) A = YtY + self.reg * np.eye(self.n_factors) for index in range(indptr[u], indptr[u + 1]): # indices[index] stores non-zero positions for a given row # data[index] stores corresponding confidence, # we also add 1 to the confidence, since we did not # do it in the beginning, when we were to give every # user-item pair and minimal confidence i = indices[index] confidence = data[index] + 1 factor = Y[i] # for b, Y^T C^u p_u # there should be a times 1 for the preference # Pui = 1 # b += confidence * Y[i] * Pui # but the times 1 can be dropped b += confidence * factor # for A, Y^T (C^u - I) Y A += (confidence - 1) * np.outer(factor, factor) X[u] = np.linalg.solve(A, b) return self def predict(self): predict ratings for every user and item prediction = self.user_factors.dot(self.item_factors.T) return prediction def _predict_user(self, user): returns the predicted ratings for the specified user, this is mainly used in computing evaluation metric user_pred = self.user_factors[user].dot(self.item_factors.T) return user_pred als = ALSWR(n_iters = 15, n_factors = 20, alpha = 15, reg = 0.01, seed = 1234) als.fit(X_train) Explanation: The reason why this can speed things up is that the matrix product is now the sum of the outer products of the rows, where each row's computation is independent of another can be computed in the parallelized fashion then added back together! Last but not least, is exploiting the property of scipy's Compressed Sparse Row Matrix to access the non-zero elements. For those that are unfamiliar with it, the following link has a pretty decent quick introduction. Blog: Empty rows in sparse arrays. End of explanation def compute_apk(y_true, y_pred, k): average precision at k, y_pred is assumed to be truncated to length k prior to feeding it to the function # convert to set since membership # testing in a set is vastly faster actual = set(y_true) # precision at i is a percentage of correct # items among first i recommendations; the # correct count will be summed up by n_hit n_hit = 0 precision = 0 for i, p in enumerate(y_pred, 1): if p in actual: n_hit += 1 precision += n_hit / i # divide by recall at the very end avg_precision = precision / min(len(actual), k) return avg_precision # example 1 # y_true, is the true interaction of a user # and y_pred is the recommendation we decided # to give to the user k = 2 y_true = np.array([1, 2, 3, 4, 5]) y_pred = np.array([6, 4, 7, 1, 2]) compute_apk(y_true, y_pred[:k], k) # 0.25 # example 2 k = 5 y_true = np.array([1, 2]) y_pred = np.array([6, 4, 7, 1, 2]) compute_apk(y_true, y_pred[:k], k) # 0.325 Explanation: Ranking Metrics Now that we've built our recommendation engine, the next important thing to do is to evaluate our model's offline performance. Let's say that there are some users and some items, like movies, songs or jobs. Each user might be interested in some items. The client asks us to recommend a few items (the number is x) for each user. In other words, what we're after is the top-N recommendation for each user and after recommending these items to the user, we need a way to measure whether the recommendation is useful or not. One key thing to note is that metrics such as RMSE might not be the best at assessing the quality of recommendations because the training focused on items with the most ratings, achieving a good fit for those. The items with few ratings don't mean much in terms of their impact on the loss. As a result, predictions for them will be off. Long story short, we need metrics specifically crafted for ranking evaluation and the two most popular ranking metrics are MAP (Mean Average Precision) and NDCG (Normalized Discounted Cumulative Gain). The main difference between the two is that MAP assumes binary relevance (an item is either of interest or not, e.g. a user clicked a link, watched a video, purchased a product), while NDCG can be used in any case where we can assign relevance score to a recommended item (binary, integer or real). The relationship is just like classification and regression. Mean Average Precision For this section of the content, a large portion is based on the excellent blog post at the following link. Blog: What you wanted to know about Mean Average Precision. This documentation builds on top of it by carrying out the educational implementation. Let's say that there are some users and some items, like movies, songs or jobs. Each user might be interested in some items. The client asks us to recommend a few items (the number is x) for each user. After recommending the items to the user, we need a way to measure whether the recommendation is useful or not. One way to do this is using MAP@k (Mean Average Precision at k) . The intuition behind this evaluation metric is that: We can recommend at most k items for each user (this is essentially the @k part), but we will be penalized for bad recommendations Order matters, so it's better to submit more certain recommendations first, followed by recommendations we are less sure about Diving a bit deeper, we will first ignore @k and get M out of the way. MAP is just the mean of APs, or average precision, for all users. If we have 1000 users, we sum APs for each user and divide the sum by 1000. This is MAP. So now, what is AP, or average precision? One way to understand average precision is this way: we type something in Google and it shows us 10 results. It's probably best if all of them were relevant. If only some are relevant, say five of them, then it's much better if the relevant ones are shown first. It would be bad if first five were irrelevant and good ones only started from sixth, wouldn't it? The formula for computing AP is: sum i=1:k of (precision at i * change in recall at i) Where precision at i is a percentage of correct items among first i recommendations. Change in recall is 1/k if item at i is correct (for every correct item), otherwise zero. Note that this is base on the assumption that the number of relevant items is bigger or equal to k: r >= k. If not, change in recall is 1/r for each correct i instead of 1/k. For example, If the actual items were [1 2 3 4 5] and we recommend [6 4 7 1 2]. In this case we get 4, 1 and 2 right, but with some incorrect guesses in between. Now let's say we were to compute AP@2, so only two first predictions matter: 6 and 4. First is wrong, so precision@1 is 0. Second is right, so precision@2 is 0.5. Change in recall is 0 and 0.5 (that's 1/k) respectively, so AP@2 = 0 * 0 + 0.5 * 0.5 = 0.25 End of explanation def mapk_score(model, ratings, k): mean average precision at rank k for the ALS model Parameters ---------- model : ALSWR instance fitted ALSWR model ratings : scipy sparse csr_matrix [n_users, n_items] sparse matrix of user-item interactions k : int mean average precision at k's k Returns ------- mapk : float the mean average precision at k's score # compare the top k predictions' index to the actual index, # the model is assumed to have the _predict_user method mapk = 0 n_users = ratings.shape[0] for u in range(n_users): y_true = ratings[u].indices u_pred = model._predict_user(u) y_pred = np.argsort(u_pred)[::-1][:k] mapk += compute_apk(y_true, y_pred, k) mapk /= n_users return mapk k = 5 mapk_train = mapk_score(als, X_train, k) mapk_test = mapk_score(als, X_test, k) print('mapk training:', mapk_train) print('mapk testing:', mapk_test) Explanation: After computing the average precision for this individual user, we then compute this for every single user and take the mean of these values, then that would essentially be our MAP@k, mean average precision at k. For this metric, the bigger the better. End of explanation def dcg_at_k(score, k = None): discounted cumulative gain (dcg) Parameters ---------- score : 1d nd.array ranking/relevance score k : int, default None evaluate the measure for the top-k ranking score, default None evaluates all Returns ------- dcg: float if k is not None: score = score[:k] discounts = np.log2(np.arange(2, score.size + 2)) dcg = np.sum(score / discounts) return dcg score = np.array([2, 0, 3, 2]) dcg_at_k(score) Explanation: Note that it's normal for this metric to be low. We can compare this metric with a baseline to get a sense of how well the algorithm is performing. And a nice baseline for recommendation engine is to simply recommend every user the most popular items (items that has the most user interaction) NDCG Suppose that on a four-point scale, we give a 0 score for an irrelevant result, 1 for a partially relevant, 2 for relevant, and 3 for perfect. Suppose also that a query is judged by one of our judges, and the first four results that the search engine returns are assessed as relevant (2), irrelevant (0), perfect (3), and relevant (2) by a judge. The idea behind NDCG is: A recommender returns some items and we'd like to compute how good the list is. Each item has a relevance score, usually a non-negative number. That's gain (G). For items we don't have user feedback for we usually set the gain to zero. Now we add up those scores, that's cumulative gain (CG). So, the cumulative gain for the four results is the sum of the scores for each result: 2 + 0 + 3 + 2 = 7. In mathematical notations, the CG at a particular rank ${\displaystyle k}$ is defined as: \begin{align} CG_k = \sum_{i=1}^k rel_i \end{align} Where $rel_i$ is the graded relevance of the result at position ${\displaystyle i}$. As we can see from the formula, the value computed with this function is unaffected by changes in the ordering of search results, thus DCG is used in place of CG for a more accurate measure about the usefulness of results' ranking. When evaluating rankings, we’d prefer to see the most relevant items at the top of the list, i.e the first result in our search results is more important than the second, the second more important than the third, and so on. Therefore before summing the scores we divide each by a growing number, which is the discount (D). One simple way to make position one more important than two (and so on) is to divide each score by the rank. So, for example, if the third result is "great", its contribution is $3 / 3 = 1$ (since the score for "great" is 3 , and the rank of the result is 3). If "great" were the first result, its contribution would be 3 / 1 = 3. Though in practice, it's more common to discount it using a logarithm of the item position, giving us: \begin{align} DCG_k = \sum_{i=1}^k \frac{rel_i}{\log_2{\left(i+1\right)}} \end{align} End of explanation def dcg_at_k(score, k = None): discounted cumulative gain (dcg) Parameters ---------- score : 1d nd.array ranking/relevance score k : int, default None evaluate the measure for the top-k ranking score, default None evaluates all Returns ------- dcg: float if k is not None: score = score[:k] gain = 2 ** score - 1 discounts = np.log2(np.arange(2, score.size + 2)) dcg = np.sum(gain / discounts) return dcg score = np.array([2, 0, 3, 2]) dcg_at_k(score) Explanation: There's an alternative formulation of DCG that places stronger emphasis on retrieving relevant documents: \begin{align} DCG_k = \sum_{i=1}^k \frac{2^{rel_i} - 1}{\log_2{\left(i+1\right)}} \end{align} This formula is commonly used in industry including major web search companies and data science competition platform such as Kaggle. End of explanation def ndcg_at_k(score, k = None): normalized discounted cumulative gain (ndcg) Parameters ---------- score : 1d nd.array ranking/relevance score k : int, default None evaluate the measure for the top-k ranking score, default None evaluates all Returns ------- ndcg: float, 0.0 ~ 1.0 actual_dcg = dcg_at_k(score, k) sorted_score = np.sort(score)[::-1] best_dcg = dcg_at_k(sorted_score, k) ndcg = actual_dcg / best_dcg return ndcg ndcg_at_k(score) Explanation: The final touch to this metric is Normalized (N). It's not fair to compare DCG values across queries because some queries are easier than others or result lists vary in length depending on the query, so we normalize them by: First, figure out what the best ranking score is for this result and compute DCG for that, then we divide the raw DCG by this ideal DCG to get NDCG@K, a number between 0 and 1. In our previous example, we had 2, then 0, 3, and a 2. The best arrangement of these same results would have been: 3, 2, 2, 0, that is, if the "great" result had been ranked first, followed by the two "relevant" ones, and then the "irrelevant". So we compute the DCG score for the rank 3, 2, 2, 0 to obtain our ideal DCG (IDCG) and simply perform: \begin{align} NDCG_k = \frac{DCG_k}{IDCG_k} \end{align} to obtain our final ndcg. End of explanation def ndcg_score(model, ratings, k): Normalized discounted cumulative gain (NDCG) at rank k for the ALS model; which computes the ndcg score for each users' recommendation and does a simply average Parameters ---------- model : ALSWR instance fitted ALSWR model ratings : scipy sparse csr_matrix [n_users, n_items] sparse matrix of user-item interactions k : int rank k's k Returns ------- avg_ndcg : float ndcg at k's score averaged across all users ndcg = 0.0 n_users, n_items = ratings.shape for u in range(n_users): y_true = np.zeros(n_items) y_true[ratings[u].indices] = 1 u_pred = model._predict_user(u) ndcg += ndcg_at_k(y_true, u_pred, k) avg_ndcg = ndcg / n_users return avg_ndcg def ndcg_at_k(y_true, y_score, k = 10): Normalized discounted cumulative gain (NDCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels) y_score : array-like, shape = [n_samples] Predicted scores k : int Rank Returns ------- ndcg : float, 0.0 ~ 1.0 actual = dcg_at_k(y_true, y_score, k) best = dcg_at_k(y_true, y_true, k) ndcg = actual / best return ndcg def dcg_at_k(y_true, y_score, k = 10): Discounted cumulative gain (DCG) at rank k Parameters ---------- y_true : array-like, shape = [n_samples] Ground truth (true relevance labels) y_score : array-like, shape = [n_samples] Predicted scores k : int Rank Returns ------- dcg : float order = np.argsort(y_score)[::-1] y_true = np.take(y_true, order[:k]) gains = 2 ** y_true - 1 discounts = np.log2(np.arange(2, gains.size + 2)) dcg = np.sum(gains / discounts) return dcg k = 5 ndcg_train = ndcg_score(als, X_train, k) ndcg_test = ndcg_score(als, X_test, k) print('ndcg training:', ndcg_train) print('ndcg testing:', ndcg_test) Explanation: The next section modifies the function API a little bit so it becomes more suitable for evaluating the recommendation engine. End of explanation
7,346
Given the following text description, write Python code to implement the functionality described below step by step Description: 07- Feature Selection by Alejandro Correa Bahnsen version 0.2, May 2016 Part of the class Machine Learning for Security Informatics This notebook is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. Special thanks goes to Kevin Markham Preprocessing & Cross-validation (review) Step1: Removing features with low variance VarianceThreshold is a simple baseline approach to feature selection. It removes all features whose variance doesn’t meet some threshold. By default, it removes all zero-variance features, i.e. features that have the same value in all samples. As an example, suppose that we have a dataset with boolean features, and we want to remove all features that are either one or zero (on or off) in more than 80% of the samples. Boolean features are Bernoulli random variables, and the variance of such variables is given by $$\mathrm{Var}[X] = p(1 - p)$$ so we can select using the threshold .8 * (1 - .8) Step2: Univariate feature selection Univariate feature selection works by selecting the best features based on univariate statistical tests. It can be seen as a preprocessing step to an estimator. Scikit-learn exposes feature selection routines as objects that implement the transform method Step3: There is still the question of how to select the parameter k Step4: Recursive feature elimination Given an external estimator that assigns weights to features (e.g., the coefficients of a linear model), recursive feature elimination (RFE) is to select features by recursively considering smaller and smaller sets of features. First, the estimator is trained on the initial set of features and weights are assigned to each one of them. Then, features whose absolute weights are the smallest are pruned from the current set features. That procedure is recursively repeated on the pruned set until the desired number of features to select is eventually reached. RFECV performs RFE in a cross-validation loop to find the optimal number of features.
Python Code: import pandas as pd import numpy as np import zipfile with zipfile.ZipFile('../datasets/titanic.csv.zip', 'r') as z: f = z.open('titanic.csv') titanic = pd.read_csv(f, sep=',', index_col=0) titanic.head() titanic.Age.fillna(titanic.Age.median(), inplace=True) titanic.loc[titanic.Embarked.isnull(), 'Embarked'] = titanic.Embarked.mode().values titanic['Sex_Female'] = titanic.Sex.map({'male':0, 'female':1}) embarked_dummies = pd.get_dummies(titanic.Embarked, prefix='Embarked') titanic = pd.concat([titanic, embarked_dummies], axis=1) titanic['Age2'] = titanic['Age'] ** 2 titanic['Age3'] = titanic['Age'] ** 3 from sklearn.linear_model import LogisticRegression from sklearn.cross_validation import cross_val_score logreg = LogisticRegression(C=1e9) features = ['Pclass', 'Age', 'Age2', 'Age3', 'Parch', 'SibSp', 'Sex_Female', 'Embarked_C', 'Embarked_Q', 'Embarked_S'] X = titanic[list(features)] y = titanic['Survived'] pd.Series(cross_val_score(logreg, X, y, cv=10, scoring='accuracy')).describe() Explanation: 07- Feature Selection by Alejandro Correa Bahnsen version 0.2, May 2016 Part of the class Machine Learning for Security Informatics This notebook is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License. Special thanks goes to Kevin Markham Preprocessing & Cross-validation (review) End of explanation from sklearn.feature_selection import VarianceThreshold sel = VarianceThreshold(threshold=(.8 * (1 - .8))) sel.fit(X) sel.variances_, sel.get_support() X_sel = sel.transform(X) features_sel = np.array(features)[sel.get_support()] print(np.array(features)[~sel.get_support()]) pd.Series(cross_val_score(logreg, X_sel, y, cv=10, scoring='accuracy')).describe() Explanation: Removing features with low variance VarianceThreshold is a simple baseline approach to feature selection. It removes all features whose variance doesn’t meet some threshold. By default, it removes all zero-variance features, i.e. features that have the same value in all samples. As an example, suppose that we have a dataset with boolean features, and we want to remove all features that are either one or zero (on or off) in more than 80% of the samples. Boolean features are Bernoulli random variables, and the variance of such variables is given by $$\mathrm{Var}[X] = p(1 - p)$$ so we can select using the threshold .8 * (1 - .8): End of explanation from sklearn.feature_selection import SelectKBest sel = SelectKBest(k=8) sel.fit(X, y) sel.get_support() print(np.array(features)[~sel.get_support()]) print(np.array(features)[sel.get_support()]) X_sel = sel.transform(X) pd.Series(cross_val_score(logreg, X_sel, y, cv=10, scoring='accuracy')).describe() Explanation: Univariate feature selection Univariate feature selection works by selecting the best features based on univariate statistical tests. It can be seen as a preprocessing step to an estimator. Scikit-learn exposes feature selection routines as objects that implement the transform method: SelectKBest removes all but the k highest scoring features SelectPercentile removes all but a user-specified highest scoring percentage of features using common univariate statistical tests for each feature: false positive rate SelectFpr, false discovery rate SelectFdr, or family wise error SelectFwe. GenericUnivariateSelect allows to perform univariate feature selection with a configurable strategy. This allows to select the best univariate selection strategy with hyper-parameter search estimator End of explanation from sklearn.feature_selection import SelectPercentile, f_classif sel = SelectPercentile(f_classif, percentile=50) sel.fit(X, y) sel.get_support() print(np.array(features)[~sel.get_support()]) print(np.array(features)[sel.get_support()]) X_sel = sel.transform(X) pd.Series(cross_val_score(logreg, X_sel, y, cv=10, scoring='accuracy')).describe() Explanation: There is still the question of how to select the parameter k End of explanation from sklearn.feature_selection import RFE sel = RFE(estimator=logreg, n_features_to_select=6) sel.fit(X, y) sel.get_support() print(np.array(features)[~sel.get_support()]) print(np.array(features)[sel.get_support()]) X_sel = sel.transform(X) pd.Series(cross_val_score(logreg, X_sel, y, cv=10, scoring='accuracy')).describe() Explanation: Recursive feature elimination Given an external estimator that assigns weights to features (e.g., the coefficients of a linear model), recursive feature elimination (RFE) is to select features by recursively considering smaller and smaller sets of features. First, the estimator is trained on the initial set of features and weights are assigned to each one of them. Then, features whose absolute weights are the smallest are pruned from the current set features. That procedure is recursively repeated on the pruned set until the desired number of features to select is eventually reached. RFECV performs RFE in a cross-validation loop to find the optimal number of features. End of explanation
7,347
Given the following text description, write Python code to implement the functionality described below step by step Description: Priklad vyber autributov pomocou filtra a ukazka toho, preco PCA nie je vyber atributov Step1: Skusme najskor priklad toho ako by sme z nejakeho datasetu vyberali najdolezitejsie atributy pomocou filtra Step2: Pouzijeme oblubeny dataset kvietkov ktory ma 150 pozorovani a 4 atributy K nemu dogenerujeme 20 nahodnych atributov, ktore by mali mat len minimalny vplyv na predikciu zavyslej premennej Step3: Pre porovnanie sa pozireme na dva riadky povodnych a novych dat Step4: Mozeme skusit najst najdolezitejsie atributy. Mali by to byt prve 4 Step5: Naozaj sa nam podarilo najst tie data, ktore suviseli s predikovanou premennou. Da sa na nieco podobne pouzit PCA? A case against PCA a.k.a. Nepouzivajte PCA na vyber atributov PCA sa obycajne pouziva na redukciu atributov do mensieho poctu komponentov. Tu sa ale vyrabaju uplne nove komponenty (atributy), ktore su linearnymi kombinaciami tych povodnych Step6: Skusme pouzit PCA na zobrazenie toho, kolko potrebuje komponentov na vysvetlenie datasetu pozor, hovorime o komponentoch ktore vznikli linearnou kombinaciou atributov a nie priamo o atributoch Step7: Mozeme skusit pouzit PCA na oznacenie tych atributov, ktore najviac prispievaju k variancii v datach Zobrazime si heatmapu toho, ako silno prispievaju jednotlive vlastnosti k tvorbe komponentov a teda ako silno su v nich odrazene. To by nam malo vediet povedat, ktory atribut je vo vyslednych datach najviac odrazeny. Step8: matica nieje uplne nahodna ale su tam 3 pruhy, ktore zobrazuju 3 skupiny vlastnosti, ktore su v komponentoch odrazene vyraznejsie ako ostatne. Zda sa, ze toto su tie najdolezitejsie atributy. Mozeme si spocitat ich priemerny prispevok k vysvetleniu datasetu Step9: Zda sa, ze su tam nejake atributy, ktore su v tych komponentoch odrazene velmi silno. O co sa ale snazi PCA? Vysvetlit varianciu v datach. Skusme si teda vykreslit variancie vsetkych vlastnosti. Step10: Tu sa nam asi nieco nezda Pca nam vratilo prakticky to iste ako obycajne spocitanie variancie per atribut. Pri pouziti PCA je vzdy treba najskor normalizovat data PCA sa snazi vysvetlit co najviac variancie v datach. Ak maju rozne atributy roznu varianciu, tak pri niektorych sa bude snazit viac. Skusme spravit to iste ale predtym tie data normalizujeme Step11: Teraz potrebujem trochu viac komponentov na to aby som vysvetlil rovnake mnozstvo variancie Atributy maju asi vyrovnanejsi prispevok Ako bude vyzerat ta heatmapa? Step12: Teraz ta heatmapa vyzera nahodne a neda sa jasne pouzit na urcenie najdolezitejsich vlastnosti Mozeme si spocitat aj priemerny prispevok per atribut Step13: Po normalizovani dat sa priemrny prispevok pre vsetky atributy pohybuje tesne okolo 0. Neda as teda povedat ktory je najdolezitejsi a PCA nam povedalo len to, ktory ma najviac variancie. Toto sa da spocitat aj podstatne jednoduchsie Neodraza to strukturu dat, ale len ich varianciu Pouzivanie PCA na feature selection teda nema velky zmysel. Na dimensionality reduction ale ano. Ak ale mate nejaku kategoricku predikovanu hodnotu, tak zvazte skor LDA Skusme si pozriet co nam vrati PCA na ten dataset z prikladu na zaciatku Step14: Z tejto heatmapy sa neda vycitat ziadny jasny trend. Skusme este tie priemery prispevkov do komponentov per atribut.
Python Code: %matplotlib inline import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn plt.rcParams['figure.figsize'] = 9, 6 Explanation: Priklad vyber autributov pomocou filtra a ukazka toho, preco PCA nie je vyber atributov End of explanation from sklearn import datasets, svm from sklearn.feature_selection import SelectPercentile, f_classif iris = datasets.load_iris() iris.data.shape Explanation: Skusme najskor priklad toho ako by sme z nejakeho datasetu vyberali najdolezitejsie atributy pomocou filtra End of explanation # vygenerujme si 20 uplne nahodnych atributov a pricapme ich k povodnym datam E = np.random.uniform(0, 0.1, size=(len(iris.data), 20)) X = np.hstack((iris.data, E)) y = iris.target X_indices = np.arange(X.shape[-1]) X_indices X.shape Explanation: Pouzijeme oblubeny dataset kvietkov ktory ma 150 pozorovani a 4 atributy K nemu dogenerujeme 20 nahodnych atributov, ktore by mali mat len minimalny vplyv na predikciu zavyslej premennej End of explanation # povodne data iris.data[:2] # data rozsirene o dalsich 20 nahodnych atributov # len tie prve by mali davat zmysel X[:2] Explanation: Pre porovnanie sa pozireme na dva riadky povodnych a novych dat End of explanation from sklearn.feature_selection import SelectPercentile, f_classif selector = SelectPercentile(f_classif, percentile=10) selector.fit(X, y) scores = -np.log10(selector.pvalues_) scores /= scores.max() plt.bar(X_indices, scores) Explanation: Mozeme skusit najst najdolezitejsie atributy. Mali by to byt prve 4 End of explanation from sklearn.decomposition import PCA Explanation: Naozaj sa nam podarilo najst tie data, ktore suviseli s predikovanou premennou. Da sa na nieco podobne pouzit PCA? A case against PCA a.k.a. Nepouzivajte PCA na vyber atributov PCA sa obycajne pouziva na redukciu atributov do mensieho poctu komponentov. Tu sa ale vyrabaju uplne nove komponenty (atributy), ktore su linearnymi kombinaciami tych povodnych End of explanation import sklearn.datasets as ds data = ds.load_breast_cancer()['data'] pca_trafo = PCA().fit(data) fig = plt.figure() ax = fig.add_subplot(1,1,1) line, = ax.plot(pca_trafo.explained_variance_ratio_, '--o') ax.set_yscale('log') # skus si vyhodit logaritmicku mierku, uvidis, ze je tam asi problem ax.set_title('Prispevok komponentov k vysvetleniu variancie datasetu') Explanation: Skusme pouzit PCA na zobrazenie toho, kolko potrebuje komponentov na vysvetlenie datasetu pozor, hovorime o komponentoch ktore vznikli linearnou kombinaciou atributov a nie priamo o atributoch End of explanation import sklearn.datasets as ds from sklearn.decomposition import PCA pca_trafo = PCA() data = ds.load_breast_cancer()['data'] pca_data = pca_trafo.fit_transform(data) ax = seaborn.heatmap(np.log(pca_trafo.inverse_transform(np.eye(data.shape[1]))), cmap="hot", cbar=False) ax.set_xlabel('features') ax.set_ylabel('components') Explanation: Mozeme skusit pouzit PCA na oznacenie tych atributov, ktore najviac prispievaju k variancii v datach Zobrazime si heatmapu toho, ako silno prispievaju jednotlive vlastnosti k tvorbe komponentov a teda ako silno su v nich odrazene. To by nam malo vediet povedat, ktory atribut je vo vyslednych datach najviac odrazeny. End of explanation means = np.mean(pca_trafo.inverse_transform(np.eye(data.shape[1])), axis=0) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(means) ax.set_ylabel('mean contrib. in components') ax.set_xlabel('feature #') Explanation: matica nieje uplne nahodna ale su tam 3 pruhy, ktore zobrazuju 3 skupiny vlastnosti, ktore su v komponentoch odrazene vyraznejsie ako ostatne. Zda sa, ze toto su tie najdolezitejsie atributy. Mozeme si spocitat ich priemerny prispevok k vysvetleniu datasetu End of explanation # PCA sa pokusa vysvetliv varianciu v datach. Ak ma kazdy atribut inu strednu hodnotu (varianciu), tak nevysvetli mnozstvo informacie v atribute ale len jeho varianciu fig = plt.figure() ax = fig.add_subplot(111) ax.plot(np.std(data, axis=0)) ax.set_ylabel('standard deviation') ax.set_xlabel('feature #') # ax.set_yscale('log') Explanation: Zda sa, ze su tam nejake atributy, ktore su v tych komponentoch odrazene velmi silno. O co sa ale snazi PCA? Vysvetlit varianciu v datach. Skusme si teda vykreslit variancie vsetkych vlastnosti. End of explanation import sklearn.datasets as ds from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler # vykona z-normalizaciu na kazdom atribute z_scaler = StandardScaler() data = ds.load_breast_cancer()['data'] z_data = z_scaler.fit_transform(data) pca_trafo = PCA().fit(z_data) plt.plot(pca_trafo.explained_variance_ratio_, '--o') # mnozstvo vysvetlenej variancie per atribut plt.plot(pca_trafo.explained_variance_ratio_.cumsum(), '--o') # kumulativna suma vysvetlenej variancie ak si chcem vybrat atributy plt.ylim((0,1.0)) Explanation: Tu sa nam asi nieco nezda Pca nam vratilo prakticky to iste ako obycajne spocitanie variancie per atribut. Pri pouziti PCA je vzdy treba najskor normalizovat data PCA sa snazi vysvetlit co najviac variancie v datach. Ak maju rozne atributy roznu varianciu, tak pri niektorych sa bude snazit viac. Skusme spravit to iste ale predtym tie data normalizujeme End of explanation import sklearn.datasets as ds from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler z_scaler = StandardScaler() data = ds.load_breast_cancer()['data'] pca_trafo = PCA() z_data = z_scaler.fit_transform(data) pca_data = pca_trafo.fit_transform(z_data) ax = seaborn.heatmap(np.log(pca_trafo.inverse_transform(np.eye(data.shape[1]))), cmap="hot", cbar=False) ax.set_xlabel('features') ax.set_ylabel('components') Explanation: Teraz potrebujem trochu viac komponentov na to aby som vysvetlil rovnake mnozstvo variancie Atributy maju asi vyrovnanejsi prispevok Ako bude vyzerat ta heatmapa? End of explanation means = np.mean(pca_trafo.inverse_transform(np.eye(data.shape[1])), axis=0) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(means) ax.set_ylabel('mean contrib. in components') ax.set_xlabel('feature #') Explanation: Teraz ta heatmapa vyzera nahodne a neda sa jasne pouzit na urcenie najdolezitejsich vlastnosti Mozeme si spocitat aj priemerny prispevok per atribut End of explanation iris = datasets.load_iris() iris.data.shape # vygenerujme si 20 uplne nahodnych atributov a pricapme ich k povodnym datam E = np.random.uniform(0, 0.1, size=(len(iris.data), 20)) X = np.hstack((iris.data, E)) y = iris.target print('Tvar povodnych dat', iris.data.shape) print('Tvar upravenych dat', X.shape) X_indices = np.arange(X.shape[-1]) z_scaler = StandardScaler() pca_trafo = PCA() z_data = z_scaler.fit_transform(X) pca_data = pca_trafo.fit_transform(z_data) ax = seaborn.heatmap(np.log(pca_trafo.inverse_transform(np.eye(X.shape[1]))), cmap="hot", cbar=False) ax.set_xlabel('features') ax.set_ylabel('components') Explanation: Po normalizovani dat sa priemrny prispevok pre vsetky atributy pohybuje tesne okolo 0. Neda as teda povedat ktory je najdolezitejsi a PCA nam povedalo len to, ktory ma najviac variancie. Toto sa da spocitat aj podstatne jednoduchsie Neodraza to strukturu dat, ale len ich varianciu Pouzivanie PCA na feature selection teda nema velky zmysel. Na dimensionality reduction ale ano. Ak ale mate nejaku kategoricku predikovanu hodnotu, tak zvazte skor LDA Skusme si pozriet co nam vrati PCA na ten dataset z prikladu na zaciatku End of explanation means = np.mean(pca_trafo.inverse_transform(np.eye(X.shape[1])), axis=0) fig = plt.figure() ax = fig.add_subplot(111) ax.bar(X_indices, means) ax.set_ylabel('mean contrib. in components') ax.set_xlabel('feature #') Explanation: Z tejto heatmapy sa neda vycitat ziadny jasny trend. Skusme este tie priemery prispevkov do komponentov per atribut. End of explanation
7,348
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Example of the $k$-point sampling for TBtrans. Step2: Run these two executables
Python Code: chain = sisl.Geometry([0]*3, sisl.Atom(1, R=1.), sc=[1, 1, 10]) chain.set_nsc([3, 3, 1]) # Transport along y-direction chain = chain.tile(20, 0) He = sisl.Hamiltonian(chain) He.construct(([0.1, 1.1], [0, -1])) Hd = He.tile(20, 1) He.write('ELEC.nc') Hd.write('DEVICE.nc') with open('RUN.fdf', 'w') as f: f.write( TBT.k [ 3 1 1 ] TBT.DOS.A TBT.Current.Orb TBT.HS DEVICE.nc %block TBT.Elec.Left HS ELEC.nc semi-inf-direction -a2 electrode-position 1 %endblock %block TBT.Elec.Right HS ELEC.nc semi-inf-direction +a2 electrode-position end -1 %endblock ) Explanation: Example of the $k$-point sampling for TBtrans. End of explanation trs = sisl.get_sile('TRS/siesta.TBT.nc') no_trs = sisl.get_sile('NO_TRS/siesta.TBT.nc') def plot_bond(tbt, E): xy = tbt.geometry.xyz[:, :2] vector = tbt.vector_current(0, E)[:, :2] atom = tbt.atom_current(0, E) # Normalize atomic current atom += 1 atom *= 10 / atom.max() plt.scatter(xy[:, 0], xy[:, 1], atom); plt.quiver(xy[:, 0], xy[:, 1], vector[:, 0], vector[:, 1]); plt.gca().get_xaxis().set_visible(False) plt.gca().get_yaxis().set_visible(False) plt.tight_layout() plot_bond(trs, 1.) plt.savefig('fig/trs.png') plot_bond(no_trs, 1.) plt.savefig('fig/no_trs.png') Explanation: Run these two executables: tbtrans -D TRS RUN.fdf tbtrans -D NO_TRS -fdf TBT.Symmetry.TimeReversal:f RUN.fdf End of explanation
7,349
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: Filtering of Data in Insights Parsers and Rules In this tutorial we will investigate filters in insights-core, what they are, how they affect your components and how you can use them in your code. Documentation on filters can be found in the insights-core documentation. The primary purposes of filters are Step3: First we'll need to add a specification to collect the configuration file. Note that for purposes of this tutorial we are collecting from a directory where this notebook is located. Normally the file path would be an absolute path on your system or in an archive. Step5: Next we'll need to add a parser to parse the file being collected by the spec. Since this file is in INI format and insights-core provides the IniConfigFile parser, we can just use that to parse the file. See the parser documentation to find out what methods that parser provides. Step7: Finally we can write the rule that will examine the contents of the parsed configuration file to determine if there are any vulnerabilities. In this INI file we can find the vulnerabilities by searching for keywords to find one that contains the string vulnerability. If any vulnerabilities are found the rule should return information in the form of a response that documents the vulnerabilities found, and tags them with the key DS_IS_VULNERABLE. If no vulnerabilities are found the rule should just drop out, effectively returning None. Step8: Before we run the rule, lets look at the contents of the configuration file. It is in the format of a typical INI file and contains some interesting information. In particular we see that it does contain a keyword that should match the string we are looking for in the rule, "major_vulnerability=ray-shielded particle exhaust vent". So we expect the rule to return results. Step9: Lets run our rule and find out. To run the rule we'll use the insights.run() function and as the argument pass in our rule object (note this is not a string but the actual object). The results returned will be an insights.dr.broker object that contains all sorts of information about the execution of the rule. You can explore more details of the broker in the Insights Core Tutorial notebook. The print statements in our rule provide output as it loops through the configuration file. Step10: Now we are ready to look at the results. The results are stored in results[ds_vulnerable] where the rule object ds_vulnerable is the key into the dictionary of objects that your rule depended upon to execute, such as the parser DeathStarCfg and the spec Spec.death_star_config. You can see this by looking at those objects in results. Step11: Now lets look at the rule results to see if they match what we expected. Step13: Success, it worked as we expected finding the vulnerability. Now lets look at how filtering can affect the rule results. Filtering Data When we looked at the contents of the file you may have noticed some other interesting information such as this Step14: Now lets run the rule again and see what happens. Do you expect the same results we got before? Step16: Is that what you expected? Notice the output from the print statements in the rule, only the section names are printed. That is the result of adding the filter, only lines with '[' (the sections) are collected and provided to the parser. This means that the lines we were looking for in the rule are no longer there, and that it appears our rule didn't find any vulnerabilities. Next we'll look at how to fix our rule to work with the filtered data. Adding Filters to Rules We can add filters to a rule just like we added a filter to the parser, using the add_filter() method. The add_filter method requires a spec and a string or list/set of strings. In this case our rule is looking for the string 'vulnerability' so we just need to add that to the filter. Alternatively, filters can be added by specifying a parser or combiner in the add_filter() method instead of a spec. In that scenario, the dependency tree will be traversed to locate underlying datasources that are filterable (filterable parameter is equal to True). And the specified filters will be added to those datasouces. In our example, we can filter the underlying Specs.death_star_config datasource by adding the add_filter(DeathStarCfg, 'vulnerability') statement. This is especially useful when you are working with a combiner that consolidates data from multiple parsers, which in turn depend on multiple datasources. Adding a filter to a combiner would allow for consistent filtering of data across all applicable datasources. Step17: Now lets run the rule again and see what happens. Step19: Now look at the output from the print statements in the rule, the item that was missing is now included. By adding the string required by our rule to the spec filters we have successfully included the data needed by our rule to detect the problem. Also, by adding the filter to the parser we have eliminated the sensitive information from the input. Determining if a Spec is Filtered When you are developing your rule, you may want to add some code, during development, to check if the spec you are using is filtered. This can be accomplished by looking at the spec in insights/specs/init.py. Each spec is defined here as a RegistryPoint() type. If the spec is filtered it will have the parameter filterable=True, for example the following indicates that the messages log (/var/log/messages) will be filtered Step21: Debugging Components If you are writing component code you may sometimes not see any results even though you expected them and no errors were displayed. That is because insights-core is catching the exceptions and saving them. In order to see the exceptions you can use the following method to display the results of a run and any errors that occurrerd. Step22: Here's an example of this function in use
Python Code: Some imports used by all of the code in this tutorial import sys sys.path.insert(0, "../..") from __future__ import print_function import os from insights import run from insights.specs import SpecSet from insights.core import IniConfigFile from insights.core.plugins import parser, rule, make_fail from insights.core.spec_factory import simple_file Explanation: Filtering of Data in Insights Parsers and Rules In this tutorial we will investigate filters in insights-core, what they are, how they affect your components and how you can use them in your code. Documentation on filters can be found in the insights-core documentation. The primary purposes of filters are: to prevent the collection of sensitive information while enabling the collection of necessary information for analysis, and; to reduce the amount of information collected. Filters are typically added in rule modules since the purpose of a rule is to analyze particular information and identify a problem, potential problem or fact about the system. A filter may also be added in a parse modules if it is required to enable parsing of the data. We will discuss this further when we look at the example. Filters added by rules and parsers are applied when the data is collected from a system. They are combined so that if they are added from multiple rules and parsers, each rule will receive all information that was collected by all filters for a given source. An example will help demonstrate this. Suppose you write some rules that needs information from /var/log/messages. This file could be very large and contain potentially sensitive information, so it is not desirable to collect the entire file. Let's say rule_a needs messages that indicate my_special_process has failed to start. And another rule, rule_b needs messages that indicate that my_other_process had the errors MY_OTHER_PROCESS: process locked or MY_OTHER_PROCESS: memory exceeded. Then the two rules could add the following filters to ensure that just the information they need is collected: rule_a: python add_filter(Specs.messages, 'my_special_process') rule_b: python add_filter(Specs.messages, ['MY_OTHER_PROCESS: process locked', 'MY_OTHER_PROCESS: memory exceeded']) The effect of this would be that when /var/log/messages is collected, the filters would be applied and only the lines containing the strings 'my_special_process', 'MY_OTHER_PROCESS: process locked', or 'MY_OTHER_PROCESS: memory exceeded' would be collected. This significantly reduces the size of the data and the chance that sensitive information in /var/log/messages might be collected. While there are significant benefits to filtering, you must be aware that a datasource is being filtered or your rules could fail to identify a condition that may be present on a system. For instance suppose a rule rule_c also needs information from /var/log/messages about process_xyz. If rule_c runs with other rules like rule_a or rule_b then it would never see lines containing "process_xyz" appearing in /var/log/messages unless it adds a new filter. When any rule or parser adds a filter to a datasource, that data will be filtered for all components, not just the component adding the filter. Because of this it is important to understand when a datasource is being filtered so that your rule will function properly and include its own filters if needed. Exploring Filters Unfiltered Data Suppose we want to write a rule that will evaluate the contents of the configuration file death_star.ini to determine if there are any vulnerabilities. Since this is a new data source that is not currently collected by insights-core we'll need to add three elements to collect, parse and evaluate the information. End of explanation class Specs(SpecSet): Define a new spec to collect the file we need. death_star_config = simple_file(os.path.join(os.getcwd(), 'death_star.ini'), filterable=True) Explanation: First we'll need to add a specification to collect the configuration file. Note that for purposes of this tutorial we are collecting from a directory where this notebook is located. Normally the file path would be an absolute path on your system or in an archive. End of explanation @parser(Specs.death_star_config) class DeathStarCfg(IniConfigFile): Define a new parser to parse the spec. Since the spec is a standard INI format we can use the existing IniConfigFile parser that is provided by insights-core. See documentation here: https://insights-core.readthedocs.io/en/latest/api_index.html#insights.core.IniConfigFile pass Explanation: Next we'll need to add a parser to parse the file being collected by the spec. Since this file is in INI format and insights-core provides the IniConfigFile parser, we can just use that to parse the file. See the parser documentation to find out what methods that parser provides. End of explanation @rule(DeathStarCfg) def ds_vulnerable(ds_cfg): Define a new rule to look for vulnerable conditions that may be included in the INI file. If found report them. vulnerabilities = [] for section in ds_cfg.sections(): print("Section: {}".format(section)) for item_key in ds_cfg.items(section): print(" {}={}".format(item_key, ds_cfg.get(section, item_key))) if 'vulnerability' in item_key: vulnerabilities.append((item_key, ds_cfg.get(section, item_key))) if vulnerabilities: return make_fail('DS_IS_VULNERABLE', vulnerabilities=vulnerabilities) Explanation: Finally we can write the rule that will examine the contents of the parsed configuration file to determine if there are any vulnerabilities. In this INI file we can find the vulnerabilities by searching for keywords to find one that contains the string vulnerability. If any vulnerabilities are found the rule should return information in the form of a response that documents the vulnerabilities found, and tags them with the key DS_IS_VULNERABLE. If no vulnerabilities are found the rule should just drop out, effectively returning None. End of explanation !cat death_star.ini Explanation: Before we run the rule, lets look at the contents of the configuration file. It is in the format of a typical INI file and contains some interesting information. In particular we see that it does contain a keyword that should match the string we are looking for in the rule, "major_vulnerability=ray-shielded particle exhaust vent". So we expect the rule to return results. End of explanation results = run(ds_vulnerable) Explanation: Lets run our rule and find out. To run the rule we'll use the insights.run() function and as the argument pass in our rule object (note this is not a string but the actual object). The results returned will be an insights.dr.broker object that contains all sorts of information about the execution of the rule. You can explore more details of the broker in the Insights Core Tutorial notebook. The print statements in our rule provide output as it loops through the configuration file. End of explanation type(results[Specs.death_star_config]) type(results[DeathStarCfg]) type(results[ds_vulnerable]) Explanation: Now we are ready to look at the results. The results are stored in results[ds_vulnerable] where the rule object ds_vulnerable is the key into the dictionary of objects that your rule depended upon to execute, such as the parser DeathStarCfg and the spec Spec.death_star_config. You can see this by looking at those objects in results. End of explanation results[ds_vulnerable] Explanation: Now lets look at the rule results to see if they match what we expected. End of explanation from insights.core.filters import add_filter add_filter(Specs.death_star_config, '[') @parser(Specs.death_star_config) class DeathStarCfg(IniConfigFile): Define a new parser to parse the spec. Since the spec is a standard INI format we can use the existing IniConfigFile parser that is provided by insights-core. See documentation here: https://insights-core.readthedocs.io/en/latest/api_index.html#insights.core.IniConfigFile pass Explanation: Success, it worked as we expected finding the vulnerability. Now lets look at how filtering can affect the rule results. Filtering Data When we looked at the contents of the file you may have noticed some other interesting information such as this: ``` Keep this info secret [secret_stuff] username=dvader password=luke_is_my_son `` As a parser writer, if you know that a file could contain sensitive information, you may choose to filter it in the parser module to avoid collecting it. Usernames, passwords, hostnames, security keys, and other sensitive information should not be collected. In this case theusernameandpassword` are in the configuration file, so we should add a filter to this parser to prevent them from being collected. How do we add a filter and avoid breaking the parser? Each parser is unique, so the parser writer must determine if a filter is necessary, and how to add a filter that will allow the parser to function with a minimal set of data. For instance a Yaml or XML parser might have a difficult time parsing a filtered Yaml or XML file. For our example, we are using an INI file parser. INI files are structured with sections which are identified as a section name in square brackets like [section name], followed by items like name or name=value. One possible way to filter an INI file is to add the filter "[" which will collect all lines with sections but no items. This can be successfully parsed by the INI parser, so that is how we'll filter out this sensitive information in our configuration file. We'll rewrite the parser adding the add_filter(Specs.death_star_config, '[') to filter all lines except those with a '[' string. End of explanation results = run(ds_vulnerable) results.get(ds_vulnerable, "No results") # Use .get method of dict so we can provide default other than None Explanation: Now lets run the rule again and see what happens. Do you expect the same results we got before? End of explanation add_filter(Specs.death_star_config, 'vulnerability') @rule(DeathStarCfg) def ds_vulnerable(ds_cfg): Define a new rule to look for vulnerable conditions that may be included in the INI file. If found report them. vulnerabilities = [] for section in ds_cfg.sections(): print("Section: {}".format(section)) for item_key in ds_cfg.items(section): print(" {}={}".format(item_key, ds_cfg.get(section, item_key))) if 'vulnerability' in item_key: vulnerabilities.append((item_key, ds_cfg.get(section, item_key))) if vulnerabilities: return make_fail('DS_IS_VULNERABLE', vulnerabilities=vulnerabilities) Explanation: Is that what you expected? Notice the output from the print statements in the rule, only the section names are printed. That is the result of adding the filter, only lines with '[' (the sections) are collected and provided to the parser. This means that the lines we were looking for in the rule are no longer there, and that it appears our rule didn't find any vulnerabilities. Next we'll look at how to fix our rule to work with the filtered data. Adding Filters to Rules We can add filters to a rule just like we added a filter to the parser, using the add_filter() method. The add_filter method requires a spec and a string or list/set of strings. In this case our rule is looking for the string 'vulnerability' so we just need to add that to the filter. Alternatively, filters can be added by specifying a parser or combiner in the add_filter() method instead of a spec. In that scenario, the dependency tree will be traversed to locate underlying datasources that are filterable (filterable parameter is equal to True). And the specified filters will be added to those datasouces. In our example, we can filter the underlying Specs.death_star_config datasource by adding the add_filter(DeathStarCfg, 'vulnerability') statement. This is especially useful when you are working with a combiner that consolidates data from multiple parsers, which in turn depend on multiple datasources. Adding a filter to a combiner would allow for consistent filtering of data across all applicable datasources. End of explanation results = run(ds_vulnerable) results.get(ds_vulnerable, "No results") # Use .get method of dict so we can provide default other than None Explanation: Now lets run the rule again and see what happens. End of explanation This code will disable all filtering if it is run as the first cell when the notebook is opened. After the notebook has been started you will need to click on the Kernel menu and then the restart item, and then run this cell first before all others. You would need to restart the kernel and then not run this cell to prevent disabling filters. import os os.environ['INSIGHTS_FILTERS_ENABLED'] = 'False' results = run(ds_vulnerable) results.get(ds_vulnerable, "No results") # Use .get method of dict so we can provide default other than None Explanation: Now look at the output from the print statements in the rule, the item that was missing is now included. By adding the string required by our rule to the spec filters we have successfully included the data needed by our rule to detect the problem. Also, by adding the filter to the parser we have eliminated the sensitive information from the input. Determining if a Spec is Filtered When you are developing your rule, you may want to add some code, during development, to check if the spec you are using is filtered. This can be accomplished by looking at the spec in insights/specs/init.py. Each spec is defined here as a RegistryPoint() type. If the spec is filtered it will have the parameter filterable=True, for example the following indicates that the messages log (/var/log/messages) will be filtered: messages = RegistryPoint(filterable=True) If you need to use a parser that relies on a filtered spec then you need to add your own filter to ensure that your rule will receive the data necessary to evaluate the rule conditions. If you forget to add a filter to your rule, if you include integration tests for your rule, pytest will indicate an exception like the following warning you that the add_filter is missing: ``` telemetry/rules/tests/integration.py:7: component = <function report at 0x7fa843094e60>, input_data = <InputData {name:test4-00000}>, expected = None def run_test(component, input_data, expected=None): if filters.ENABLED: mod = component.__module__ sup_mod = '.'.join(mod.split('.')[:-1]) rps = _get_registry_points(component) filterable = set(d for d in rps if dr.get_delegate(d).filterable) missing_filters = filterable - ADDED_FILTERS.get(mod, set()) - ADDED_FILTERS.get(sup_mod, set()) if missing_filters: names = [dr.get_name(m) for m in missing_filters] msg = "%s must add filters to %s" raise Exception(msg % (mod, ", ".join(names))) E Exception: telemetry.rules.plugins.kernel.overcommit must add filters to insights.specs.Specs.messages ../../insights/insights-core/insights/tests/init.py:114: Exception ``` If you see this exception when you run tests then it means you need to include add_filter to your rule. Turning Off Filtering Globally There are often times that you would want or need to turn off filtering in order to perform testing or to fully analyze some aspects of a system and diagnose problems. Also if you are running locally on a system you might want to collect all data unfiltered. You can to this by setting the environment variable INSIGHTS_FILTERS_ENABLED=False prior to running insights-core. This won't work inside this notebook unless you follow the directions below. End of explanation def show_results(results, component): This function will show the results from run() where: results = run(component) run will catch all exceptions so if there are any this function will print them out with a stack trace, making it easier to develop component code. if component in results: print(results[component]) else: print("No results for: {}".format(component)) if results.exceptions: for comp in results.exceptions: print("Component Exception: {}".format(comp)) for exp in results.exceptions[comp]: print(results.tracebacks[exp]) Explanation: Debugging Components If you are writing component code you may sometimes not see any results even though you expected them and no errors were displayed. That is because insights-core is catching the exceptions and saving them. In order to see the exceptions you can use the following method to display the results of a run and any errors that occurrerd. End of explanation @rule(DeathStarCfg) def bad_rule(cfg): # Force an error here infinity = 1 / 0 results = run(bad_rule) show_results(results, bad_rule) Explanation: Here's an example of this function in use End of explanation
7,350
Given the following text description, write Python code to implement the functionality described below step by step Description: last lesson we wrote code to plot some values from our inflammation data. but we have a dozen we want to do same for how to repeat things? Step1: This is a bad appoach b/c Step2: uses a for loop to repeat operations general form Step3: Let's trace the execution Step4: finding the length of a string is such a common operation that Python actually has a built-in function to do it called len Step5: for loop is a way to do operations many times, a list is a way to store many values lists are builtins use [] Loop challenge Step6: Loop challenge 2 Step7: Loop challenge 3
Python Code: #example task: print each character in a word #one way to do is use a series of print statements word = 'lead' print(word[0]) print(word[1]) print(word[2]) print(word[3]) Explanation: last lesson we wrote code to plot some values from our inflammation data. but we have a dozen we want to do same for how to repeat things? End of explanation word = 'tin' print(word[0]) print(word[1]) print(word[2]) print(word[3]) #better approach word = 'lead' for char in word: print (char) #better word = 'supercalifragilisticexpialidocious' for char in word: print (char) Explanation: This is a bad appoach b/c: doesnt scale - what if you wanted to print: supercalifragilisticexpialidocious - on for each 34 characters fragile - long word it only prints partial; short sting it will throw error End of explanation length = 0 for vowel in 'aeiou': length = length + 1 #print(vowel, length) print('There are', length, 'vowels') Explanation: uses a for loop to repeat operations general form: python for variable in collection: do things with variable loop variable can be arbitrary, need colon at the end indention necessary no command to end loop like many languages End of explanation #note loop var still exists after loop letter = 'z' for letter in 'abc': print(letter) print('after the loop, letter is', letter) Explanation: Let's trace the execution: 1. length is 1, vowel is 'a' 2. length is 2, vowel is 'e' 3. length is 3, vowel is 'i' 4. length is 4, vowel is 'o' 5. length is 5, vowel is 'u' End of explanation print(len('aeiou')) Explanation: finding the length of a string is such a common operation that Python actually has a built-in function to do it called len: End of explanation # solution for i in range(1, 4): print(i) Explanation: for loop is a way to do operations many times, a list is a way to store many values lists are builtins use [] Loop challenge: Python has a built-in function called range that creates a sequence of numbers. Range can accept 1-3 parameters. If one parameter is input, range creates an array of that length, starting at zero and incrementing by 1. If 2 parameters are input, range starts at the first and ends at the second, incrementing by one. If range is passed 3 parameters, it starts at the first one, ends at the second one, and increments by the third one. For example, range(3) produces the numbers 0, 1, 2, while range(2, 5) produces 2, 3, 4, and range(3, 10, 3) produces 3, 6, 9. Using range, write a loop that uses range to print the first 3 natural numbers: 1 2 3 End of explanation result = 1 for i in range(0, 3): result = result * 5 print(result) for i in range(0,3): print(i) Explanation: Loop challenge 2: Exponentiation is built into Python: python print(5 ** 3) 125 Write a loop that calculates the same result as 5 ** 3 using multiplication (and without exponentiation). End of explanation newstring = '' oldstring = 'Newton' length_old = len(oldstring) for char_index in range(length_old): newstring = newstring + oldstring[length_old - char_index - 1] print(newstring) Explanation: Loop challenge 3: Write a loop that takes a string, and produces a new string with the characters in reverse order, so 'Newton' becomes 'notweN'. End of explanation
7,351
Given the following text description, write Python code to implement the functionality described below step by step Description: 3A.mr - Random Walk with Restart (système de recommandations) Si la méthode de factorisation de matrices est la méthode la plus connue pour faire des recommandations, ce n'est pas la seule. L'algorithme Random Walk with Restart s'appuie sur l'exploration locale des noeuds d'un graphe et produit des résultats plus facile à intepréter. Une des façons d'expliquer le PageRank est de modéliser Internet comme une immense chaîne de Markov. Le score PageRank correspond alors à la probabilité de rester dans un état ou un site Internet dans ce cas-là. Ce score est relié à la probabilité d'atterrir sur un site en suivant une marche aléatoire à travers les hyperliens. Et pour éviter les problèmes numériques lors du calcul, la formule fait apparaître un terme $d$ qui correspond à la probabilité qu'un surfer a de continuer son chemin ou d'aller voir ailleurs sur un site qui n'a rien à voir Step1: Une autre de procéder est de considérer que le vecteur $\pi$ est un point fixe de la suite Step2: On retrouve sensiblement la même chose. Une dernière façon est d'utiliser des marches aléatoires avec restart ou <i>Random Walk with Restart</i>. Mais pour ce faire, on doit générer des marches aléatoires partant de $i$ avec la probabilité de revenir au début égale à $c$.
Python Code: import numpy as np from numpy.linalg import det P = np.matrix ( [[ 0,0.5,0,0.5],[0.5,0,0.5,0],[1./3,1./3,0,1./3],[0.1,0.9,0,0]]) P c = 0.15 I = np.identity(4) e = np.matrix( [[ 0., 1., 0., 0. ]]).T pi = ((I-P.T*(1-c))).I * e * c pi Explanation: 3A.mr - Random Walk with Restart (système de recommandations) Si la méthode de factorisation de matrices est la méthode la plus connue pour faire des recommandations, ce n'est pas la seule. L'algorithme Random Walk with Restart s'appuie sur l'exploration locale des noeuds d'un graphe et produit des résultats plus facile à intepréter. Une des façons d'expliquer le PageRank est de modéliser Internet comme une immense chaîne de Markov. Le score PageRank correspond alors à la probabilité de rester dans un état ou un site Internet dans ce cas-là. Ce score est relié à la probabilité d'atterrir sur un site en suivant une marche aléatoire à travers les hyperliens. Et pour éviter les problèmes numériques lors du calcul, la formule fait apparaître un terme $d$ qui correspond à la probabilité qu'un surfer a de continuer son chemin ou d'aller voir ailleurs sur un site qui n'a rien à voir : il fait un bond avec une probabilité $(1-d)$. Je ne réécris pas les formules, elles sont disponibles sur Wikipedia. Maintenant, si on considère qu'un surfeur se ballade sur Internet de façon aléatoire mais qu'au lieu d'arrêter sa marche et d'aller n'importe ou ailleurs, il revient à son point de départ. Cela revient à étudier toutes les marches aléatoires partant du même noeud. On obtient alors des probabilités de rester dans des états qui dépendent de ce point de départ qu'on utilise pour faire des recommandations Fast Random Walk with Restart and Its Applications). Je suppose qu'on a un graphe $(G,V,E)$, $V$ pour les noeuds, $E$ pour les arcs. $P$ représente la matrice de transition d'un noeud à l'autre. La somme des coefficients sur la même ligne fait 1 : $\sum_j P_{ij}=1$. $e$ est un vecteur avec que des 0 sauf pour une coordonnées $i$ où $i$ est le noeud de départ. $c$ est la probabilité de revenir au point de départ. L'objectif est de trouver le régime transition $\pi$ qui vérifie l'équation suivante : $$\pi=(1-c)P'\pi+ce \Longleftrightarrow \pi = c(I-(1-c)P')^{-1}e$$ Le vecteur $\pi$ qui en résulte donne un poids à chaque noeud du graphe et c'est ce poids dont on se sert pour ordonner les recommandations. Autrement dit, si un surfeur est sur un site $i$, on lui recommandera comme autre site ceux dont le poids est le plus fort dans le vecteur $\pi$. Le tout est savoir de le calculer. Exemple, on choisit pour $P$ : End of explanation pi = e for i in range(0,10): pi = P.T * pi * (1-c) + e * c pi Explanation: Une autre de procéder est de considérer que le vecteur $\pi$ est un point fixe de la suite : $\pi^t = (1-c)P \pi^{t-1} +ce$. End of explanation import random from numpy.random import multinomial def marche_alea(P,c,i): marche = [ i ] while True: r = random.random() if r <= c: return marche vect = P[i,:].tolist()[0] i = multinomial(1,vect,size=1).tolist()[0].index(1) marche.append(i) def aggregation(marches): count = {} for marche in marches: for i in marche : count[i] = count.get(i,0)+1.0 s = sum( _ for _ in count.values())*1.0 for i in count: count[i] /= s return [ count.get(i,0) for i in range(0,max(_ for _ in count.keys())+1) ] marches = [ marche_alea(P,c,1) for k in range(0,1000) ] count = aggregation(marches) count Explanation: On retrouve sensiblement la même chose. Une dernière façon est d'utiliser des marches aléatoires avec restart ou <i>Random Walk with Restart</i>. Mais pour ce faire, on doit générer des marches aléatoires partant de $i$ avec la probabilité de revenir au début égale à $c$. End of explanation
7,352
Given the following text description, write Python code to implement the functionality described below step by step Description: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9. This kind of neural network is used in a variety of real-world applications including Step1: Retrieving training and test data The MNIST data set already contains both training and test data. There are 55,000 data points of training data, and 10,000 points of test data. Each MNIST data point has Step2: Visualize the training data Provided below is a function that will help you visualize the MNIST data. By passing in the index of a training example, the function show_digit will display that training image along with it's corresponding label in the title. Step3: Building the network TFLearn lets you build the network by defining the layers in that network. For this example, you'll define Step4: Training the network Now that we've constructed the network, saved as the variable model, we can fit it to the data. Here we use the model.fit method. You pass in the training features trainX and the training targets trainY. Below I set validation_set=0.1 which reserves 10% of the data set as the validation set. You can also set the batch size and number of epochs with the batch_size and n_epoch keywords, respectively. Too few epochs don't effectively train your network, and too many take a long time to execute. Choose wisely! Step5: Testing After you're satisified with the training output and accuracy, you can then run the network on the test data set to measure it's performance! Remember, only do this after you've done the training and are satisfied with the results. A good result will be higher than 95% accuracy. Some simple models have been known to get up to 99.7% accuracy!
Python Code: # Import Numpy, TensorFlow, TFLearn, and MNIST data import numpy as np import tensorflow as tf import tflearn import tflearn.datasets.mnist as mnist Explanation: Handwritten Number Recognition with TFLearn and MNIST In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9. This kind of neural network is used in a variety of real-world applications including: recognizing phone numbers and sorting postal mail by address. To build the network, we'll be using the MNIST data set, which consists of images of handwritten numbers and their correct labels 0-9. We'll be using TFLearn, a high-level library built on top of TensorFlow to build the neural network. We'll start off by importing all the modules we'll need, then load the data, and finally build the network. End of explanation # Retrieve the training and test data trainX, trainY, testX, testY = mnist.load_data(one_hot=True) Explanation: Retrieving training and test data The MNIST data set already contains both training and test data. There are 55,000 data points of training data, and 10,000 points of test data. Each MNIST data point has: 1. an image of a handwritten digit and 2. a corresponding label (a number 0-9 that identifies the image) We'll call the images, which will be the input to our neural network, X and their corresponding labels Y. We're going to want our labels as one-hot vectors, which are vectors that holds mostly 0's and one 1. It's easiest to see this in a example. As a one-hot vector, the number 0 is represented as [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], and 4 is represented as [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]. Flattened data For this example, we'll be using flattened data or a representation of MNIST images in one dimension rather than two. So, each handwritten number image, which is 28x28 pixels, will be represented as a one dimensional array of 784 pixel values. Flattening the data throws away information about the 2D structure of the image, but it simplifies our data so that all of the training data can be contained in one array whose shape is [55000, 784]; the first dimension is the number of training images and the second dimension is the number of pixels in each image. This is the kind of data that is easy to analyze using a simple neural network. End of explanation trainY[0].argmax(axis=0) plt.imshow? # Visualizing the data import matplotlib.pyplot as plt %matplotlib inline # Function for displaying a training image by it's index in the MNIST set def show_digit(index): label = trainY[index].argmax(axis=0) # Reshape 784 array into 28x28 image image = trainX[index].reshape([28,28]) plt.title('Training data, index: %d, Label: %d' % (index, label)) plt.imshow(image, cmap='gray_r') plt.show() # Display the first (index 0) training image show_digit(0) Explanation: Visualize the training data Provided below is a function that will help you visualize the MNIST data. By passing in the index of a training example, the function show_digit will display that training image along with it's corresponding label in the title. End of explanation # Define the neural network def build_model(lr=0.01, n_units=40, n_hidden_layers=1): # This resets all parameters and variables, leave this here tf.reset_default_graph() #### Your code #### # Include the input layer, hidden layer(s), and set how you want to train the model # input net = tflearn.input_data([None, 784]) # hidden for i in range(n_hidden_layers): net = tflearn.fully_connected(net, n_units, activation='ReLU') # output net = tflearn.fully_connected(net, 10, activation='softmax') net = tflearn.regression(net, optimizer='sgd', learning_rate=lr, loss='categorical_crossentropy') # This model assumes that your network is named "net" model = tflearn.DNN(net) return model Explanation: Building the network TFLearn lets you build the network by defining the layers in that network. For this example, you'll define: The input layer, which tells the network the number of inputs it should expect for each piece of MNIST data. Hidden layers, which recognize patterns in data and connect the input to the output layer, and The output layer, which defines how the network learns and outputs a label for a given image. Let's start with the input layer; to define the input layer, you'll define the type of data that the network expects. For example, net = tflearn.input_data([None, 100]) would create a network with 100 inputs. The number of inputs to your network needs to match the size of your data. For this example, we're using 784 element long vectors to encode our input data, so we need 784 input units. Adding layers To add new hidden layers, you use net = tflearn.fully_connected(net, n_units, activation='ReLU') This adds a fully connected layer where every unit (or node) in the previous layer is connected to every unit in this layer. The first argument net is the network you created in the tflearn.input_data call, it designates the input to the hidden layer. You can set the number of units in the layer with n_units, and set the activation function with the activation keyword. You can keep adding layers to your network by repeated calling tflearn.fully_connected(net, n_units). Then, to set how you train the network, use: net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy') Again, this is passing in the network you've been building. The keywords: optimizer sets the training method, here stochastic gradient descent learning_rate is the learning rate loss determines how the network error is calculated. In this example, with categorical cross-entropy. Finally, you put all this together to create the model with tflearn.DNN(net). Exercise: Below in the build_model() function, you'll put together the network using TFLearn. You get to choose how many layers to use, how many hidden units, etc. Hint: The final output layer must have 10 output nodes (one for each digit 0-9). It's also recommended to use a softmax activation layer as your final output layer. End of explanation # find a good range with learning rate sample_n = int(1000 * 1.5) # max_count = 100 # nums of experiments to run # for count in xrange(max_count): # n_units = np.random.choice([50, 100, 150, 200]) # lr = 10**uniform(-3, -6) model = build_model(lr = 10**-2, n_units=100, n_hidden_layers=2) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) model = build_model(lr = 10**-3, n_units=100, n_hidden_layers=2) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) model = build_model(lr = 10**-4, n_units=100, n_hidden_layers=2) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) model = build_model(lr = 10**-1, n_units=100, n_hidden_layers=2) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) model = build_model(lr = 10**-4, n_units=100, n_hidden_layers=3) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) model = build_model(lr = 10**-5, n_units=100, n_hidden_layers=3) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) model = build_model(lr = 10**-1, n_units=50, n_hidden_layers=2) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) model = build_model(lr = 10**-2, n_units=50, n_hidden_layers=2) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) model = build_model(lr = 10**-3, n_units=50, n_hidden_layers=2) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) model = build_model(lr = 10**-2, n_units=50, n_hidden_layers=3) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) model = build_model(lr = 10**-1, n_units=50, n_hidden_layers=3) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) model = build_model(lr = 10**-4, n_units=50, n_hidden_layers=3) model.fit(trainX[:sample_n, :], trainY[:sample_n], validation_set=0.1, show_metric=True, batch_size=100, n_epoch=10) # finer search max_count = 20 sample_n = int(500 * 1.5) validation_frac = 0.1 train_n = int(sample_n * (1-validation_frac)) val_acc = [] lrs = [] for count in range(max_count): lr = 10**np.random.uniform(-2, -1) lrs.append(lr) model = build_model(lr = lr, n_units=100, n_hidden_layers=2) model.fit(trainX[:train_n, :], trainY[:train_n], validation_set=0, show_metric=False, snapshot_epoch=False, batch_size=100, n_epoch=10) val_acc.append(model.evaluate(trainX[train_n:sample_n,:], trainY[train_n:sample_n])[0]) for lr, acc in zip(lrs, val_acc): print("learning rate: %6.6f; val_acc: %4.4f" % (lr, acc)) # Training model = build_model(lr = 0.1, n_units=100, n_hidden_layers=2) model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=100, n_epoch=50) Explanation: Training the network Now that we've constructed the network, saved as the variable model, we can fit it to the data. Here we use the model.fit method. You pass in the training features trainX and the training targets trainY. Below I set validation_set=0.1 which reserves 10% of the data set as the validation set. You can also set the batch size and number of epochs with the batch_size and n_epoch keywords, respectively. Too few epochs don't effectively train your network, and too many take a long time to execute. Choose wisely! End of explanation # Compare the labels that our model predicts with the actual labels # Find the indices of the most confident prediction for each item. That tells us the predicted digit for that sample. predictions = np.array(model.predict(testX)).argmax(axis=1) # Calculate the accuracy, which is the percentage of times the predicated labels matched the actual labels actual = testY.argmax(axis=1) test_accuracy = np.mean(predictions == actual, axis=0) # Print out the result print("Test accuracy: ", test_accuracy) Explanation: Testing After you're satisified with the training output and accuracy, you can then run the network on the test data set to measure it's performance! Remember, only do this after you've done the training and are satisfied with the results. A good result will be higher than 95% accuracy. Some simple models have been known to get up to 99.7% accuracy! End of explanation
7,353
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 13 Examples and Exercises from Think Stats, 2nd Edition http Step1: Survival analysis If we have an unbiased sample of complete lifetimes, we can compute the survival function from the CDF and the hazard function from the survival function. Here's the distribution of pregnancy length in the NSFG dataset. Step3: The survival function is just the complementary CDF. Step4: Here's the CDF and SF. Step5: And here's the hazard function. Step6: Age at first marriage We'll use the NSFG respondent file to estimate the hazard function and survival function for age at first marriage. Step7: We have to clean up a few variables. Step8: And the extract the age at first marriage for people who are married, and the age at time of interview for people who are not. Step10: The following function uses Kaplan-Meier to estimate the hazard function. Step11: Here is the hazard function and corresponding survival function. Step14: Quantifying uncertainty To see how much the results depend on random sampling, we'll use a resampling process again. Step15: The following plot shows the survival function based on the raw data and a 90% CI based on resampling. Step16: The SF based on the raw data falls outside the 90% CI because the CI is based on weighted resampling, and the raw data is not. You can confirm that by replacing ResampleRowsWeighted with ResampleRows in ResampleSurvival. More data To generate survivial curves for each birth cohort, we need more data, which we can get by combining data from several NSFG cycles. Step20: The following is the code from survival.py that generates SFs broken down by decade of birth. Step21: Here are the results for the combined data. Step23: We can generate predictions by assuming that the hazard function of each generation will be the same as for the previous generation. Step24: And here's what that looks like. Step25: Remaining lifetime Distributions with difference shapes yield different behavior for remaining lifetime as a function of age. Step26: Here's the expected remaining duration of a pregnancy as a function of the number of weeks elapsed. After week 36, the process becomes "memoryless". Step27: And here's the median remaining time until first marriage as a function of age. Step29: Exercises Exercise
Python Code: from os.path import basename, exists def download(url): filename = basename(url) if not exists(filename): from urllib.request import urlretrieve local, _ = urlretrieve(url, filename) print("Downloaded " + local) download("https://github.com/AllenDowney/ThinkStats2/raw/master/code/thinkstats2.py") download("https://github.com/AllenDowney/ThinkStats2/raw/master/code/thinkplot.py") import thinkstats2 import thinkplot import numpy as np import pandas as pd try: import empiricaldist except ImportError: !pip install empiricaldist Explanation: Chapter 13 Examples and Exercises from Think Stats, 2nd Edition http://thinkstats2.com Copyright 2016 Allen B. Downey MIT License: https://opensource.org/licenses/MIT End of explanation download("https://github.com/AllenDowney/ThinkStats2/raw/master/code/nsfg.py") download("https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemPreg.dct") download( "https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemPreg.dat.gz" ) import nsfg preg = nsfg.ReadFemPreg() complete = preg.query("outcome in [1, 3, 4]").prglngth cdf = thinkstats2.Cdf(complete, label="cdf") Explanation: Survival analysis If we have an unbiased sample of complete lifetimes, we can compute the survival function from the CDF and the hazard function from the survival function. Here's the distribution of pregnancy length in the NSFG dataset. End of explanation download("https://github.com/AllenDowney/ThinkStats2/raw/master/code/survival.py") import survival def MakeSurvivalFromCdf(cdf, label=""): Makes a survival function based on a CDF. cdf: Cdf returns: SurvivalFunction ts = cdf.xs ss = 1 - cdf.ps return survival.SurvivalFunction(ts, ss, label) sf = MakeSurvivalFromCdf(cdf, label="survival") print(cdf[13]) print(sf[13]) Explanation: The survival function is just the complementary CDF. End of explanation thinkplot.Plot(sf) thinkplot.Cdf(cdf, alpha=0.2) thinkplot.Config(loc="center left") Explanation: Here's the CDF and SF. End of explanation hf = sf.MakeHazardFunction(label="hazard") print(hf[39]) thinkplot.Plot(hf) thinkplot.Config(ylim=[0, 0.75], loc="upper left") Explanation: And here's the hazard function. End of explanation download("https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemResp.dct") download( "https://github.com/AllenDowney/ThinkStats2/raw/master/code/2002FemResp.dat.gz" ) resp6 = nsfg.ReadFemResp() Explanation: Age at first marriage We'll use the NSFG respondent file to estimate the hazard function and survival function for age at first marriage. End of explanation resp6.cmmarrhx.replace([9997, 9998, 9999], np.nan, inplace=True) resp6["agemarry"] = (resp6.cmmarrhx - resp6.cmbirth) / 12.0 resp6["age"] = (resp6.cmintvw - resp6.cmbirth) / 12.0 Explanation: We have to clean up a few variables. End of explanation complete = resp6[resp6.evrmarry == 1].agemarry.dropna() ongoing = resp6[resp6.evrmarry == 0].age Explanation: And the extract the age at first marriage for people who are married, and the age at time of interview for people who are not. End of explanation from collections import Counter def EstimateHazardFunction(complete, ongoing, label="", verbose=False): Estimates the hazard function by Kaplan-Meier. http://en.wikipedia.org/wiki/Kaplan%E2%80%93Meier_estimator complete: list of complete lifetimes ongoing: list of ongoing lifetimes label: string verbose: whether to display intermediate results if np.sum(np.isnan(complete)): raise ValueError("complete contains NaNs") if np.sum(np.isnan(ongoing)): raise ValueError("ongoing contains NaNs") hist_complete = Counter(complete) hist_ongoing = Counter(ongoing) ts = list(hist_complete | hist_ongoing) ts.sort() at_risk = len(complete) + len(ongoing) lams = pd.Series(index=ts, dtype=float) for t in ts: ended = hist_complete[t] censored = hist_ongoing[t] lams[t] = ended / at_risk if verbose: print(t, at_risk, ended, censored, lams[t]) at_risk -= ended + censored return survival.HazardFunction(lams, label=label) Explanation: The following function uses Kaplan-Meier to estimate the hazard function. End of explanation hf = EstimateHazardFunction(complete, ongoing) thinkplot.Plot(hf) thinkplot.Config(xlabel="Age (years)", ylabel="Hazard") sf = hf.MakeSurvival() thinkplot.Plot(sf) thinkplot.Config(xlabel="Age (years)", ylabel="Prob unmarried", ylim=[0, 1]) Explanation: Here is the hazard function and corresponding survival function. End of explanation def EstimateMarriageSurvival(resp): Estimates the survival curve. resp: DataFrame of respondents returns: pair of HazardFunction, SurvivalFunction # NOTE: Filling missing values would be better than dropping them. complete = resp[resp.evrmarry == 1].agemarry.dropna() ongoing = resp[resp.evrmarry == 0].age hf = EstimateHazardFunction(complete, ongoing) sf = hf.MakeSurvival() return hf, sf def ResampleSurvival(resp, iters=101): Resamples respondents and estimates the survival function. resp: DataFrame of respondents iters: number of resamples _, sf = EstimateMarriageSurvival(resp) thinkplot.Plot(sf) low, high = resp.agemarry.min(), resp.agemarry.max() ts = np.arange(low, high, 1 / 12.0) ss_seq = [] for _ in range(iters): sample = thinkstats2.ResampleRowsWeighted(resp) _, sf = EstimateMarriageSurvival(sample) ss_seq.append(sf.Probs(ts)) low, high = thinkstats2.PercentileRows(ss_seq, [5, 95]) thinkplot.FillBetween(ts, low, high, color="gray", label="90% CI") Explanation: Quantifying uncertainty To see how much the results depend on random sampling, we'll use a resampling process again. End of explanation ResampleSurvival(resp6) thinkplot.Config( xlabel="Age (years)", ylabel="Prob unmarried", xlim=[12, 46], ylim=[0, 1], loc="upper right", ) Explanation: The following plot shows the survival function based on the raw data and a 90% CI based on resampling. End of explanation download( "https://github.com/AllenDowney/ThinkStats2/raw/master/code/1995FemRespData.dat.gz" ) download( "https://github.com/AllenDowney/ThinkStats2/raw/master/code/2006_2010_FemRespSetup.dct" ) download( "https://github.com/AllenDowney/ThinkStats2/raw/master/code/2006_2010_FemResp.dat.gz" ) resp5 = survival.ReadFemResp1995() resp6 = survival.ReadFemResp2002() resp7 = survival.ReadFemResp2010() resps = [resp5, resp6, resp7] Explanation: The SF based on the raw data falls outside the 90% CI because the CI is based on weighted resampling, and the raw data is not. You can confirm that by replacing ResampleRowsWeighted with ResampleRows in ResampleSurvival. More data To generate survivial curves for each birth cohort, we need more data, which we can get by combining data from several NSFG cycles. End of explanation def AddLabelsByDecade(groups, **options): Draws fake points in order to add labels to the legend. groups: GroupBy object thinkplot.PrePlot(len(groups)) for name, _ in groups: label = "%d0s" % name thinkplot.Plot([15], [1], label=label, **options) def EstimateMarriageSurvivalByDecade(groups, **options): Groups respondents by decade and plots survival curves. groups: GroupBy object thinkplot.PrePlot(len(groups)) for _, group in groups: _, sf = EstimateMarriageSurvival(group) thinkplot.Plot(sf, **options) def PlotResampledByDecade(resps, iters=11, predict_flag=False, omit=None): Plots survival curves for resampled data. resps: list of DataFrames iters: number of resamples to plot predict_flag: whether to also plot predictions for i in range(iters): samples = [thinkstats2.ResampleRowsWeighted(resp) for resp in resps] sample = pd.concat(samples, ignore_index=True) groups = sample.groupby("decade") if omit: groups = [(name, group) for name, group in groups if name not in omit] # TODO: refactor this to collect resampled estimates and # plot shaded areas if i == 0: AddLabelsByDecade(groups, alpha=0.7) if predict_flag: PlotPredictionsByDecade(groups, alpha=0.1) EstimateMarriageSurvivalByDecade(groups, alpha=0.1) else: EstimateMarriageSurvivalByDecade(groups, alpha=0.2) Explanation: The following is the code from survival.py that generates SFs broken down by decade of birth. End of explanation PlotResampledByDecade(resps) thinkplot.Config( xlabel="Age (years)", ylabel="Prob unmarried", xlim=[13, 45], ylim=[0, 1] ) Explanation: Here are the results for the combined data. End of explanation def PlotPredictionsByDecade(groups, **options): Groups respondents by decade and plots survival curves. groups: GroupBy object hfs = [] for _, group in groups: hf, sf = EstimateMarriageSurvival(group) hfs.append(hf) thinkplot.PrePlot(len(hfs)) for i, hf in enumerate(hfs): if i > 0: hf.Extend(hfs[i - 1]) sf = hf.MakeSurvival() thinkplot.Plot(sf, **options) Explanation: We can generate predictions by assuming that the hazard function of each generation will be the same as for the previous generation. End of explanation PlotResampledByDecade(resps, predict_flag=True) thinkplot.Config( xlabel="Age (years)", ylabel="Prob unmarried", xlim=[13, 45], ylim=[0, 1] ) Explanation: And here's what that looks like. End of explanation preg = nsfg.ReadFemPreg() complete = preg.query("outcome in [1, 3, 4]").prglngth print("Number of complete pregnancies", len(complete)) ongoing = preg[preg.outcome == 6].prglngth print("Number of ongoing pregnancies", len(ongoing)) hf = EstimateHazardFunction(complete, ongoing) sf1 = hf.MakeSurvival() Explanation: Remaining lifetime Distributions with difference shapes yield different behavior for remaining lifetime as a function of age. End of explanation rem_life1 = sf1.RemainingLifetime() thinkplot.Plot(rem_life1) thinkplot.Config( title="Remaining pregnancy length", xlabel="Weeks", ylabel="Mean remaining weeks" ) Explanation: Here's the expected remaining duration of a pregnancy as a function of the number of weeks elapsed. After week 36, the process becomes "memoryless". End of explanation hf, sf2 = EstimateMarriageSurvival(resp6) func = lambda pmf: pmf.Percentile(50) rem_life2 = sf2.RemainingLifetime(filler=np.inf, func=func) thinkplot.Plot(rem_life2) thinkplot.Config( title="Years until first marriage", ylim=[0, 15], xlim=[11, 31], xlabel="Age (years)", ylabel="Median remaining years", ) Explanation: And here's the median remaining time until first marriage as a function of age. End of explanation def CleanData(resp): Cleans respondent data. resp: DataFrame resp.cmdivorcx.replace([9998, 9999], np.nan, inplace=True) resp["notdivorced"] = resp.cmdivorcx.isnull().astype(int) resp["duration"] = (resp.cmdivorcx - resp.cmmarrhx) / 12.0 resp["durationsofar"] = (resp.cmintvw - resp.cmmarrhx) / 12.0 month0 = pd.to_datetime("1899-12-15") dates = [month0 + pd.DateOffset(months=cm) for cm in resp.cmbirth] resp["decade"] = (pd.DatetimeIndex(dates).year - 1900) // 10 CleanData(resp6) married6 = resp6[resp6.evrmarry == 1] CleanData(resp7) married7 = resp7[resp7.evrmarry == 1] Explanation: Exercises Exercise: In NSFG Cycles 6 and 7, the variable cmdivorcx contains the date of divorce for the respondent’s first marriage, if applicable, encoded in century-months. Compute the duration of marriages that have ended in divorce, and the duration, so far, of marriages that are ongoing. Estimate the hazard and survival curve for the duration of marriage. Use resampling to take into account sampling weights, and plot data from several resamples to visualize sampling error. Consider dividing the respondents into groups by decade of birth, and possibly by age at first marriage. End of explanation
7,354
Given the following text description, write Python code to implement the functionality described below step by step Description: Variational Equations For a complete introduction to variational equations, please read the paper by Rein and Tamayo (2016). For this tutorial, we work with a two planet system. We vary the initial semi-major axis $a$ of the outer planet. Because the planets interact with each other, the final $x$-position of the inner planet at the end of the simulation will depend on the initial semi-major axis of the outer planet. We run the simulation once for a fixed $a_0$ and then use first and second order variational equations to predict the final position of the outer planet for different $a$s in a neighbourhood of $a_0$. To do that, let us first import REBOUND, numpy and matplotlib. Step1: Before using variational equations, let us define a function that calculates the final position of the inner planet as a function of $a$ in the brute-force way Step2: We'll use this function to create a list of true final positions to which we later compare our results. Step3: Running a simulation with variational equations is very easy. We start by creating a simulation and add the three particles (the star and two planets) just as before. Note that the vary convenience function we use below only accepts heliocentric coordinates, so we explicitly tell REBOUND that the star is the primary when adding particles to the simulation. We then add variational particles to the simulation. We vary one parameter ($a$) and thus need only one set of first order variational equations. The second order variational equations depend on the first order ones. Thus, when initializing them, one has to pass the set of first order variational equations using the 'first_order' parameter. After adding a variation, one must always initialize it. We do this below with REBOUND's vary() convenience function, which makes varying orbital parameters particularly easy. Alternatively, one can also initialize the variational particles directly, e.g. using var_da.particles[1].x = 1. Note that variations are implemented as particles, but you they really represent derivatives of a particle's coordinates with respect to some initial parameter. For more details, see Rein and Tamayo (2016). The function below does all that and returns the final position of the inner planet, as well as the first and second derivatives of the position with respect to $a$. Step4: We can now use the variational equations to predict the final position of the inner particle. Note that we only run one simulation, at $a_0=1.56$. Step5: In the figure below, we plot the final position as a function of the initial semi-major axis. The black line corresponds to the true final position as calculated by the brute-force approach. The dashed and dotted lines correspond to the approximations using first and second order variational equations. As one can see, the second order approximation is very accurate within a neighbourhood of $a_0$.
Python Code: import rebound import numpy as np %matplotlib inline import matplotlib; import matplotlib.pyplot as plt Explanation: Variational Equations For a complete introduction to variational equations, please read the paper by Rein and Tamayo (2016). For this tutorial, we work with a two planet system. We vary the initial semi-major axis $a$ of the outer planet. Because the planets interact with each other, the final $x$-position of the inner planet at the end of the simulation will depend on the initial semi-major axis of the outer planet. We run the simulation once for a fixed $a_0$ and then use first and second order variational equations to predict the final position of the outer planet for different $a$s in a neighbourhood of $a_0$. To do that, let us first import REBOUND, numpy and matplotlib. End of explanation def run_sim(a): sim = rebound.Simulation() sim.add(m=1.) sim.add(primary=sim.particles[0],m=1e-3, a=1) sim.add(primary=sim.particles[0],m=1e-3, a=a) sim.integrate(2.*np.pi*10.) return sim.particles[1].x Explanation: Before using variational equations, let us define a function that calculates the final position of the inner planet as a function of $a$ in the brute-force way: End of explanation N=400 x_exact = np.zeros((N)) a_grid = np.linspace(1.4,1.7,N) for i,a in enumerate(a_grid): x_exact[i] = run_sim(a) Explanation: We'll use this function to create a list of true final positions to which we later compare our results. End of explanation def run_sim_var(a): sim = rebound.Simulation() sim.add(m=1.) sim.add(primary=sim.particles[0],m=1e-3, a=1) sim.add(primary=sim.particles[0],m=1e-3, a=a) var_da = sim.add_variation() var_dda = sim.add_variation(order=2, first_order=var_da) var_da.vary(2, "a") var_dda.vary(2, "a") sim.integrate(2.*np.pi*10.) return sim.particles[1].x, var_da.particles[1].x, var_dda.particles[1].x Explanation: Running a simulation with variational equations is very easy. We start by creating a simulation and add the three particles (the star and two planets) just as before. Note that the vary convenience function we use below only accepts heliocentric coordinates, so we explicitly tell REBOUND that the star is the primary when adding particles to the simulation. We then add variational particles to the simulation. We vary one parameter ($a$) and thus need only one set of first order variational equations. The second order variational equations depend on the first order ones. Thus, when initializing them, one has to pass the set of first order variational equations using the 'first_order' parameter. After adding a variation, one must always initialize it. We do this below with REBOUND's vary() convenience function, which makes varying orbital parameters particularly easy. Alternatively, one can also initialize the variational particles directly, e.g. using var_da.particles[1].x = 1. Note that variations are implemented as particles, but you they really represent derivatives of a particle's coordinates with respect to some initial parameter. For more details, see Rein and Tamayo (2016). The function below does all that and returns the final position of the inner planet, as well as the first and second derivatives of the position with respect to $a$. End of explanation a_0 = 1.56 x, dxda, ddxdda = run_sim_var(a_0) x_1st_order = np.zeros(N) x_2nd_order = np.zeros(N) for i,a in enumerate(a_grid): x_1st_order[i] = x + (a-a_0)*dxda x_2nd_order[i] = x + (a-a_0)*dxda + 0.5*(a-a_0)*(a-a_0)*ddxdda Explanation: We can now use the variational equations to predict the final position of the inner particle. Note that we only run one simulation, at $a_0=1.56$. End of explanation fig = plt.figure(figsize=(6,4)) ax = plt.subplot(111) ax.set_xlim(a_grid[0],a_grid[-1]) ax.set_ylim(np.min(x_exact),np.max(x_exact)*1.01) ax.set_xlabel("initial semi-major axis of the outer planet") ax.set_ylabel("$x$ position of inner planet after 10 orbits") ax.plot(a_grid, x_exact, "-", color="black", lw=2) ax.plot(a_grid, x_1st_order, "--", color="green") ax.plot(a_grid, x_2nd_order, ":", color="blue") ax.plot(a_0, x, "ro",ms=10); Explanation: In the figure below, we plot the final position as a function of the initial semi-major axis. The black line corresponds to the true final position as calculated by the brute-force approach. The dashed and dotted lines correspond to the approximations using first and second order variational equations. As one can see, the second order approximation is very accurate within a neighbourhood of $a_0$. End of explanation
7,355
Given the following text description, write Python code to implement the functionality described below step by step Description: Simple script to transform exported GeoModeller 3-D regular grid into MOOSE grid Note Step3: Load exported GeoModeller file We use here simply the export functionality of GeoModeller (note Step4: Some quick checks in 2-D slices Step5: And as a 3-D view Step6: Export model Simply store as np array
Python Code: # some basic imports: import numpy as np import os import matplotlib.pyplot as plt # for 3-D visualisation: import ipyvolume.pylab as p3 Explanation: Simple script to transform exported GeoModeller 3-D regular grid into MOOSE grid Note: we don't create a proper FE mesh here, but simply perform a "mapping" between a predefined mesh structure (in this case: a simple regular mesh, defined in MOOSE) and an exported GeoModeller model - with all limitations concerning refinement, problem size, etc. - however: a good way to get the first tests running! End of explanation class GeoExport(object): def __init__(self, filename): Load exported model self.filename = filename def load_file(self): Load file pass voxet_file = r'/Users/flow/Documents/01_work/61_simulation_results/PerthBasin/notebooks/voxet_NPB.vox' vf = open(voxet_file, 'r').readlines() vf_header = vf[:10] vf_entries = vf[10:] # remove newlines and convert to numpy array vf_entries = np.array([entry.rstrip() for entry in vf_entries]) # determine all formation names in model: form_names = np.unique(vf_entries) nx, ny, nz = int(vf_header[0].rstrip().split(" ")[1]),\ int(vf_header[1].rstrip().split(" ")[1]),\ int(vf_header[2].rstrip().split(" ")[1]) nx, ny, nz nx * ny * nz # create dictionary with formation names formation_dict = {} for i in range(len(form_names)): formation_dict[form_names[i]] = i formation_dict # read file and transform string arrays into appropriate integer values vox_int = [int(formation_dict[entry]) for entry in vf_entries] vox_int = np.array(vox_int, dtype='int') # reshape into 3-D array vox_3d = vox_int.reshape(nz, ny, nx) # swap axes to get x,y,z array vox_3d = np.swapaxes(vox_3d, 0, 2) Explanation: Load exported GeoModeller file We use here simply the export functionality of GeoModeller (note: far better results can be achieved with a dedicated export using the API). The exported file has some header information and then the formations simply listed in an $x$-dominant way. We load this file here in a simple structure: End of explanation plt.figure(figsize=(12,4)) plt.imshow(vox_3d[:,-1,:].transpose(), origin='bottom') plt.xlabel('X') plt.ylabel('Z') plt.show() plt.figure(figsize=(12,4)) plt.imshow(vox_3d[0,:,:].transpose(), origin='bottom') plt.xlabel('Y') plt.ylabel('Z') plt.show() plt.figure(figsize=(12,4)) plt.imshow(vox_3d[:,:,0].transpose(), origin='bottom') plt.xlabel('X') plt.ylabel('Y') plt.show() Explanation: Some quick checks in 2-D slices: End of explanation import ipyvolume ipyvolume.quickvolshow(vox_3d) # extract submodel for faster vis-test nx_sub = nz ny_sub = 80 nz_sub = nz x = np.arange(nx_sub) y = np.arange(ny_sub) z = np.arange(nz_sub) X,Y,Z = np.meshgrid(y,x,z) # extract subvolume vox_sub = vox_3d[:nx_sub, :ny_sub, :nz_sub] vox_sub = np.swapaxes(vox_sub, 0, 2) ipyvolume.quickvolshow(vox_sub) # vox_sub.shape np.unique(vox_sub) # create colour array: nc = np.max(vox_sub) vox_c = [plt.cm.viridis(i/nc)[:3] for i in vox_sub.ravel()] print(X.ravel().shape) print(vox_sub.ravel().shape) p3.figure() p3.scatter(X.ravel(), Y.ravel(), Z.ravel(), color=vox_c, marker='box', size=3.4) p3.show() Explanation: And as a 3-D view: End of explanation np.save("PB_sub.txt", vox_sub) vox_sub.shape Explanation: Export model Simply store as np array: End of explanation
7,356
Given the following text description, write Python code to implement the functionality described below step by step Description: Sebastian Raschka last updated Step1: <br> <br> <a name='plotting_data'></a> Plotting the sample data To get an intuitive idea of how our data looks like, let us visualize it in a simple scatter plot. Step3: <br> <br> <a name='objective_function'></a> Defining the objective function and decision rule Here, our objective function is to maximize the discriminant function $g_i(\pmb x)$, which we define as the posterior probability to perform a minimum-error classification (Bayes classifier). $ g_1(\pmb x) = P(\omega_1 | \; \pmb{x}), \quad g_2(\pmb{x}) = P(\omega_2 | \; \pmb{x}), \quad g_3(\pmb{x}) = P(\omega_2 | \; \pmb{x})$ So that our decision rule is to choose the class $\omega_i$ for which $g_i(\pmb x)$ is max., where $ \quad g_i(\pmb{x}) = \pmb{x}^{\,t} \bigg( - \frac{1}{2} \Sigma_i^{-1} \bigg) \pmb{x} + \bigg( \Sigma_i^{-1} \pmb{\mu}{\,i}\bigg)^t \pmb x + \bigg( -\frac{1}{2} \pmb{\mu}{\,i}^{\,t} \Sigma_{i}^{-1} \pmb{\mu}_{\,i} -\frac{1}{2} ln(|\Sigma_i|)\bigg) $ <br> <br> <a name='discriminant_functions'></a> Implementing the discriminant function Now, let us implement the discriminant function for $g_i(\pmb x)$ in Python code Step5: <br> <br> <a name='decision_rule'></a> Implementing the decision rule (classifier) Next, we need to implement the code that returns the max. $g_i(\pmb x)$ with the corresponding class label Step6: <br> <br> <a name='classifying'></a> Classifying the sample data Using the discriminant function and classifier that we just implemented above, let us classify our sample data. (I have to apologize for the long code below, but I thought it makes it a little more clear of what exactly is going on) Step7: <br> <br> <a name='confusion matrix'></a> Drawing the confusion matrix and calculating the empirical error Now, that we classified our data, let us plot the confusion matrix to see what the empirical error looks like. Step8: <br> <br> <a name='two'></a> 2) Assuming that the parameters are unknown - using MLE <br> <br> <a name='about_mle'></a> About the Maximum Likelihood Estimate (MLE) In contrast to the first section, let us assume that we only know the number of parameters for the class conditional densities $p (\; \pmb x \; | \; \omega_i)$, and we want to use a Maximum Likelihood Estimation (MLE) to estimate the quantities of these parameters from the training data (here Step10: <br> <br> <a name='mle_cov'></a> MLE of the covariance matrix $\pmb \Sigma$ Analog to $\pmb \mu$ we can find the equation for the $\pmb\Sigma$ via differentiation - okay the equations are a little bit more involved, but the approach is the same - so that we come to this equation Step11: <br> <br> <a name='classifying_mle'></a> Classification using our estimated parameters Using the estimated parameters $\pmb \mu_i$ and $\pmb \Sigma_i$, which we obtained via MLE, we calculate the error on the sample dataset again.
Python Code: import numpy as np np.random.seed(123456) # Generate 100 random patterns for class1 mu_vec1 = np.array([[0],[0]]) cov_mat1 = np.array([[3,0],[0,3]]) x1_samples = np.random.multivariate_normal(mu_vec1.ravel(), cov_mat1, 100) # Generate 100 random patterns for class2 mu_vec2 = np.array([[9],[0]]) cov_mat2 = np.array([[3,0],[0,3]]) x2_samples = np.random.multivariate_normal(mu_vec2.ravel(), cov_mat2, 100) # Generate 100 random patterns for class3 mu_vec3 = np.array([[6],[6]]) cov_mat3 = np.array([[4,0],[0,4]]) x3_samples = np.random.multivariate_normal(mu_vec3.ravel(), cov_mat3, 100) Explanation: Sebastian Raschka last updated: 04/14/2014 Link to this IPython Notebook on GitHub <hr> I am really looking forward to your comments and suggestions to improve and extend this tutorial! Just send me a quick note via Twitter: @rasbt or Email: bluewoodtree@gmail.com <hr> Maximum Likelihood Estimation for Statistical Pattern Classification Sections Introduction 1) A simple case where the parameters are known - no MLE required Generating some sample data Plotting the sample data Defining the objective function and decision rule Implementing the discriminant function Implementing the decision rule (classifier) Classifying our sample data Drawing the confusion matrix and calculating the empirical error 2) Assuming that the parameters are unknown - using MLE About the Maximum Likelihood Estimate (MLE) MLE of the mean vector $\pmb \mu$ MLE of the covariance matrix $\pmb \Sigma$ Classification using our estimated parameters Conclusion <br> <br> <a name='introduction'></a> Introduction Popular applications for Maximum Likelihood Estimates are the typical statistical pattern classification tasks, and in the past, I posted some examples using Bayes' classifiers for which the probabilistic models and parameters were known. In those cases, the design of the classifier was rather easy, however, in real applications, we are rarely given this information; this is where the Maximum Likelihood Estimate comes into play. However, the Maximum Likelihood Estimate still requires partial knowledge about the problem: We have to assume that the model of the class conditional densities is known (e.g., that the data follows typical Gaussian distribution). In contrast, non-parametric approaches like the Parzen-window technqiue do not require prior information about the distribution of the data (I will discuss this technique in more detail in a future article, the IPython notebook is already in preparation). To summarize the problem: Using MLE, we want to estimate the values of the parameters of a given distribution for the class-conditional densities, for example, the mean and variance assuming that the class-conditional densities are normal distributed (Gaussian) with $p(\pmb x \; | \; \omega_i) \sim N(\mu, \sigma^2)$. To illustrate the problem with an example, we will first take a look at a case where we already know the parameters, and then we will use the same dataset and estimate the parameters. This will give us some idea about the performance of the classifier using the estimated parameters. <br> <br> <a name='one'></a> 1) A simple case where the parameters are known - no MLE required Imagine that we want to classify data consisting of two-dimensional patterns, $\pmb{x} = [x_1, x_2]^t$ that could belong to 1 out of 3 classes $\omega_1,\omega_2,\omega_3$. Let's assume the following information about the model and the parameters are known: model: continuous univariate normal (Gaussian) model for the class-conditional densities $ p(\pmb x | \omega_j) \sim N(\pmb \mu|\Sigma) $ $ p(\pmb x | \omega_j) \sim \frac{1}{(2\pi)^{d/2} \; |\Sigma|^{1/2}} exp \bigg[ -\frac{1}{2}(\pmb x - \pmb \mu)^t \Sigma^{-1}(\pmb x - \pmb \mu) \bigg]$ $p([x_1, x_2]^t |\omega_1) ∼ N([0,0]^t,3I), \ p([x_1, x_2]^t |\omega_2) ∼ N([9,0]^t,3I), \ p([x_1, x_2]^t |\omega_3) ∼ N([6,6]^t,4I),$ Means of the sample distributions for 2-dimensional features: $ \pmb{\mu}{\,1} = \bigg[ \begin{array}{c} 0 \ 0 \ \end{array} \bigg] $, $ \; \pmb{\mu}{\,2} = \bigg[ \begin{array}{c} 9 \ 0 \ \end{array} \bigg] $, $ \; \pmb{\mu}_{\,3} = \bigg[ \begin{array}{c} 6 \ 6 \ \end{array} \bigg] $ Covariance matrices for the statistically independend and identically distributed ('i.i.d') features: $ \Sigma_i = \bigg[ \begin{array}{cc} \sigma_{11}^2 & \sigma_{12}^2\ \sigma_{21}^2 & \sigma_{22}^2 \ \end{array} \bigg] \ \Sigma_1 = \bigg[ \begin{array}{cc} 3 & 0\ 0 & 3 \ \end{array} \bigg] \ \Sigma_2 = \bigg[ \begin{array}{cc} 3 & 0\ 0 & 3 \ \end{array} \bigg] \ \Sigma_3 = \bigg[ \begin{array}{cc} 4 & 0\ 0 & 4 \ \end{array} \bigg] \$ Equal prior probabilities $P(\omega_1\; |\; \pmb x) \; = \; P(\omega_2\; |\; \pmb x) \; = \; P(\omega_3\; |\; \pmb x) \; = \frac{1}{3}$ <br> <br> <a name='sample_data'></a> Generating some sample data Given those information, let us draw some random data from a Gaussian distribution. End of explanation %pylab inline import numpy as np from matplotlib import pyplot as plt f, ax = plt.subplots(figsize=(7, 7)) ax.scatter(x1_samples[:,0], x1_samples[:,1], marker='o', color='green', s=40, alpha=0.5, label='$\omega_1$') ax.scatter(x2_samples[:,0], x2_samples[:,1], marker='s', color='blue', s=40, alpha=0.5, label='$\omega_2$') ax.scatter(x3_samples[:,0], x3_samples[:,1], marker='^', color='red', s=40, alpha=0.5, label='$\omega_2$') plt.legend(loc='upper right') plt.title('Training Dataset', size=20) plt.ylabel('$x_2$', size=20) plt.xlabel('$x_1$', size=20) plt.show() Explanation: <br> <br> <a name='plotting_data'></a> Plotting the sample data To get an intuitive idea of how our data looks like, let us visualize it in a simple scatter plot. End of explanation def discriminant_function(x_vec, cov_mat, mu_vec): Calculates the value of the discriminant function for a dx1 dimensional sample given the covariance matrix and mean vector. Keyword arguments: x_vec: A dx1 dimensional numpy array representing the sample. cov_mat: numpy array of the covariance matrix. mu_vec: dx1 dimensional numpy array of the sample mean. Returns a float value as result of the discriminant function. W_i = (-1/2) * np.linalg.inv(cov_mat) assert(W_i.shape[0] > 1 and W_i.shape[1] > 1), 'W_i must be a matrix' w_i = np.linalg.inv(cov_mat).dot(mu_vec) assert(w_i.shape[0] > 1 and w_i.shape[1] == 1), 'w_i must be a column vector' omega_i_p1 = (((-1/2) * (mu_vec).T).dot(np.linalg.inv(cov_mat))).dot(mu_vec) omega_i_p2 = (-1/2) * np.log(np.linalg.det(cov_mat)) omega_i = omega_i_p1 - omega_i_p2 assert(omega_i.shape == (1, 1)), 'omega_i must be a scalar' g = ((x_vec.T).dot(W_i)).dot(x_vec) + (w_i.T).dot(x_vec) + omega_i return float(g) Explanation: <br> <br> <a name='objective_function'></a> Defining the objective function and decision rule Here, our objective function is to maximize the discriminant function $g_i(\pmb x)$, which we define as the posterior probability to perform a minimum-error classification (Bayes classifier). $ g_1(\pmb x) = P(\omega_1 | \; \pmb{x}), \quad g_2(\pmb{x}) = P(\omega_2 | \; \pmb{x}), \quad g_3(\pmb{x}) = P(\omega_2 | \; \pmb{x})$ So that our decision rule is to choose the class $\omega_i$ for which $g_i(\pmb x)$ is max., where $ \quad g_i(\pmb{x}) = \pmb{x}^{\,t} \bigg( - \frac{1}{2} \Sigma_i^{-1} \bigg) \pmb{x} + \bigg( \Sigma_i^{-1} \pmb{\mu}{\,i}\bigg)^t \pmb x + \bigg( -\frac{1}{2} \pmb{\mu}{\,i}^{\,t} \Sigma_{i}^{-1} \pmb{\mu}_{\,i} -\frac{1}{2} ln(|\Sigma_i|)\bigg) $ <br> <br> <a name='discriminant_functions'></a> Implementing the discriminant function Now, let us implement the discriminant function for $g_i(\pmb x)$ in Python code: End of explanation import operator def classify_data(x_vec, g, mu_vecs, cov_mats): Classifies an input sample into 1 out of 3 classes determined by maximizing the discriminant function g_i(). Keyword arguments: x_vec: A dx1 dimensional numpy array representing the sample. g: The discriminant function. mu_vecs: A list of mean vectors as input for g. cov_mats: A list of covariance matrices as input for g. Returns a tuple (g_i()_value, class label). assert(len(mu_vecs) == len(cov_mats)), 'Number of mu_vecs and cov_mats must be equal.' g_vals = [] for m,c in zip(mu_vecs, cov_mats): g_vals.append(g(x_vec, mu_vec=m, cov_mat=c)) max_index, max_value = max(enumerate(g_vals), key=operator.itemgetter(1)) return (max_value, max_index + 1) Explanation: <br> <br> <a name='decision_rule'></a> Implementing the decision rule (classifier) Next, we need to implement the code that returns the max. $g_i(\pmb x)$ with the corresponding class label: End of explanation class1_as_1 = 0 class1_as_2 = 0 class1_as_3 = 0 for row in x1_samples: g = classify_data( row, discriminant_function, [mu_vec1, mu_vec2, mu_vec3], [cov_mat1, cov_mat2, cov_mat3] ) if g[1] == 2: class1_as_2 += 1 elif g[1] == 3: class1_as_3 += 1 else: class1_as_1 += 1 class2_as_1 = 0 class2_as_2 = 0 class2_as_3 = 0 for row in x2_samples: g = classify_data( row, discriminant_function, [mu_vec1, mu_vec2, mu_vec3], [cov_mat1, cov_mat2, cov_mat3] ) if g[1] == 2: class2_as_2 += 1 elif g[1] == 3: class2_as_3 += 1 else: class2_as_1 += 1 class3_as_1 = 0 class3_as_2 = 0 class3_as_3 = 0 for row in x3_samples: g = classify_data( row, discriminant_function, [mu_vec1, mu_vec2, mu_vec3], [cov_mat1, cov_mat2, cov_mat3] ) if g[1] == 2: class3_as_2 += 1 elif g[1] == 3: class3_as_3 += 1 else: class3_as_1 += 1 Explanation: <br> <br> <a name='classifying'></a> Classifying the sample data Using the discriminant function and classifier that we just implemented above, let us classify our sample data. (I have to apologize for the long code below, but I thought it makes it a little more clear of what exactly is going on) End of explanation import prettytable confusion_mat = prettytable.PrettyTable(["sample dataset", "w1 (predicted)", "w2 (predicted)", "w3 (predicted)"]) confusion_mat.add_row(["w1 (actual)",class1_as_1, class1_as_2, class1_as_3]) confusion_mat.add_row(["w2 (actual)",class2_as_1, class2_as_2, class2_as_3]) confusion_mat.add_row(["w3 (actual)",class3_as_1, class3_as_2, class3_as_3]) print(confusion_mat) misclass = x1_samples.shape[0]*3 - class1_as_1 - class2_as_2 - class3_as_3 bayes_err = misclass / (len(x1_samples)*3) print('Empirical Error: {:.2f} ({:.2f}%)'.format(bayes_err, bayes_err * 100)) Explanation: <br> <br> <a name='confusion matrix'></a> Drawing the confusion matrix and calculating the empirical error Now, that we classified our data, let us plot the confusion matrix to see what the empirical error looks like. End of explanation import prettytable mu_est1 = np.array([[sum(x1_samples[:,0])/len(x1_samples[:,0])],[sum(x1_samples[:,1])/len(x1_samples[:,1])]]) mu_est2 = np.array([[sum(x2_samples[:,0])/len(x2_samples[:,0])],[sum(x2_samples[:,1])/len(x2_samples[:,1])]]) mu_est3 = np.array([[sum(x3_samples[:,0])/len(x3_samples[:,0])],[sum(x3_samples[:,1])/len(x3_samples[:,1])]]) mu_mle = prettytable.PrettyTable(["", "mu_1", "mu_2", "mu_3"]) mu_mle.add_row(["MLE",mu_est1, mu_est2, mu_est3]) mu_mle.add_row(["actual",mu_vec1, mu_vec2, mu_vec3]) print(mu_mle) Explanation: <br> <br> <a name='two'></a> 2) Assuming that the parameters are unknown - using MLE <br> <br> <a name='about_mle'></a> About the Maximum Likelihood Estimate (MLE) In contrast to the first section, let us assume that we only know the number of parameters for the class conditional densities $p (\; \pmb x \; | \; \omega_i)$, and we want to use a Maximum Likelihood Estimation (MLE) to estimate the quantities of these parameters from the training data (here: our random sample data). Given the information about the form of the model - the data is normal distributed - the 2 parameters to be estimated are $\pmb \mu_i$ and $\pmb \Sigma_i$, which are summarized by the parameter vector $\pmb \theta_i = \bigg[ \begin{array}{c} \ \theta_{i1} \ \ \theta_{i2} \ \end{array} \bigg]= \bigg[ \begin{array}{c} \pmb \mu_i \ \pmb \Sigma_i \ \end{array} \bigg]$ For the Maximum Likelihood Estimate (MLE), we assume that we have a set of samples $D = \left{ \pmb x_1, \pmb x_2,..., \pmb x_n \right} $ that are i.i.d. (independent and identically distributed, drawn with probability $p(\pmb x \; | \; \omega_i, \; \pmb \theta_i) $). Thus, we can work with each class separately and omit the class labels, so that we write the probability density as $p(\pmb x \; | \; \pmb \theta)$ <br> <br> Likelihood of $ \pmb \theta $ Thus, the probability of observing $D = \left{ \pmb x_1, \pmb x_2,..., \pmb x_n \right} $ is: <br> <br> $p(D\; | \; \pmb \theta\;) = p(\pmb x_1 \; | \; \pmb \theta\;)\; \cdot \; p(\pmb x_2 \; | \;\pmb \theta\;) \; \cdot \;... \; p(\pmb x_n \; | \; \pmb \theta\;) = \prod_{k=1}^{n} \; p(\pmb x_k \pmb \; | \; \pmb \theta \;)$ <br> Where $p(D\; | \; \pmb \theta\;)$ is also called the likelihood of $\pmb\ \theta$. We are given the information that $p([x_1,x_2]^t) \;∼ \; N(\pmb \mu,\pmb \Sigma) $ (remember that we dropped the class labels, since we are working with every class separately). And the mutlivariate normal density is given as: $\quad \quad p(\pmb x) = \frac{1}{(2\pi)^{d/2} \; |\Sigma|^{1/2}} exp \bigg[ -\frac{1}{2}(\pmb x - \pmb \mu)^t \Sigma^{-1}(\pmb x - \pmb \mu) \bigg]$ So that $p(D\; | \; \pmb \theta\;) = \prod_{k=1}^{n} \; p(\pmb x_k \pmb \; | \; \pmb \theta \;) = \prod_{k=1}^{n} \; \frac{1}{(2\pi)^{d/2} \; |\Sigma|^{1/2}} exp \bigg[ -\frac{1}{2}(\pmb x - \pmb \mu)^t \Sigma^{-1}(\pmb x - \pmb \mu) \bigg]$ and the log of the multivariate density $ l(\pmb\theta) = \sum\limits_{k=1}^{n} - \frac{1}{2}(\pmb x - \pmb \mu)^t \pmb \Sigma^{-1} \; (\pmb x - \pmb \mu) - \frac{d}{2} \; ln \; 2\pi - \frac{1}{2} \;ln \; |\pmb\Sigma|$ <br> <br> Maximum Likelihood Estimate (MLE) In order to obtain the MLE $\boldsymbol{\hat{\theta}}$, we maximize $l (\pmb \theta)$, which can be done via differentiation: with $\nabla_{\pmb \theta} \equiv \begin{bmatrix} \frac{\partial \; }{\partial \; \theta_1} \ \frac{\partial \; }{\partial \; \theta_2} \end{bmatrix} = \begin{bmatrix} \frac{\partial \; }{\partial \; \pmb \mu} \ \frac{\partial \; }{\partial \; \pmb \sigma} \end{bmatrix}$ $\nabla_{\pmb \theta} l = \sum\limits_{k=1}^n \nabla_{\pmb \theta} \;ln\; p(\pmb x| \pmb \theta) = 0 $ <br> <br> <a name='mle_mu'></a> MLE of the mean vector $\pmb \mu$ After doing the differentiation, we find that the MLE of the parameter $\pmb\mu$ is given by the equation: ${\hat{\pmb\mu}} = \frac{1}{n} \sum\limits_{k=1}^{n} \pmb x_k$ As you can see, this is simply the mean of our dataset, so we can implement the code very easily and compare the estimate to the actual values for $\pmb \mu$. End of explanation import prettytable def mle_est_cov(x_samples, mu_est): Calculates the Maximum Likelihood Estimate for the covariance matrix. Keyword Arguments: x_samples: np.array of the samples for 1 class, n x d dimensional mu_est: np.array of the mean MLE, d x 1 dimensional Returns the MLE for the covariance matrix as d x d numpy array. cov_est = np.zeros((2,2)) for x_vec in x_samples: x_vec = x_vec.reshape(2,1) assert(x_vec.shape == mu_est.shape), 'mean and x vector hmust be of equal shape' cov_est += (x_vec - mu_est).dot((x_vec - mu_est).T) return cov_est / len(x_samples) cov_est1 = mle_est_cov(x1_samples, mu_est1) cov_est2 = mle_est_cov(x2_samples, mu_est2) cov_est3 = mle_est_cov(x3_samples, mu_est3) cov_mle = prettytable.PrettyTable(["", "covariance_matrix_1", "covariance_matrix_2", "covariance_matrix_3"]) cov_mle.add_row(["MLE", cov_est1, cov_est2, cov_est3]) cov_mle.add_row(['','','','']) cov_mle.add_row(["actual", cov_mat1, cov_mat2, cov_mat3]) print(cov_mle) Explanation: <br> <br> <a name='mle_cov'></a> MLE of the covariance matrix $\pmb \Sigma$ Analog to $\pmb \mu$ we can find the equation for the $\pmb\Sigma$ via differentiation - okay the equations are a little bit more involved, but the approach is the same - so that we come to this equation: ${\hat{\pmb\Sigma}} = \frac{1}{n} \sum\limits_{k=1}^{n} (\pmb x_k - \hat{\mu})(\pmb x_k - \hat{\mu})^t$ which we will also implement in Python code, and then compare to the acutal values of ${\pmb\Sigma}$. End of explanation class1_as_1 = 0 class1_as_2 = 0 class1_as_3 = 0 for row in x1_samples: g = classify_data( row, discriminant_function, [mu_est1, mu_est2, mu_est3], [cov_est1, cov_est2, cov_est3] ) if g[1] == 2: class1_as_2 += 1 elif g[1] == 3: class1_as_3 += 1 else: class1_as_1 += 1 class2_as_1 = 0 class2_as_2 = 0 class2_as_3 = 0 for row in x2_samples: g = classify_data( row, discriminant_function, [mu_est1, mu_est2, mu_est3], [cov_est1, cov_est2, cov_est3] ) if g[1] == 2: class2_as_2 += 1 elif g[1] == 3: class2_as_3 += 1 else: class2_as_1 += 1 class3_as_1 = 0 class3_as_2 = 0 class3_as_3 = 0 for row in x3_samples: g = classify_data( row, discriminant_function, [mu_est1, mu_est2, mu_est3], [cov_est1, cov_est2, cov_est3] ) if g[1] == 2: class3_as_2 += 1 elif g[1] == 3: class3_as_3 += 1 else: class3_as_1 += 1 import prettytable confusion_mat = prettytable.PrettyTable(["sample dataset", "w1 (predicted)", "w2 (predicted)", "w3 (predicted)"]) confusion_mat.add_row(["w1 (actual)",class1_as_1, class1_as_2, class1_as_3]) confusion_mat.add_row(["w2 (actual)",class2_as_1, class2_as_2, class2_as_3]) confusion_mat.add_row(["w3 (actual)",class3_as_1, class3_as_2, class3_as_3]) print(confusion_mat) misclass = x1_samples.shape[0]*3 - class1_as_1 - class2_as_2 - class3_as_3 bayes_err = misclass / (len(x1_samples)*3) print('Empirical Error: {:.2f} ({:.2f}%)'.format(bayes_err, bayes_err * 100)) Explanation: <br> <br> <a name='classifying_mle'></a> Classification using our estimated parameters Using the estimated parameters $\pmb \mu_i$ and $\pmb \Sigma_i$, which we obtained via MLE, we calculate the error on the sample dataset again. End of explanation
7,357
Given the following text description, write Python code to implement the functionality described below step by step Description: Example reading THREDDS NCSS as point in Python Step1: First generate a sample RESTful URL using the NCSS Web Form Step2: Once you have a sample URL, it's easy to create a different URL programmatically
Python Code: %matplotlib inline import pandas as pd Explanation: Example reading THREDDS NCSS as point in Python End of explanation url = 'http://data.ncof.co.uk/thredds/ncss/METOFFICE-NWS-AF-WAV-HOURLY?var=VHM0&var=VHM0_SW1&var=VHM0_WW&latitude=61.15&longitude=-9.5&time_start=2017-06-02T00%3A00%3A00Z&time_end=2017-06-17T23%3A00%3A00Z&accept=csv' Explanation: First generate a sample RESTful URL using the NCSS Web Form: http://data.ncof.co.uk/thredds/ncss/METOFFICE-NWS-AF-WAV-HOURLY/pointDataset.html End of explanation latitude = 61.15 longitude = -9.5 time_start = '2017-06-02T00:00:00Z' time_end = '2017-06-17T23:00:00Z' url = 'http://data.ncof.co.uk/thredds/ncss/METOFFICE-NWS-AF-WAV-HOURLY?var=VHM0&var=VHM0_SW1&var=VHM0_WW&latitude={}&longitude={}&time_start={}&time_end={}&accept=csv'.format(latitude,longitude,time_start,time_end) df = pd.read_csv(url, parse_dates=True, index_col=0, na_values=[-32767.0], skiprows=[0], names=['Lon','Lat','SigHeight(m)','Swell(m)','Wind Waves(m)']) # drop lon,lat columns df = df.drop(df.columns[[0,1]], axis=1) df.head() # Ugh, NCSS apparently ignores the scale_factor. Shite! I'll report this bug, but in the meantime... df = df/100. df.head() df.plot(figsize=(12,4),grid='on'); Explanation: Once you have a sample URL, it's easy to create a different URL programmatically End of explanation
7,358
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 21 Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: In the previous chapter we simulated a penny falling in a vacuum, that is, without air resistance. But the computational framework we used is very general; it is easy to add additional forces, including drag. In this chapter, I present a model of drag force and add it to the simulation. Drag force As an object moves through a fluid, like air, the object applies force to the air and, in accordance with Newton's third law of motion, the air applies an equal and opposite force to the object (see http Step2: The mass and diameter are from http Step3: And here's how we call it. Step4: Based on the mass and diameter of the penny, the density of air, and acceleration due to gravity, and the observed terminal velocity, we estimate that the coefficient of drag is about 0.44. Step5: It might not be obvious why it is useful to create a Params object just to create a System object. In fact, if we only run one simulation, it might not be useful. But it helps when we want to change or sweep the parameters. For example, suppose we learn that the terminal velocity of a penny is actually closer to 20 m/s. We can make a Params object with the new value, and a corresponding System object, like this Step6: The result from set is a new Params object that is identical to the original except for the given value of v_term. If we pass params2 to make_system, we see that it computes a different value of C_d. Step7: If the terminal velocity of the penny is 20 m/s, rather than 18 m/s, that implies that the coefficient of drag is 0.36, rather than 0.44. And that makes sense, since lower drag implies faster terminal velocity. Using Params objects to make System objects helps make sure that relationships like this are consistent. And since we are always making new objects, rather than modifying existing objects, we are less likely to make a mistake. Simulation Now let's get to the simulation. Here's a version of the slope function that includes drag Step8: f_drag is force due to drag, based on the drag equation. a_drag is acceleration due to drag, based on Newton's second law. To compute total acceleration, we add accelerations due to gravity and drag. g is negated because it is in the direction of decreasing y, and a_drag is positive because it is in the direction of increasing y. In the next chapter we will use Vector objects to keep track of the direction of forces and add them up in a less error-prone way. Step9: To stop the simulation when the penny hits the sidewalk, we'll use the event function from Section xxx Step10: Now we can run the simulation like this Step11: Here are the last few time steps Step12: The final height is close to 0, as expected. Interestingly, the final velocity is not exactly terminal velocity, which suggests that there are some numerical errors. We can get the flight time from results. Step13: Here's the plot of position as a function of time. Step14: And velocity as a function of time Step15: From an initial velocity of 0, the penny accelerates downward until it reaches terminal velocity; after that, velocity is constant. Summary Exercises Exercise Step17: Exercise
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/main/' local, _ = urlretrieve(url+filename, filename) print('Downloaded ' + local) # import functions from modsim from modsim import * Explanation: Chapter 21 Modeling and Simulation in Python Copyright 2021 Allen Downey License: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International End of explanation from modsim import Params params = Params( mass = 0.0025, # kg diameter = 0.019, # m rho = 1.2, # kg/m**3 g = 9.8, # m/s**2 v_init = 0, # m / s v_term = 18, # m / s height = 381, # m t_end = 30, # s ) Explanation: In the previous chapter we simulated a penny falling in a vacuum, that is, without air resistance. But the computational framework we used is very general; it is easy to add additional forces, including drag. In this chapter, I present a model of drag force and add it to the simulation. Drag force As an object moves through a fluid, like air, the object applies force to the air and, in accordance with Newton's third law of motion, the air applies an equal and opposite force to the object (see http://modsimpy.com/newton). The direction of this drag force is opposite the direction of travel, and its magnitude is given by the drag equation (see http://modsimpy.com/drageq): $$F_d = \frac{1}{2}~\rho~v^2~C_d~A$$ where $F_d$ is force due to drag, in newtons (N). $\rho$ is the density of the fluid in kg/m^3^. $v$ is the magnitude of velocity in m/s. $A$ is the reference area of the object, in m^2^. In this context, the reference area is the projected frontal area, that is, the visible area of the object as seen from a point on its line of travel (and far away). $C_d$ is the drag coefficient, a dimensionless quantity that depends on the shape of the object (including length but not frontal area), its surface properties, and how it interacts with the fluid. For objects moving at moderate speeds through air, typical drag coefficients are between 0.1 and 1.0, with blunt objects at the high end of the range and streamlined objects at the low end (see http://modsimpy.com/dragco). For simple geometric objects we can sometimes guess the drag coefficient with reasonable accuracy; for more complex objects we usually have to take measurements and estimate $C_d$ from data. Of course, the drag equation is itself a model, based on the assumption that $C_d$ does not depend on the other terms in the equation: density, velocity, and area. For objects moving in air at moderate speeds (below 45 mph or 20 m/s), this model might be good enough, but we should remember to revisit this assumption. For the falling penny, we can use measurements to estimate $C_d$. In particular, we can measure terminal velocity, $v_{term}$, which is the speed where drag force equals force due to gravity: $$\frac{1}{2}~\rho~v_{term}^2~C_d~A = m g$$ where $m$ is the mass of the object and $g$ is acceleration due to gravity. Solving this equation for $C_d$ yields: $$C_d = \frac{2~m g}{\rho~v_{term}^2~A}$$ According to Mythbusters, the terminal velocity of a penny is between 35 and 65 mph (see http://modsimpy.com/mythbust). Using the low end of their range, 40 mph or about 18 m/s, the estimated value of $C_d$ is 0.44, which is close to the drag coefficient of a smooth sphere. Now we are ready to add air resistance to the model. The Params Object As the number of system parameters increases, and as we need to do more work to compute them, we will find it useful to define a Params object to contain the quantities we need to make a System object. Params objects are similar to System objects, and we initialize them the same way. Here's the Params object for the falling penny: End of explanation from numpy import pi from modsim import State from modsim import System def make_system(params): init = State(y=params.height, v=params.v_init) area = pi * (params.diameter/2)**2 C_d = (2 * params.mass * params.g / (params.rho * area * params.v_term**2)) return System(init=init, area=area, C_d=C_d, mass=params.mass, rho=params.rho, g=params.g, t_end=params.t_end ) Explanation: The mass and diameter are from http://modsimpy.com/penny. The density of air depends on temperature, barometric pressure (which depends on altitude), humidity, and composition (http://modsimpy.com/density). I chose a value that might be typical in Boston, Massachusetts at 20 °C. Here's a version of make_system that takes the Params object and computes the inital state, init, the area, and the coefficient of drag. Then it returns a System object with the quantities we'll need for the simulation. End of explanation system = make_system(params) Explanation: And here's how we call it. End of explanation system.C_d Explanation: Based on the mass and diameter of the penny, the density of air, and acceleration due to gravity, and the observed terminal velocity, we estimate that the coefficient of drag is about 0.44. End of explanation params2 = params.set(v_term=20) Explanation: It might not be obvious why it is useful to create a Params object just to create a System object. In fact, if we only run one simulation, it might not be useful. But it helps when we want to change or sweep the parameters. For example, suppose we learn that the terminal velocity of a penny is actually closer to 20 m/s. We can make a Params object with the new value, and a corresponding System object, like this: End of explanation system2 = make_system(params2) system2.C_d Explanation: The result from set is a new Params object that is identical to the original except for the given value of v_term. If we pass params2 to make_system, we see that it computes a different value of C_d. End of explanation def slope_func(t, state, system): y, v = state rho, C_d, area = system.rho, system.C_d, system.area mass, g = system.mass, system.g f_drag = rho * v**2 * C_d * area / 2 a_drag = f_drag / mass dydt = v dvdt = -g + a_drag return dydt, dvdt Explanation: If the terminal velocity of the penny is 20 m/s, rather than 18 m/s, that implies that the coefficient of drag is 0.36, rather than 0.44. And that makes sense, since lower drag implies faster terminal velocity. Using Params objects to make System objects helps make sure that relationships like this are consistent. And since we are always making new objects, rather than modifying existing objects, we are less likely to make a mistake. Simulation Now let's get to the simulation. Here's a version of the slope function that includes drag: End of explanation slope_func(0, system.init, system) Explanation: f_drag is force due to drag, based on the drag equation. a_drag is acceleration due to drag, based on Newton's second law. To compute total acceleration, we add accelerations due to gravity and drag. g is negated because it is in the direction of decreasing y, and a_drag is positive because it is in the direction of increasing y. In the next chapter we will use Vector objects to keep track of the direction of forces and add them up in a less error-prone way. End of explanation def event_func(t, state, system): y, v = state return y event_func(0, system.init, system) Explanation: To stop the simulation when the penny hits the sidewalk, we'll use the event function from Section xxx: End of explanation from modsim import run_solve_ivp results, details = run_solve_ivp(system, slope_func, events=event_func) details.message Explanation: Now we can run the simulation like this: End of explanation results.tail() Explanation: Here are the last few time steps: End of explanation t_sidewalk = results.index[-1] t_sidewalk Explanation: The final height is close to 0, as expected. Interestingly, the final velocity is not exactly terminal velocity, which suggests that there are some numerical errors. We can get the flight time from results. End of explanation from modsim import decorate def plot_position(results): results.y.plot() decorate(xlabel='Time (s)', ylabel='Position (m)') plot_position(results) Explanation: Here's the plot of position as a function of time. End of explanation def plot_velocity(results): results.v.plot(color='C1', label='v') decorate(xlabel='Time (s)', ylabel='Velocity (m/s)') plot_velocity(results) Explanation: And velocity as a function of time: End of explanation # Solution params = params.set(v_init=-30) system2 = make_system(params) # Solution results2, details2 = run_solve_ivp(system2, slope_func, events=event_func) details2.message t_sidewalk = results2.index[-1] t_sidewalk plot_position(results2) # Solution plot_velocity(results2) Explanation: From an initial velocity of 0, the penny accelerates downward until it reaches terminal velocity; after that, velocity is constant. Summary Exercises Exercise: Run the simulation with a downward initial velocity that exceeds the penny's terminal velocity. What do you expect to happen? Plot velocity and position as a function of time, and see if they are consistent with your prediction. Hint: Use params.set to make a new Params object with a different initial velocity. End of explanation # Solution params_quarter = params.set( mass = 0.0057, # kg diameter = 0.024, # m flight_time = 19.1, # s ) # Solution system3 = make_system(params_quarter) # Solution # Run the simulation results3, details3 = run_solve_ivp(system3, slope_func, events=event_func) details3.message # Solution # And get the flight time t_sidewalk = results3.index[-1] t_sidewalk # Solution # The flight time is a little long, # so we could increase `v_term` and try again. # Or we could write an error function def error_func(guess, params): Final height as a function of C_d. guess: guess at v_term params: Params object returns: height in m print(guess) params = params.set(v_term=guess) system = make_system(params) results, details = run_solve_ivp(system, slope_func, events=event_func) t_sidewalk = results.index[-1] error = t_sidewalk - params.flight_time return error # Solution # We can test the error function like this v_guess1 = 18 error_func(v_guess1, params_quarter) # Solution v_guess2 = 22 error_func(v_guess2, params_quarter) # Solution # Now we can use `root_scalar` to find the value of # `v_term` that yields the measured flight time. from scipy.optimize import root_scalar res = root_scalar(error_func, params_quarter, bracket=[v_guess1, v_guess2]) # Solution v_term = res.root v_term # Solution # Plugging in the estimated value, # we can use `make_system` to compute `C_d` system4 = make_system(params_quarter.set(v_term=res.root)) system4.C_d Explanation: Exercise: Suppose we drop a quarter from the Empire State Building and find that its flight time is 19.1 seconds. Use this measurement to estimate terminal velocity and coefficient of drag. You can get the relevant dimensions of a quarter from https://en.wikipedia.org/wiki/Quarter_(United_States_coin). Create a Params object with new values of mass and diameter. We don't know v_term, so we'll start with the initial guess 18 m/s. Use make_system to create a System object. Call run_solve_ivp to simulate the system. How does the flight time of the simulation compare to the measurement? Try a few different values of v_term and see if you can get the simulated flight time close to 19.1 seconds. Optionally, write an error function and use root_scalar to improve your estimate. Use your best estimate of v_term to compute C_d. Note: I fabricated the observed flight time, so don't take the results of this exercise too seriously. End of explanation
7,359
Given the following text description, write Python code to implement the functionality described below step by step Description: K-Means Clustering Example Let's make some fake data that includes people clustered by income and age, randomly Step1: We'll use k-means to rediscover these clusters in unsupervised learning
Python Code: from numpy import random, array #Create fake income/age clusters for N people in k clusters def createClusteredData(N, k): random.seed(10) pointsPerCluster = float(N)/k X = [] for i in range (k): incomeCentroid = random.uniform(20000.0, 200000.0) ageCentroid = random.uniform(20.0, 70.0) for j in range(int(pointsPerCluster)): X.append([random.normal(incomeCentroid, 10000.0), random.normal(ageCentroid, 2.0)]) X = array(X) return X Explanation: K-Means Clustering Example Let's make some fake data that includes people clustered by income and age, randomly: End of explanation %matplotlib inline from sklearn.cluster import KMeans import matplotlib.pyplot as plt from sklearn.preprocessing import scale from numpy import random, float data = createClusteredData(100, 5) model = KMeans(n_clusters=5) # Note I'm scaling the data to normalize it! Important for good results. model = model.fit(scale(data)) # We can look at the clusters each data point was assigned to print(model.labels_) # And we'll visualize it: plt.figure(figsize=(8, 6)) plt.scatter(data[:,0], data[:,1], c=model.labels_.astype(float)) plt.show() Explanation: We'll use k-means to rediscover these clusters in unsupervised learning: End of explanation
7,360
Given the following text description, write Python code to implement the functionality described below step by step Description: Python Flight Mechanics Engine This installs pyfme to be run in this online notebook Step1: Aircraft In order to perform a simulation, the first thing we need is an aircraft Step2: Aircraft will provide the simulator the forces, moments and inertial properties in order to perform the integration of the dynamic system equations Step3: For the aircraft, in order to calculate its forces and moments it is necessary to set the controls values within the limits Step4: but also to provide and environment (ie. atmosphere, winds, gravity) and the aircraft state, which will also determine the aerodynamic contribution. Environment Step5: The atmosphere, wind and gravity model make up the environment Step6: The environment has an update method which given the state (ie. position, altitude...) updates the environment variables (ie. density, wind magnitude, gravity force...) Step7: State Even if the state can be set manually by giving the position, attitude, velocity, angular velocities... Most of the times, the user will want to trim the aircraft in a stationary condition. The aircraft controls to flight in that condition will be also provided by the trimmer. Step8: Now, all the necessary elements in order to calculate forces and moments are available Step9: The aircraft is trimmed indeed Step10: Constant Controls Let's set the controls for the aircraft during the simulation. As a first step we will set them constant and equal to the trimmed values. Step11: Once the simulation is set, the propagation can be performed Step12: The results are returned in a DataFrame Step13: Doublet Let's set the controls for the aircraft during the simulation. As a first step we will set them constant and equal to the trimmed values. Step14: Once the simulation is set, the propagation can be performed Step15: Propagating only one time step Step16: We can propagate for one time step even once the simulation has been propagated before Step17: Notice that results will include the previous timesteps as well as the last one. To get just the last one one can use pandas loc or iloc
Python Code: !pip install git+https://github.com/AeroPython/PyFME.git Explanation: Python Flight Mechanics Engine This installs pyfme to be run in this online notebook End of explanation from pyfme.aircrafts import Cessna172 aircraft = Cessna172() Explanation: Aircraft In order to perform a simulation, the first thing we need is an aircraft: End of explanation print(f"Aircraft mass: {aircraft.mass} kg") print(f"Aircraft inertia tensor: \n {aircraft.inertia} kg/m²") print(f"forces: {aircraft.total_forces} N") print(f"moments: {aircraft.total_moments} N·m") Explanation: Aircraft will provide the simulator the forces, moments and inertial properties in order to perform the integration of the dynamic system equations: End of explanation print(aircraft.controls) print(aircraft.control_limits) Explanation: For the aircraft, in order to calculate its forces and moments it is necessary to set the controls values within the limits: End of explanation from pyfme.environment.atmosphere import ISA1976 from pyfme.environment.wind import NoWind from pyfme.environment.gravity import VerticalConstant atmosphere = ISA1976() gravity = VerticalConstant() wind = NoWind() Explanation: but also to provide and environment (ie. atmosphere, winds, gravity) and the aircraft state, which will also determine the aerodynamic contribution. Environment End of explanation from pyfme.environment import Environment environment = Environment(atmosphere, gravity, wind) Explanation: The atmosphere, wind and gravity model make up the environment: End of explanation help(environment.update) Explanation: The environment has an update method which given the state (ie. position, altitude...) updates the environment variables (ie. density, wind magnitude, gravity force...) End of explanation from pyfme.utils.trimmer import steady_state_trim help(steady_state_trim) from pyfme.models.state.position import EarthPosition pos = EarthPosition(x=0, y=0, height=1000) psi = 0.5 # rad TAS = 45 # m/s controls0 = {'delta_elevator': 0, 'delta_aileron': 0, 'delta_rudder': 0, 'delta_t': 0.5} trimmed_state, trimmed_controls = steady_state_trim( aircraft, environment, pos, psi, TAS, controls0 ) trimmed_state trimmed_controls Explanation: State Even if the state can be set manually by giving the position, attitude, velocity, angular velocities... Most of the times, the user will want to trim the aircraft in a stationary condition. The aircraft controls to flight in that condition will be also provided by the trimmer. End of explanation # Environment conditions for the current state: environment.update(trimmed_state) # Forces and moments calculation: forces, moments = aircraft.calculate_forces_and_moments(trimmed_state, environment, controls0) forces, moments Explanation: Now, all the necessary elements in order to calculate forces and moments are available End of explanation from pyfme.models import EulerFlatEarth system = EulerFlatEarth(t0=0, full_state=trimmed_state) Explanation: The aircraft is trimmed indeed: the total forces and moments (aerodynamics + gravity + thrust) are zero Simulation In order to simulate the dynamics of the aircraft under certain inputs in an environment, the user can set up a simulation using a dynamic system: End of explanation from pyfme.utils.input_generator import Constant controls = controls = { 'delta_elevator': Constant(trimmed_controls['delta_elevator']), 'delta_aileron': Constant(trimmed_controls['delta_aileron']), 'delta_rudder': Constant(trimmed_controls['delta_rudder']), 'delta_t': Constant(trimmed_controls['delta_t']) } from pyfme.simulator import Simulation sim = Simulation(aircraft, system, environment, controls) Explanation: Constant Controls Let's set the controls for the aircraft during the simulation. As a first step we will set them constant and equal to the trimmed values. End of explanation results = sim.propagate(10) Explanation: Once the simulation is set, the propagation can be performed: End of explanation results %matplotlib inline kwargs = {'marker': '.', 'subplots': True, 'sharex': True, 'figsize': (12, 6)} results.plot(y=['x_earth', 'y_earth', 'height'], **kwargs); results.plot(y=['psi', 'theta', 'phi'], **kwargs); results.plot(y=['v_north', 'v_east', 'v_down'], **kwargs); results.plot(y=['p', 'q', 'r'], **kwargs); results.plot(y=['alpha', 'beta', 'TAS'], **kwargs); results.plot(y=['Fx', 'Fy', 'Fz'], **kwargs); results.plot(y=['Mx', 'My', 'Mz'], **kwargs); results.plot(y=['elevator', 'aileron', 'rudder', 'thrust'], **kwargs); Explanation: The results are returned in a DataFrame: End of explanation from pyfme.utils.input_generator import Doublet de0 = trimmed_controls['delta_elevator'] controls = controls = { 'delta_elevator': Doublet(t_init=2, T=1, A=0.1, offset=de0), 'delta_aileron': Constant(trimmed_controls['delta_aileron']), 'delta_rudder': Constant(trimmed_controls['delta_rudder']), 'delta_t': Constant(trimmed_controls['delta_t']) } sim = Simulation(aircraft, system, environment, controls) Explanation: Doublet Let's set the controls for the aircraft during the simulation. As a first step we will set them constant and equal to the trimmed values. End of explanation results = sim.propagate(90) results.plot(y=['x_earth', 'y_earth', 'height'], **kwargs); results.plot(y=['psi', 'theta', 'phi'], **kwargs); results.plot(y=['v_north', 'v_east', 'v_down'], **kwargs); results.plot(y=['p', 'q', 'r'], **kwargs); results.plot(y=['alpha', 'beta', 'TAS'], **kwargs); results.plot(y=['Fx', 'Fy', 'Fz'], **kwargs); results.plot(y=['Mx', 'My', 'Mz'], **kwargs); results.plot(y=['elevator', 'aileron', 'rudder', 'thrust'], **kwargs); Explanation: Once the simulation is set, the propagation can be performed: End of explanation dt = 0.05 # seconds sim = Simulation(aircraft, system, environment, controls, dt) results = sim.propagate(0.5) results Explanation: Propagating only one time step End of explanation results = sim.propagate(sim.time+dt) results Explanation: We can propagate for one time step even once the simulation has been propagated before: End of explanation results.iloc[-1] # last time step results.loc[sim.time] # results for current simulation time Explanation: Notice that results will include the previous timesteps as well as the last one. To get just the last one one can use pandas loc or iloc: End of explanation
7,361
Given the following text description, write Python code to implement the functionality described below step by step Description: Post Training Integer Quantization <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https Step1: Train and export the model Step2: For the example, we only trained the model for a single epoch, so it only trains to ~96% accuracy. Convert to a TensorFlow Lite model The savedmodel directory is named with a timestamp. Select the most recent one Step3: Using the Python TFLiteConverter, the saved model can be converted into a TensorFlow Lite model. First load the model using the TFLiteConverter Step4: Write it out to a .tflite file Step5: To instead quantize the model on export, first set the optimizations flag to optimize for size Step6: Now, construct and provide a representative dataset, this is used to get the dynamic range of activations. Step7: Finally, convert the model like usual. Note, by default the converted model will still use float input and outputs for invocation convenience. Step8: Note how the resulting file is approximately 1/4 the size. Step9: Run the TensorFlow Lite models We can run the TensorFlow Lite model using the Python TensorFlow Lite Interpreter. Load the test data First, let's load the MNIST test data to feed to the model Step10: Load the model into the interpreters Step11: Test the models on one image Step12: Evaluate the models Step13: We can repeat the evaluation on the fully quantized model to obtain
Python Code: ! pip uninstall -y tensorflow ! pip install -U tf-nightly import tensorflow as tf tf.enable_eager_execution() ! git clone --depth 1 https://github.com/tensorflow/models import sys import os if sys.version_info.major >= 3: import pathlib else: import pathlib2 as pathlib # Add `models` to the python path. models_path = os.path.join(os.getcwd(), "models") sys.path.append(models_path) Explanation: Post Training Integer Quantization <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/lite/tutorials/post_training_quant.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/tutorials/post_training_quant.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a> </td> </table> Overview TensorFlow Lite now supports converting an entire model (weights and activations) to 8-bit during model conversion from TensorFlow to TensorFlow Lite's flat buffer format. This results in a 4x reduction in model size and a 3 to 4x performance improvement on CPU performance. In addition, this fully quantized model can be consumed by integer-only hardware accelerators. In contrast to post-training "on-the-fly" quantization , which only stores weights as 8-bit ints, in this technique all weights and activations are quantized statically during model conversion. In this tutorial, we train an MNIST model from scratch, check its accuracy in TensorFlow, and then convert the saved model into a Tensorflow Lite flatbuffer with full quantization. We finally check the accuracy of the converted model and compare it to the original saved model. We run the training script mnist.py from Tensorflow official MNIST tutorial. Building an MNIST model Setup End of explanation saved_models_root = "/tmp/mnist_saved_model" # The above path addition is not visible to subprocesses, add the path for the subprocess as well. # Note: channels_last is required here or the conversion may fail. !PYTHONPATH={models_path} python models/official/mnist/mnist.py --train_epochs=1 --export_dir {saved_models_root} --data_format=channels_last Explanation: Train and export the model End of explanation saved_model_dir = str(sorted(pathlib.Path(saved_models_root).glob("*"))[-1]) saved_model_dir Explanation: For the example, we only trained the model for a single epoch, so it only trains to ~96% accuracy. Convert to a TensorFlow Lite model The savedmodel directory is named with a timestamp. Select the most recent one: End of explanation import tensorflow as tf tf.enable_eager_execution() tf.logging.set_verbosity(tf.logging.DEBUG) converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_dir) tflite_model = converter.convert() Explanation: Using the Python TFLiteConverter, the saved model can be converted into a TensorFlow Lite model. First load the model using the TFLiteConverter: End of explanation tflite_models_dir = pathlib.Path("/tmp/mnist_tflite_models/") tflite_models_dir.mkdir(exist_ok=True, parents=True) tflite_model_file = tflite_models_dir/"mnist_model.tflite" tflite_model_file.write_bytes(tflite_model) Explanation: Write it out to a .tflite file: End of explanation tf.logging.set_verbosity(tf.logging.INFO) converter.optimizations = [tf.lite.Optimize.DEFAULT] Explanation: To instead quantize the model on export, first set the optimizations flag to optimize for size: End of explanation mnist_train, _ = tf.keras.datasets.mnist.load_data() images = tf.cast(mnist_train[0], tf.float32)/255.0 mnist_ds = tf.data.Dataset.from_tensor_slices((images)).batch(1) def representative_data_gen(): for input_value in mnist_ds.take(100): yield [input_value] converter.representative_dataset = representative_data_gen Explanation: Now, construct and provide a representative dataset, this is used to get the dynamic range of activations. End of explanation tflite_quant_model = converter.convert() tflite_model_quant_file = tflite_models_dir/"mnist_model_quant.tflite" tflite_model_quant_file.write_bytes(tflite_quant_model) Explanation: Finally, convert the model like usual. Note, by default the converted model will still use float input and outputs for invocation convenience. End of explanation !ls -lh {tflite_models_dir} Explanation: Note how the resulting file is approximately 1/4 the size. End of explanation import numpy as np _, mnist_test = tf.keras.datasets.mnist.load_data() images, labels = tf.cast(mnist_test[0], tf.float32)/255.0, mnist_test[1] mnist_ds = tf.data.Dataset.from_tensor_slices((images, labels)).batch(1) Explanation: Run the TensorFlow Lite models We can run the TensorFlow Lite model using the Python TensorFlow Lite Interpreter. Load the test data First, let's load the MNIST test data to feed to the model: End of explanation interpreter = tf.lite.Interpreter(model_path=str(tflite_model_file)) interpreter.allocate_tensors() interpreter_quant = tf.lite.Interpreter(model_path=str(tflite_model_quant_file)) interpreter_quant.allocate_tensors() Explanation: Load the model into the interpreters End of explanation for img, label in mnist_ds: break interpreter.set_tensor(interpreter.get_input_details()[0]["index"], img) interpreter.invoke() predictions = interpreter.get_tensor( interpreter.get_output_details()[0]["index"]) import matplotlib.pylab as plt plt.imshow(img[0]) template = "True:{true}, predicted:{predict}" _ = plt.title(template.format(true= str(label[0].numpy()), predict=str(predictions[0]))) plt.grid(False) interpreter_quant.set_tensor( interpreter_quant.get_input_details()[0]["index"], img) interpreter_quant.invoke() predictions = interpreter_quant.get_tensor( interpreter_quant.get_output_details()[0]["index"]) plt.imshow(img[0]) template = "True:{true}, predicted:{predict}" _ = plt.title(template.format(true= str(label[0].numpy()), predict=str(predictions[0]))) plt.grid(False) Explanation: Test the models on one image End of explanation def eval_model(interpreter, mnist_ds): total_seen = 0 num_correct = 0 input_index = interpreter.get_input_details()[0]["index"] output_index = interpreter.get_output_details()[0]["index"] for img, label in mnist_ds: total_seen += 1 interpreter.set_tensor(input_index, img) interpreter.invoke() predictions = interpreter.get_tensor(output_index) if predictions == label.numpy(): num_correct += 1 if total_seen % 500 == 0: print("Accuracy after %i images: %f" % (total_seen, float(num_correct) / float(total_seen))) return float(num_correct) / float(total_seen) print(eval_model(interpreter, mnist_ds)) Explanation: Evaluate the models End of explanation # NOTE: Colab runs on server CPUs. At the time of writing this, TensorFlow Lite # doesn't have super optimized server CPU kernels. For this reason this may be # slower than the above float interpreter. But for mobile CPUs, considerable # speedup can be observed. print(eval_model(interpreter_quant, mnist_ds)) Explanation: We can repeat the evaluation on the fully quantized model to obtain: End of explanation
7,362
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting crime in San Francisco with machine learning (Kaggle 2015) Notice Step1: Raw data Step2: View composing & feature engineering Step3: Garbage Collection Step4: Draw samples Step5: Stochastic Gradient Descent (SGD) SGD with Kernel Approximation RBF Kernel by Monte Carlo approximation of its Fourier transform Step6: Parameter Search Step7: Training Step8: Classification Step9: Random Forest Classifier
Python Code: import datetime import gc import zipfile import matplotlib as mpl import numpy as np import pandas as pd import seaborn as sns import sklearn as sk from pandas.tseries.holiday import USFederalHolidayCalendar from sklearn.cross_validation import KFold, cross_val_score from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import SGDClassifier from sklearn.grid_search import GridSearchCV from sklearn.kernel_approximation import RBFSampler from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler, LabelEncoder, LabelBinarizer from sklearn_pandas import DataFrameMapper %matplotlib inline DATADIR = "./data/" Explanation: Predicting crime in San Francisco with machine learning (Kaggle 2015) Notice: sklearn-pandas should be checked out from latest master branch ~~~ $ pip2 install --upgrade git+https://github.com/paulgb/sklearn-pandas.git@master ~~~ Requirements End of explanation train, test = pd.DataFrame(), pd.DataFrame() with zipfile.ZipFile(DATADIR + "train.csv.zip", "r") as zf: train = pd.read_csv(zf.open("train.csv"), parse_dates=['Dates']) with zipfile.ZipFile(DATADIR + "test.csv.zip", "r") as zf: test = pd.read_csv(zf.open("test.csv"), parse_dates=['Dates']) train.head() test.head() Explanation: Raw data End of explanation train_view, test_view = pd.DataFrame(), pd.DataFrame() train_view["category"] = train["Category"] for (view, data) in [(train_view, train), (test_view, test)]: view["district"] = data["PdDistrict"] view["hour"] = data["Dates"].map(lambda x: x.hour) view["weekday"] = data["Dates"].map(lambda x: x.weekday()) view["day"] = data["Dates"].map(lambda x: x.day) view["dayofyear"] = data["Dates"].map(lambda x: x.dayofyear) view["month"] = data["Dates"].map(lambda x: x.month) view["year"] = data["Dates"].map(lambda x: x.year) view["lon"] = data["X"] view["lat"] = data["Y"] view["address"] = data["Address"].map(lambda x: x.split(" ", 1)[1] if x.split(" ", 1)[0].isdigit() else x) view["corner"] = data["Address"].map(lambda x: "/" in x) days_off = USFederalHolidayCalendar().holidays(start='2003-01-01', end='2015-05-31').to_pydatetime() for (view, data) in [(train_view, train), (test_view, test)]: view["holiday"] = data["Dates"].map(lambda x: datetime.datetime(x.year,x.month,x.day) in days_off) view["workhour"] = data["Dates"].map(lambda x: x.hour in range(9,17)) view["sunlight"] = data["Dates"].map(lambda x: x.hour in range(7,19)) train_view.head() test_view.head() Explanation: View composing & feature engineering End of explanation del train del test gc.collect() target_mapper = DataFrameMapper([ ("category", LabelEncoder()), ]) y = target_mapper.fit_transform(train_view.copy()) print "sample:", y[0] print "shape:", y.shape data_mapper = DataFrameMapper([ ("district", LabelBinarizer()), ("hour", StandardScaler()), ("weekday", StandardScaler()), ("day", StandardScaler()), ("dayofyear", StandardScaler()), ("month", StandardScaler()), ("year", StandardScaler()), ("lon", StandardScaler()), ("lat", StandardScaler()), ("address", [LabelEncoder(), StandardScaler()]), ("corner", LabelEncoder()), ("holiday", LabelEncoder()), ("workhour", LabelEncoder()), ("sunlight", LabelEncoder()), ]) data_mapper.fit(pd.concat([train_view.copy(), test_view.copy()])) X = data_mapper.transform(train_view.copy()) X_test = data_mapper.transform(test_view.copy()) print "sample:", X[0] print "shape:", X.shape Explanation: Garbage Collection End of explanation samples = np.random.permutation(np.arange(X.shape[0]))[:100000] X_sample = X[samples] y_sample = y[samples] y_sample = np.reshape(y_sample, -1) y = np.reshape(y, -1) Explanation: Draw samples End of explanation sgd_rbf = make_pipeline(RBFSampler(gamma=0.1, random_state=1), SGDClassifier()) Explanation: Stochastic Gradient Descent (SGD) SGD with Kernel Approximation RBF Kernel by Monte Carlo approximation of its Fourier transform End of explanation alpha_range = 10.0**-np.arange(1,7) loss_function = ["hinge", "log", "modified_huber", "squared_hinge", "perceptron"] params = dict( sgdclassifier__alpha=alpha_range, sgdclassifier__loss=loss_function ) %%time grid = GridSearchCV(sgd_rbf, params, cv=10, scoring="accuracy", n_jobs=1) grid.fit(X_sample, y_sample) print "best score:", grid.best_score_ print "parameter:", grid.best_params_ Explanation: Parameter Search End of explanation %%time rbf = RBFSampler(gamma=0.1, random_state=1) rbf.fit(np.concatenate((X, X_test), axis=0)) X_rbf = rbf.transform(X) X_test_rbf = rbf.transform(X_test) %%time sgd = SGDClassifier(loss="log", alpha=0.001, n_iter=1000, n_jobs=-1) sgd.fit(X_rbf, y) Explanation: Training End of explanation results = sgd_predict_proba(X_test_rbf) Explanation: Classification End of explanation %%time rfc = RandomForestClassifier(max_depth=16,n_estimators=1024) cross_val_score(rfc, X, y, cv=10, scoring="accuracy", n_jobs=-1).mean() Explanation: Random Forest Classifier End of explanation
7,363
Given the following text description, write Python code to implement the functionality described below step by step Description: server/udp/podCommands.js - from node.js /JavaScript to Python (object) Step1: The reactGS folder "mimics" the actual react-groundstation github repository, only copying the file directory structure, but the source code itself (which is a lot) isn't completely copied over. I wanted to keep these scripts/notebooks/files built on top of that github repository to be separate from the actual working code. Step2: node.js/(JavaScript) to json; i.e. node.js/(JavaScript) $\to$ json Make a copy of server/udp/podCommands.js. In this copy, comment out var chalk = require('chalk') (this is the only thing you have to do manually). Run this in the directory containing your copy of podCommands.js Step3: Dirty parsing of podCommands.js and the flight control parameters Step4: So the structure of our result is as follows Step6: Going to .csv @nuttwerx and @ernestyalumni decided upon separating the multiple entries in a field by the semicolon ";" Step7: Add the headers in manually Step8: The csv fields format is as follows
Python Code: # find out where we are on the file directory import os, sys print( os.getcwd()) print( os.listdir(os.getcwd())) Explanation: server/udp/podCommands.js - from node.js /JavaScript to Python (object) End of explanation wherepodCommandsis = os.getcwd()+'/reactGS/server/udp/' print(wherepodCommandsis) Explanation: The reactGS folder "mimics" the actual react-groundstation github repository, only copying the file directory structure, but the source code itself (which is a lot) isn't completely copied over. I wanted to keep these scripts/notebooks/files built on top of that github repository to be separate from the actual working code. End of explanation import json f_podCmds_json = open(wherepodCommandsis+'podCmds_lst.json','rb') rawjson_podCmds = f_podCmds_json.read() f_podCmds_json.close() print(type(rawjson_podCmds)) podCmds_lst=json.loads(rawjson_podCmds) print(type(podCmds_lst)) print(len(podCmds_lst)) # there are 104 available commands for the pod! for cmd in podCmds_lst: print cmd Explanation: node.js/(JavaScript) to json; i.e. node.js/(JavaScript) $\to$ json Make a copy of server/udp/podCommands.js. In this copy, comment out var chalk = require('chalk') (this is the only thing you have to do manually). Run this in the directory containing your copy of podCommands.js: node traverse_podCommands.js This should generate a json file podCmds_lst.json Available podCommands as a Python list; json to Python list, i.e. json $\to$ Python list End of explanation f_podCmds = open(wherepodCommandsis+'podCommands.js','rb') raw_podCmds = f_podCmds.read() f_podCmds.close() print(type(raw_podCmds)) print(len(raw_podCmds)) # get the name of the functions cmdnameslst = [func[:func.find("(")].strip() for func in raw_podCmds.split("function ")] funcparamslst = [func[func.find("(")+1:func.find(")")] if func[func.find("(")+1:func.find(")")] is not '' else None for func in raw_podCmds.split("function ")] #raw_podCmds.split("function ")[3][ raw_podCmds.split("function ")[3].find("(")+1:raw_podCmds.split("function ")[3].find(")")] # more parsing of this list of strings funcparamslst_cleaned = [] for param in funcparamslst: if param is None: funcparamslst_cleaned.append(None) else: funcparamslst_cleaned.append( param.strip().split(',') ) print(len(raw_podCmds.split("function ")) ) # 106 commands # get the index value (e.g. starts at position 22) of where "udp.tx.transmitPodCommand" starts, treating it as a string #whereisudptransmit = [func.find("udp.tx.transmitPodCommand(") for func in raw_podCmds.split("function ")] whereisudptransmit = [] for func in raw_podCmds.split("function "): val = func.find("udp.tx.transmitPodCommand(") if val is not -1: if func.find("// ",val-4) is not -1 or func.find("// udp",val-4) is not -1: whereisudptransmit.append(None) else: whereisudptransmit.append(val) else: whereisudptransmit.append(None) #whereisudptransmit = [func.find("udp.tx.transmitPodCommand(") for func in raw_podCmds.split("function ")] # remove -1 values #whereisudptransmit = filter(lambda x : x != -1, whereisudptransmit) rawParams=[funcstr[ funcstr.find("(",val)+1:funcstr.find(")",val)] if val is not None else None for funcstr, val in zip(raw_podCmds.split("function "), whereisudptransmit)] funcparamslst_cleaned[:10] raw_podCmds.split("function ")[4].find("// ",116-4); # more parsing of this list of strings cleaningParams = [] for rawparam in rawParams: if rawparam is None: cleaningParams.append(None) else: cleanParam = [] cleanParam.append( rawparam.split(',')[0].strip("'") ) for strval in rawparam.split(',')[1:]: strval2 = strval.strip() try: strval2 = int(strval2,16) strval2 = hex(strval2) except ValueError: strval2 cleanParam.append(strval2) cleaningParams.append(cleanParam) cleaningParams[:10] # get the name of the functions #[func[:func.find("(")] # if func.find("()") is not -1 else None for func in raw_podCmds.split("function ")]; cmdnameslst = [func[:func.find("(")].strip() for func in raw_podCmds.split("function ")] # each node js function has its arguments; do that first podfunclst = zip(cmdnameslst, funcparamslst_cleaned) print(len(podfunclst)) podfunclst[:10]; # each node js function has its arguments; do that first podCommandparams = zip(podfunclst, cleaningParams) print(len(podCommandparams)) podCommandparams[-2] Explanation: Dirty parsing of podCommands.js and the flight control parameters End of explanation podCommandparams[:10] try: import CPickle as pickle except ImportError: import pickle podCommandparamsfile = open("podCommandparams.pkl",'wb') pickle.dump( podCommandparams , podCommandparamsfile ) podCommandparamsfile.close() # open up a pickle file like so: podCommandparamsfile_recover = open("podCommandparams.pkl",'rb') podCommandparams_recover = pickle.load(podCommandparamsfile_recover) podCommandparamsfile_recover.close() podCommandparams_recover[:10] Explanation: So the structure of our result is as follows: Python tuples (each of size 2 for each of the tuples) ( (Name of pod command as a string, None if there are no function parameters or Python list of function arguments), Python list [ Subsystem name as a string, paramter1 as a hex value, paramter2 as a hex value, paramter3 as a hex value, paramter4 as a hex value] ) Notice that in the original code, there's some TO DO's still left (eek!) so that those udp.tx.transmitPodCommand is commented out or left as TODO, and some are dependent upon arguments in the function (and thus will change, the parameter is a variable). End of explanation tocsv = [] for cmd in podCommandparams_recover: name = cmd[0][0] funcparam = cmd[0][1] if funcparam is None: fparam = None else: fparam = ";".join(funcparam) udpparam = cmd[1] if udpparam is None: uname = None uparam = None else: uname = udpparam[0] uparam = ";".join( udpparam[1:] ) tocsv.append([name,fparam,uname,uparam]) Explanation: Going to .csv @nuttwerx and @ernestyalumni decided upon separating the multiple entries in a field by the semicolon ";": End of explanation header = ["Command name","Function args", "Pod Node", "Command Args"] tocsv.insert(0,header) Explanation: Add the headers in manually: 1 = Command name; 2 = Function args; 3 = Pod Node; 4 = Command Args End of explanation import csv f_podCommands_tocsv = open("podCommands.csv",'w') tocsv_writer = csv.writer( f_podCommands_tocsv ) tocsv_writer.writerows(tocsv) f_podCommands_tocsv.close() #tocsv.insert(0,header) no need #tocsv[:10] no need Explanation: The csv fields format is as follows: (function name) , (function arguments (None is there are none)) , (UDP transmit name (None is there are no udp transmit command)), (UDP transmit parameters, 4 of them, separated by semicolon, or None if there are no udp transmit command ) End of explanation
7,364
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 2 Modeling and Simulation in Python Copyright 2021 Allen Downey License Step1: This chapter presents a simple model of a bike share system and demonstrates the features of Python we'll use to develop simulations of real-world systems. Along the way, we'll make decisions about how to model the system. In the next chapter we'll review these decisions and gradually improve the model. Modeling a Bike Share System Imagine a bike share system for students traveling between Olin College and Wellesley College, which are about 3 miles apart in eastern Massachusetts. Suppose the system contains 12 bikes and two bike racks, one at Olin and one at Wellesley, each with the capacity to hold 12 bikes. As students arrive, check out a bike, and ride to the other campus, the number of bikes in each location changes. In the simulation, we'll need to keep track of where the bikes are. To do that, we'll use a function called State, which is defined in the ModSim library. Step2: The expressions in parentheses are keyword arguments. They create two variables, olin and wellesley, and give them values. Then we call the State function. The result is a State object, which is a collection of state variables. In this example, the state variables represent the number of bikes at each location. The initial values are 10 and 2, indicating that there are 10 bikes at Olin and 2 at Wellesley. The State object is assigned to a new variable named bikeshare. We can read the variables inside a State object using the dot operator, like this Step3: And this Step4: Or, to display the state variables and their values, you can just type the name of the object Step5: These values make up the state of the system. The ModSim library provides a function called show that displays a State object as a table. Step6: You don't have to use show, but I think it looks better. We can update the state by assigning new values to the variables. For example, if a student moves a bike from Olin to Wellesley, we can figure out the new values and assign them Step7: Or we can use update operators, -= and +=, to subtract 1 from olin and add 1 to wellesley Step8: The result is the same either way. Defining functions So far we have used functions defined in NumPy and ModSim. Now we're going to define our own function. When you are developing code in Jupyter, it is often efficient to write a few lines of code, test them to confirm they do what you intend, and then use them to define a new function. For example, these lines move a bike from Olin to Wellesley Step9: Rather than repeat them every time a bike moves, we can define a new function Step10: def is a special word in Python that indicates we are defining a new function. The name of the function is bike_to_wellesley. The empty parentheses indicate that this function requires no additional information when it runs. The colon indicates the beginning of an indented code block. The next two lines are the body of the function. They have to be indented; by convention, the indentation is 4 spaces. When you define a function, it has no immediate effect. The body of the function doesn't run until you call the function. Here's how to call this function Step11: When you call the function, it runs the statements in the body, which update the variables of the bikeshare object; you can check by displaying the new state. Step12: When you call a function, you have to include the parentheses. If you leave them out, you get this Step13: This result indicates that bike_to_wellesley is a function. You don't have to know what __main__ means, but if you see something like this, it probably means that you looked up a function but you didn't actually call it. So don't forget the parentheses. Print statements As you write more complicated programs, it is easy to lose track of what is going on. One of the most useful tools for debugging is the print statement, which displays text in the Jupyter notebook. Normally when Jupyter runs the code in a cell, it displays the value of the last line of code. For example, if you run Step14: Jupyter runs both lines, but it only displays the value of the second. If you want to display more than one value, you can use print statements Step15: When you call the print function, you can put a variable name in parentheses, as in the previous example, or you can provide a sequence of variables separated by commas, like this Step16: Python looks up the values of the variables and displays them; in this example, it displays two values on the same line, with a space between them. Print statements are useful for debugging functions. For example, we can add a print statement to move_bike, like this Step17: Each time we call this version of the function, it displays a message, which can help us keep track of what the program is doing. The message in this example is a string, which is a sequence of letters and other symbols in quotes. Just like bike_to_wellesley, we can define a function that moves a bike from Wellesley to Olin Step18: And call it like this Step19: One benefit of defining functions is that you avoid repeating chunks of code, which makes programs smaller. Another benefit is that the name you give the function documents what it does, which makes programs more readable. If statements The ModSim library provides a function called flip that generates random "coin tosses". When you call it, you provide a probability between 0 and 1, like this Step20: The result is one of two values Step21: If the result from flip is True, the program displays the string 'heads'. Otherwise it does nothing. The syntax for if statements is similar to the syntax for function definitions Step22: Now we can use flip to simulate the arrival of students who want to borrow a bike. Suppose students arrive at the Olin station every 2 minutes, on average. In that case, the chance of an arrival during any one-minute period is 50%, and we can simulate it like this Step23: If students arrive at the Wellesley station every 3 minutes, on average, the chance of an arrival during any one-minute period is 33%, and we can simulate it like this Step24: We can combine these snippets into a function that simulates a time step, which is an interval of time, in this case one minute Step25: Then we can simulate a time step like this Step26: Even though there are no values in parentheses, we have to include them. Parameters The previous version of step is fine if the arrival probabilities never change, but in reality, these probabilities vary over time. So instead of putting the constant values 0.5 and 0.33 in step we can replace them with parameters. Parameters are variables whose values are set when a function is called. Here's a version of step that takes two parameters, p1 and p2 Step27: The values of p1 and p2 are not set inside this function; instead, they are provided when the function is called, like this Step28: The values you provide when you call the function are called arguments. The arguments, 0.5 and 0.33 in this example, get assigned to the parameters, p1 and p2, in order. So running this function has the same effect as Step29: The advantage of using parameters is that you can call the same function many times, providing different arguments each time. Adding parameters to a function is called generalization, because it makes the function more general, that is, less specialized. For loops At some point you will get sick of running cells over and over. Fortunately, there is an easy way to repeat a chunk of code, the for loop. Here's an example Step30: The syntax here should look familiar; the first line ends with a colon, and the lines inside the for loop are indented. The other elements of the loop are Step31: We can create a new, empty TimeSeries like this Step32: And we can add a quantity like this Step33: The number in brackets is the time stamp, also called a label. We can use a TimeSeries inside a for loop to store the results of the simulation Step34: Each time through the loop, we print the value of i and call step, which updates bikeshare. Then we store the number of bikes at Olin in results. We use the loop variable, i, to compute the time stamp, i+1. The first time through the loop, the value of i is 0, so the time stamp is 1. The last time, the value of i is 2, so the time stamp is 3. When the loop exits, results contains 4 time stamps, from 0 through 3, and the number of bikes at Olin at the end of each time step. We can display the TimeSeries like this Step35: The left column is the time stamps; the right column is the quantities (which might be negative, depending on the state of the system). At the bottom, dtype is the type of the data in the TimeSeries; you can ignore this for now. The show function displays a TimeSeries as a table Step36: Plotting results provides a function called plot we can use to plot the results, and the ModSim library provides decorate, which we can use to label the axes and give the figure a title Step37: Summary This chapter introduces the tools we need to run simulations, record the results, and plot them. We used a State object to represent the state of the system. Then we used the flip function and an if statement to simulate a single time step. We used for loop to simulate a series of steps, and a TimeSeries to record the results. Finally, we used plot and decorate to plot the results. In the next chapter, we will extend this simulation to make it a little more realistic. Exercises Exercise Step38: Exercise Step39: Exercise Step40: Under the Hood This section contains additional information about the functions we've used and pointers to their documentation. You don't need to know anything in these sections, so if you are already feeling overwhelmed, you might want to skip them. But if you are curious, read on. State and TimeSeries objects are based on the Series object defined by a the Pandas library. The documentation is at https
Python Code: # install Pint if necessary try: import pint except ImportError: !pip install pint # download modsim.py if necessary from os.path import exists filename = 'modsim.py' if not exists(filename): from urllib.request import urlretrieve url = 'https://raw.githubusercontent.com/AllenDowney/ModSim/main/' local, _ = urlretrieve(url+filename, filename) print('Downloaded ' + local) # import functions from modsim from modsim import * Explanation: Chapter 2 Modeling and Simulation in Python Copyright 2021 Allen Downey License: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International End of explanation bikeshare = State(olin=10, wellesley=2) Explanation: This chapter presents a simple model of a bike share system and demonstrates the features of Python we'll use to develop simulations of real-world systems. Along the way, we'll make decisions about how to model the system. In the next chapter we'll review these decisions and gradually improve the model. Modeling a Bike Share System Imagine a bike share system for students traveling between Olin College and Wellesley College, which are about 3 miles apart in eastern Massachusetts. Suppose the system contains 12 bikes and two bike racks, one at Olin and one at Wellesley, each with the capacity to hold 12 bikes. As students arrive, check out a bike, and ride to the other campus, the number of bikes in each location changes. In the simulation, we'll need to keep track of where the bikes are. To do that, we'll use a function called State, which is defined in the ModSim library. End of explanation bikeshare.olin Explanation: The expressions in parentheses are keyword arguments. They create two variables, olin and wellesley, and give them values. Then we call the State function. The result is a State object, which is a collection of state variables. In this example, the state variables represent the number of bikes at each location. The initial values are 10 and 2, indicating that there are 10 bikes at Olin and 2 at Wellesley. The State object is assigned to a new variable named bikeshare. We can read the variables inside a State object using the dot operator, like this: End of explanation bikeshare.wellesley Explanation: And this: End of explanation bikeshare Explanation: Or, to display the state variables and their values, you can just type the name of the object: End of explanation show(bikeshare) Explanation: These values make up the state of the system. The ModSim library provides a function called show that displays a State object as a table. End of explanation bikeshare.olin = 9 bikeshare.wellesley = 3 Explanation: You don't have to use show, but I think it looks better. We can update the state by assigning new values to the variables. For example, if a student moves a bike from Olin to Wellesley, we can figure out the new values and assign them: End of explanation bikeshare.olin -= 1 bikeshare.wellesley += 1 Explanation: Or we can use update operators, -= and +=, to subtract 1 from olin and add 1 to wellesley: End of explanation bikeshare.olin -= 1 bikeshare.wellesley += 1 Explanation: The result is the same either way. Defining functions So far we have used functions defined in NumPy and ModSim. Now we're going to define our own function. When you are developing code in Jupyter, it is often efficient to write a few lines of code, test them to confirm they do what you intend, and then use them to define a new function. For example, these lines move a bike from Olin to Wellesley: End of explanation def bike_to_wellesley(): bikeshare.olin -= 1 bikeshare.wellesley += 1 Explanation: Rather than repeat them every time a bike moves, we can define a new function: End of explanation bike_to_wellesley() Explanation: def is a special word in Python that indicates we are defining a new function. The name of the function is bike_to_wellesley. The empty parentheses indicate that this function requires no additional information when it runs. The colon indicates the beginning of an indented code block. The next two lines are the body of the function. They have to be indented; by convention, the indentation is 4 spaces. When you define a function, it has no immediate effect. The body of the function doesn't run until you call the function. Here's how to call this function: End of explanation bikeshare Explanation: When you call the function, it runs the statements in the body, which update the variables of the bikeshare object; you can check by displaying the new state. End of explanation bike_to_wellesley Explanation: When you call a function, you have to include the parentheses. If you leave them out, you get this: End of explanation bikeshare.olin bikeshare.wellesley Explanation: This result indicates that bike_to_wellesley is a function. You don't have to know what __main__ means, but if you see something like this, it probably means that you looked up a function but you didn't actually call it. So don't forget the parentheses. Print statements As you write more complicated programs, it is easy to lose track of what is going on. One of the most useful tools for debugging is the print statement, which displays text in the Jupyter notebook. Normally when Jupyter runs the code in a cell, it displays the value of the last line of code. For example, if you run: End of explanation print(bikeshare.olin) print(bikeshare.wellesley) Explanation: Jupyter runs both lines, but it only displays the value of the second. If you want to display more than one value, you can use print statements: End of explanation print(bikeshare.olin, bikeshare.wellesley) Explanation: When you call the print function, you can put a variable name in parentheses, as in the previous example, or you can provide a sequence of variables separated by commas, like this: End of explanation def bike_to_wellesley(): print('Moving a bike to Wellesley') bikeshare.olin -= 1 bikeshare.wellesley += 1 Explanation: Python looks up the values of the variables and displays them; in this example, it displays two values on the same line, with a space between them. Print statements are useful for debugging functions. For example, we can add a print statement to move_bike, like this: End of explanation def bike_to_olin(): print('Moving a bike to Olin') bikeshare.wellesley -= 1 bikeshare.olin += 1 Explanation: Each time we call this version of the function, it displays a message, which can help us keep track of what the program is doing. The message in this example is a string, which is a sequence of letters and other symbols in quotes. Just like bike_to_wellesley, we can define a function that moves a bike from Wellesley to Olin: End of explanation bike_to_olin() Explanation: And call it like this: End of explanation flip(0.7) Explanation: One benefit of defining functions is that you avoid repeating chunks of code, which makes programs smaller. Another benefit is that the name you give the function documents what it does, which makes programs more readable. If statements The ModSim library provides a function called flip that generates random "coin tosses". When you call it, you provide a probability between 0 and 1, like this: End of explanation if flip(0.5): print('heads') Explanation: The result is one of two values: True with probability 0.7 (in this example) or False with probability 0.3. If you run flip like this 100 times, you should get True about 70 times and False about 30 times. But the results are random, so they might differ from these expectations. True and False are special values defined by Python. Note that they are not strings. There is a difference between True, which is a special value, and 'True', which is a string. True and False are called boolean values because they are related to Boolean algebra (https://modsimpy.com/boolean). We can use boolean values to control the behavior of the program, using an if statement: End of explanation if flip(0.5): print('heads') else: print('tails') Explanation: If the result from flip is True, the program displays the string 'heads'. Otherwise it does nothing. The syntax for if statements is similar to the syntax for function definitions: the first line has to end with a colon, and the lines inside the if statement have to be indented. Optionally, you can add an else clause to indicate what should happen if the result is False: End of explanation if flip(0.5): bike_to_wellesley() Explanation: Now we can use flip to simulate the arrival of students who want to borrow a bike. Suppose students arrive at the Olin station every 2 minutes, on average. In that case, the chance of an arrival during any one-minute period is 50%, and we can simulate it like this: End of explanation if flip(0.33): bike_to_olin() Explanation: If students arrive at the Wellesley station every 3 minutes, on average, the chance of an arrival during any one-minute period is 33%, and we can simulate it like this: End of explanation def step(): if flip(0.5): bike_to_wellesley() if flip(0.33): bike_to_olin() Explanation: We can combine these snippets into a function that simulates a time step, which is an interval of time, in this case one minute: End of explanation step() Explanation: Then we can simulate a time step like this: End of explanation def step(p1, p2): if flip(p1): bike_to_wellesley() if flip(p2): bike_to_olin() Explanation: Even though there are no values in parentheses, we have to include them. Parameters The previous version of step is fine if the arrival probabilities never change, but in reality, these probabilities vary over time. So instead of putting the constant values 0.5 and 0.33 in step we can replace them with parameters. Parameters are variables whose values are set when a function is called. Here's a version of step that takes two parameters, p1 and p2: End of explanation step(0.5, 0.33) Explanation: The values of p1 and p2 are not set inside this function; instead, they are provided when the function is called, like this: End of explanation p1 = 0.5 p2 = 0.33 if flip(p1): bike_to_wellesley() if flip(p2): bike_to_olin() Explanation: The values you provide when you call the function are called arguments. The arguments, 0.5 and 0.33 in this example, get assigned to the parameters, p1 and p2, in order. So running this function has the same effect as: End of explanation for i in range(3): print(i) bike_to_wellesley() Explanation: The advantage of using parameters is that you can call the same function many times, providing different arguments each time. Adding parameters to a function is called generalization, because it makes the function more general, that is, less specialized. For loops At some point you will get sick of running cells over and over. Fortunately, there is an easy way to repeat a chunk of code, the for loop. Here's an example: End of explanation bikeshare = State(olin=10, wellesley=2) Explanation: The syntax here should look familiar; the first line ends with a colon, and the lines inside the for loop are indented. The other elements of the loop are: The words for and in are special words we have to use in a for loop. range is a Python function we're using here to control the number of times the loop runs. i is a loop variable that gets created when the for loop runs. When this loop runs, it runs the statements inside the loop three times. The first time, the value of i is 0; the second time, it is 1; the third time, it is 2. Each time through the loop, it prints the value of i and moves one bike Olin to Wellesley. TimeSeries When we run a simulation, we often want to save the results for later analysis. The ModSim library provides a TimeSeries object for this purpose. A TimeSeries contains a sequence of time stamps and a corresponding sequence of quantities. In this example, the time stamps are integers representing minutes, and the quantities are the number of bikes at one location. Since we have moved a number of bikes around, let's start again with a new State object. End of explanation results = TimeSeries() Explanation: We can create a new, empty TimeSeries like this: End of explanation results[0] = bikeshare.olin Explanation: And we can add a quantity like this: End of explanation for i in range(3): print(i) step(0.6, 0.6) results[i+1] = bikeshare.olin Explanation: The number in brackets is the time stamp, also called a label. We can use a TimeSeries inside a for loop to store the results of the simulation: End of explanation results Explanation: Each time through the loop, we print the value of i and call step, which updates bikeshare. Then we store the number of bikes at Olin in results. We use the loop variable, i, to compute the time stamp, i+1. The first time through the loop, the value of i is 0, so the time stamp is 1. The last time, the value of i is 2, so the time stamp is 3. When the loop exits, results contains 4 time stamps, from 0 through 3, and the number of bikes at Olin at the end of each time step. We can display the TimeSeries like this: End of explanation show(results) Explanation: The left column is the time stamps; the right column is the quantities (which might be negative, depending on the state of the system). At the bottom, dtype is the type of the data in the TimeSeries; you can ignore this for now. The show function displays a TimeSeries as a table: End of explanation results.plot() decorate(title='Olin-Wellesley Bikeshare', xlabel='Time step (min)', ylabel='Number of bikes') Explanation: Plotting results provides a function called plot we can use to plot the results, and the ModSim library provides decorate, which we can use to label the axes and give the figure a title: End of explanation bikeshare = State(olin=10, wellesley=2) bikeshare.wellesley Explanation: Summary This chapter introduces the tools we need to run simulations, record the results, and plot them. We used a State object to represent the state of the system. Then we used the flip function and an if statement to simulate a single time step. We used for loop to simulate a series of steps, and a TimeSeries to record the results. Finally, we used plot and decorate to plot the results. In the next chapter, we will extend this simulation to make it a little more realistic. Exercises Exercise: What happens if you spell the name of a state variable wrong? Edit the following cell, change the spelling of wellesley, and run it. The error message uses the word "attribute", which is another name for what we are calling a state variable. End of explanation # Solution bikeshare = State(olin=10, wellesley=2, babson=0) show(bikeshare) Explanation: Exercise: Make a State object with a third state variable, called babson, with initial value 0, and display the state of the system. End of explanation # Solution def run_simulation(p1, p2, num_steps): results = TimeSeries() results[0] = bikeshare.olin for i in range(num_steps): step(p1, p2) results[i+1] = bikeshare.olin results.plot() decorate(title='Olin-Wellesley Bikeshare', xlabel='Time step (min)', ylabel='Number of bikes') # Solution bikeshare = State(olin=10, wellesley=2) run_simulation(0.3, 0.2, 60) Explanation: Exercise: Wrap the code in the chapter in a function named run_simulation that takes three parameters, named p1, p2, and num_steps. It should: Create a TimeSeries object to hold the results. Use a for loop to run step the number of times specified by num_steps, passing along the specified values of p1 and p2. After each step, it should save the number of bikes at Olin in the TimeSeries. After the for loop, it should plot the results and Decorate the axes. To test your function: Create a State object with the initial state of the system. Call run_simulation with appropriate parameters. End of explanation source_code(flip) Explanation: Under the Hood This section contains additional information about the functions we've used and pointers to their documentation. You don't need to know anything in these sections, so if you are already feeling overwhelmed, you might want to skip them. But if you are curious, read on. State and TimeSeries objects are based on the Series object defined by a the Pandas library. The documentation is at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.html. show works by creating another Pandas object, called a DataFrame, which can be displayed as a table. We'll use DataFrame objects in future chapters. Series objects provide their own plot function which is why we call it like this: results.plot() Instead of like this: plot(results) You can read the documentation of Series.plot at https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.plot.html. decorate is based on Matplotlib, which is a widely-used plotting library for Python. Matplotlib provides separate functions for title, xlabel, and ylabel. decorate makes them a little easier to use. For the list of keyword arguments you can pass to decorate, see https://matplotlib.org/3.2.2/api/axes_api.html?highlight=axes#module-matplotlib.axes. The flip function uses NumPy's random function to generate a random number between 0 and 1, then returns True or False with the given probability. You can get the source code for flip (or any other function) by running the following cell. End of explanation
7,365
Given the following text description, write Python code to implement the functionality described below step by step Description: <a href='http Step1: Train Test Split Step2: Estimators Let's show you how to use the simpler Estimator interface! Step3: Feature Columns Step4: Input Function Step5: Model Evaluation Use the predict method from the classifier model to create predictions from X_test Step6: Now create a classification report and a Confusion Matrix. Does anything stand out to you?
Python Code: import pandas as pd df = pd.read_csv('iris.csv') df.head() df.columns = ['sepal_length','sepal_width','petal_length','petal_width','target'] X = df.drop('target',axis=1) y = df['target'].apply(int) Explanation: <a href='http://www.pieriandata.com'> <img src='../Pierian_Data_Logo.png' /></a> Tensorflow with Estimators As we saw previously how to build a full Multi-Layer Perceptron model with full Sessions in Tensorflow. Unfortunately this was an extremely involved process. However developers have created Estimators that have an easier to use flow! It is much easier to use, but you sacrifice some level of customization of your model. Let's go ahead and explore it! Get the Data We will the iris data set. Let's get the data: End of explanation from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) Explanation: Train Test Split End of explanation import tensorflow as tf Explanation: Estimators Let's show you how to use the simpler Estimator interface! End of explanation X.columns feat_cols = [] for col in X.columns: feat_cols.append(tf.feature_column.numeric_column(col)) feat_cols Explanation: Feature Columns End of explanation # there is also a pandas_input_fn we'll see in the exercise!! input_func = tf.estimator.inputs.pandas_input_fn(x=X_train,y=y_train,batch_size=10,num_epochs=5,shuffle=True) classifier = tf.estimator.DNNClassifier(hidden_units=[10, 20, 10], n_classes=3,feature_columns=feat_cols) classifier.train(input_fn=input_func,steps=50) Explanation: Input Function End of explanation pred_fn = tf.estimator.inputs.pandas_input_fn(x=X_test,batch_size=len(X_test),shuffle=False) note_predictions = list(classifier.predict(input_fn=pred_fn)) note_predictions[0] final_preds = [] for pred in note_predictions: final_preds.append(pred['class_ids'][0]) Explanation: Model Evaluation Use the predict method from the classifier model to create predictions from X_test End of explanation from sklearn.metrics import classification_report,confusion_matrix print(confusion_matrix(y_test,final_preds)) print(classification_report(y_test,final_preds)) Explanation: Now create a classification report and a Confusion Matrix. Does anything stand out to you? End of explanation
7,366
Given the following text description, write Python code to implement the functionality described below step by step Description: Introduction In the last notebook, I showed you how easy it is to connect jQAssistant/neo4j with Python Pandas/py2neo. In this notebook, I show you a (at first glance) simple analysis of the Git repository https Step2: Data input We need some data to get started. Luckily, we have jQAssistant at our hand. It's integrated into the build process of Spring PetClinic repository above and scanned the Git repository information automatically with every executed build. So let's query our almighty Neo4j graph database that holds all the structural data about the software project. Step3: The query returns all commits with their authors and the author's email addresses. We get some nice, tabular data that we put into Pandas's DataFrame. Step4: Familiarization First, I like to check the raw data a little bit. I often do this by first having a look at the data types the data source is returning. It's a good starting point to check that Pandas recognizes the data types accordingly. You can also use this approach to check for skewed data columns very quickly (especially necessary when reading CSV or Excel files) Step5: That's OK for our simple scenario. The two columns with texts are objects &ndash; nothing spectacular. In the next step, I always like to get a "feeling" of all the data. Primarily, I want to get a quick impression of the data quality again. It could always be that there is "dirty data" in the dataset or that there are outliers that would screw up the analysis. With such a small amount of data we have, we can simply list all unique values that occur in the columns. I just list the top 10's for both columns. Step6: OK, at first glance, something seems awkward. Let's have a look at the email addresses. Step7: OK, the bad feeling is strengthening. We might have a problem with multiple authors having multiple email addresses. Let me show you the problem by better representing the problem. Interlude - begin In the interlude section, I take you to a short, mostly undocumented excursion with probably messy code (don't do this at home!) to make a point. If you like, you can skip that section. Goal Step8: Same procedure for the email addresses. Step9: Then I merge the two DataFrames with a subset of the original data. I get each author and email index as well as the number of occurrences for author respectively emails. I only need the ones that are occurring multiple times, so I check for > 2. Step10: I just add some nicely normalized indexes for plotting (note Step11: Plot an assignment table with the relationships between authors and email addresses. Step12: Alright! Here we are! We see that multiple authors use multiple email addresses. And I see a pattern that could be used to get better data. Do you, too? Interlude - end If you skipped the interlude section Step13: That looks pretty good. Now we want to get only the person's real name instead of the nickname. We use a little heuristic to determine the "best fitting" real name and replace all the others. For this, we need group by nicknames and determine the real names. Step14: That looks great! Now we switch back to our previous DataFrame by joining in the new information. Step15: That should be enough data cleansing for today! Analysis Now that we have valid data, we can produce some new insights. Top 10 committers Easy tasks first Step16: Committer Distribution Next, we create a pie chart to get a good impression of the committers. Step17: Uhh...that looks ugly and kind of weird. Let's first try to fix the mess on the right side that shows all authors with minor changes by summing up their number of commits. We will use a threshold value that makes sense with our data (e. g. the committers that contribute more than 3/4 to the code) to identify them. A nice start is the description of the current data set. Step18: OK, we want the 3/4 main contributors... Step19: ...that is > 75% of the commits of all contributors. Step20: These are the entries we want to combine to our new "Others" section. But we don't want to loose the number of changes, so we store them for later usage. Step21: Now we are deleting all authors that are in the <tt>author_minor_changes</tt>'s DataFrame. To not check on the threshold value from above again, we reuse the already calculated DataFrame. Step22: This gives us for the contributors with just a few commits missing values for the <tt>changes</tt> column, because these values were in the <tt>author_minor_changes</tt> DataFrame. We drop all Nan values to get only the major contributors. Step23: We add the "Others" row by appending to the DataFrame Step24: Almost there, you redraw with some styling and minor adjustments.
Python Code: import py2neo import pandas as pd import matplotlib.pyplot as plt # display graphics directly in the notebook %matplotlib inline Explanation: Introduction In the last notebook, I showed you how easy it is to connect jQAssistant/neo4j with Python Pandas/py2neo. In this notebook, I show you a (at first glance) simple analysis of the Git repository https://github.com/feststelltaste/spring-petclinic. This repository is a fork of the demo repository for jQAssistant (https://github.com/feststelltaste/spring-petclinic) therefore it integrates jQAssistant already. As analysis task, we want to know who are the Top 10 committers and how the distribution of the commits is. This could be handy if you want to identify your main contributors of a project e. g. to send them a gift at Christmas ;-) . But first, you might ask yourself: "Why do I need a fully fledged data analysis framework like Pandas for such a simple task? Are there no standard tools out there?" Well, I'll show you why (OK, and you got me there: I needed another reason to go deeper with Python, Pandas, jQAssistant and Neo4j to get some serious software data analysis started) So let's go! Preparation This notebook assumes that - there is a running Neo4j server with the default configuration. - the graph database is filled with the scan results of jQAssistant (happens for the repository above automatically with an <tt>mvn clean install</tt>) - you use a standard Anaconda installation with Python 3+ - you installed the py2neo connector If everything is set up, we just import the usual suspects: py2neo for connecting to Neo4j and Pandas for data analysis. We also want to plot some graphics later on, so we import matplotlib accordingly as the convention suggests. End of explanation graph = py2neo.Graph() query = MATCH (author:Author)-[:COMMITED]-> (commit:Commit) RETURN author.name as name, author.email as email result = graph.data(query) # just how first three entries result[0:3] Explanation: Data input We need some data to get started. Luckily, we have jQAssistant at our hand. It's integrated into the build process of Spring PetClinic repository above and scanned the Git repository information automatically with every executed build. So let's query our almighty Neo4j graph database that holds all the structural data about the software project. End of explanation commits = pd.DataFrame(result) commits.head() Explanation: The query returns all commits with their authors and the author's email addresses. We get some nice, tabular data that we put into Pandas's DataFrame. End of explanation commits.dtypes Explanation: Familiarization First, I like to check the raw data a little bit. I often do this by first having a look at the data types the data source is returning. It's a good starting point to check that Pandas recognizes the data types accordingly. You can also use this approach to check for skewed data columns very quickly (especially necessary when reading CSV or Excel files): If there should be a column with a specific data type (e. g. because the documentation of the dataset said so), the data type should be recognized automatically as specified. If not, there is a high probability that the imported data source isn't correct (and we have a data quality problem). End of explanation commits['name'].value_counts()[0:10] Explanation: That's OK for our simple scenario. The two columns with texts are objects &ndash; nothing spectacular. In the next step, I always like to get a "feeling" of all the data. Primarily, I want to get a quick impression of the data quality again. It could always be that there is "dirty data" in the dataset or that there are outliers that would screw up the analysis. With such a small amount of data we have, we can simply list all unique values that occur in the columns. I just list the top 10's for both columns. End of explanation commits['email'].value_counts()[0:10] Explanation: OK, at first glance, something seems awkward. Let's have a look at the email addresses. End of explanation grouped_by_authors = commits[['name', 'email']]\ .drop_duplicates().groupby('name').count()\ .sort_values('email', ascending=False).reset_index().reset_index() grouped_by_authors.head() Explanation: OK, the bad feeling is strengthening. We might have a problem with multiple authors having multiple email addresses. Let me show you the problem by better representing the problem. Interlude - begin In the interlude section, I take you to a short, mostly undocumented excursion with probably messy code (don't do this at home!) to make a point. If you like, you can skip that section. Goal: Create a diagram that shows the relationship between the authors and the emails addresses. (Note to myself: It's probably better to solve that directly in Neo4j the next time ;-) ) I need a unique index for each name and I have to calculate the number of different email addresses per author. End of explanation grouped_by_email = commits[['name', 'email']]\ .drop_duplicates().groupby('email').count()\ .sort_values('name', ascending=False).reset_index().reset_index() grouped_by_email.head() Explanation: Same procedure for the email addresses. End of explanation plot_data = commits.drop_duplicates()\ .merge(grouped_by_authors, left_on='name', right_on="name", suffixes=["", "_from_authors"], how="outer")\ .merge(grouped_by_email, left_on='email', right_on="email", suffixes=["", "_from_emails"], how="outer") plot_data = plot_data[\ (plot_data['email_from_authors'] > 1) | \ (plot_data['name_from_emails'] > 1)] plot_data Explanation: Then I merge the two DataFrames with a subset of the original data. I get each author and email index as well as the number of occurrences for author respectively emails. I only need the ones that are occurring multiple times, so I check for > 2. End of explanation from sklearn import preprocessing le = preprocessing.LabelEncoder() le.fit(plot_data['index']) plot_data['normalized_index_name'] = le.transform(plot_data['index']) * 10 le.fit(plot_data['index_from_emails']) plot_data['normalized_index_email'] = le.transform(plot_data['index_from_emails']) * 10 plot_data.head() Explanation: I just add some nicely normalized indexes for plotting (note: there might be a method that's easier) End of explanation fig1 = plt.figure(facecolor='white') ax1 = plt.axes(frameon=False) ax1.set_frame_on(False) ax1.get_xaxis().tick_bottom() ax1.axes.get_yaxis().set_visible(False) ax1.axes.get_xaxis().set_visible(False) # simply plot all the data (imperfection: duplicated will be displayed in bold font) for data in plot_data.iterrows(): row = data[1] plt.text(0, row['normalized_index_name'], row['name'], fontsize=15, horizontalalignment="right") plt.text(1, row['normalized_index_email'], row['email'], fontsize=15, horizontalalignment="left") plt.plot([0,1],[row['normalized_index_name'],row['normalized_index_email']],'grey', linewidth=1.0) Explanation: Plot an assignment table with the relationships between authors and email addresses. End of explanation commits['nickname'] = commits['email'].apply(lambda x : x.split("@")[0]) commits.head() Explanation: Alright! Here we are! We see that multiple authors use multiple email addresses. And I see a pattern that could be used to get better data. Do you, too? Interlude - end If you skipped the interlude section: I just visualized / demonstrated that there are different email addresses per author (and vise versa). Some authors choose to use another email address and some choose a different name for committing to the repositories (and a few did both things). Data Wrangling The situation above is a typical case of a little data messiness and &ndash; to demotivate you &ndash; absolutely normal. So we have to do some data correction before we start our analysis. Otherwise, we would ignore reality completely and deliver wrong results. This could damage our reputation as a data analyst and is something we have to avoid at all costs! We want to fix the problem with the multiple authors having multiple email addresses (but are the same persons). We need a mapping between them. Should we do it manually? That would be kind of crazy. As mentioned above, there is a pattern in the data to fix that. We simply use the name of the email address as an identifier for a person. Let's give it a try by extracting the name part from the email address with a simple split. End of explanation def determine_real_name(names): real_name = "" for name in names: # assumption: if there is a whitespace in the name, # someone thought about it to be first name and surname if " " in name: return name # else take the longest name elif len(name) > len(real_name): real_name = name return real_name commits_grouped = commits[['nickname', 'name']].groupby(['nickname']).agg(determine_real_name) commits_grouped = commits_grouped.rename(columns={'name' : 'real_name'}) commits_grouped.head() Explanation: That looks pretty good. Now we want to get only the person's real name instead of the nickname. We use a little heuristic to determine the "best fitting" real name and replace all the others. For this, we need group by nicknames and determine the real names. End of explanation commits = commits.merge(commits_grouped, left_on='nickname', right_index=True) # drop duplicated for better displaying commits.drop_duplicates().head() Explanation: That looks great! Now we switch back to our previous DataFrame by joining in the new information. End of explanation committers = commits.groupby('real_name')[['email']]\ .count().rename(columns={'email' : 'commits'})\ .sort_values('commits', ascending=False) committers.head(10) committers.head(10) Explanation: That should be enough data cleansing for today! Analysis Now that we have valid data, we can produce some new insights. Top 10 committers Easy tasks first: We simply produce a table with the Top 10 committers. We group by the real name and count every commit by using a subset (only the <tt>email</tt> column) of the DataFrame to only get on column returned. We rename the returned columns to <tt>commits</tt> for displaying reasons (would otherwise be <tt>email</tt>). Then we just list the top 10 entries after sorting appropriately. End of explanation committers['commits'].plot(kind='pie') Explanation: Committer Distribution Next, we create a pie chart to get a good impression of the committers. End of explanation committers_description = committers.describe() committers_description Explanation: Uhh...that looks ugly and kind of weird. Let's first try to fix the mess on the right side that shows all authors with minor changes by summing up their number of commits. We will use a threshold value that makes sense with our data (e. g. the committers that contribute more than 3/4 to the code) to identify them. A nice start is the description of the current data set. End of explanation threshold = committers_description.loc['75%'].values[0] threshold Explanation: OK, we want the 3/4 main contributors... End of explanation minor_committers = committers[committers['commits'] <= threshold] minor_committers.head() Explanation: ...that is > 75% of the commits of all contributors. End of explanation others_number_of_changes = minor_committers.sum() others_number_of_changes Explanation: These are the entries we want to combine to our new "Others" section. But we don't want to loose the number of changes, so we store them for later usage. End of explanation main_committers = committers[~committers.isin(minor_committers)] main_committers.tail() Explanation: Now we are deleting all authors that are in the <tt>author_minor_changes</tt>'s DataFrame. To not check on the threshold value from above again, we reuse the already calculated DataFrame. End of explanation main_committers = main_committers.dropna() main_committers Explanation: This gives us for the contributors with just a few commits missing values for the <tt>changes</tt> column, because these values were in the <tt>author_minor_changes</tt> DataFrame. We drop all Nan values to get only the major contributors. End of explanation main_committers.loc["Others"] = others_number_of_changes main_committers Explanation: We add the "Others" row by appending to the DataFrame End of explanation # some configuration for displaying nice diagrams plt.style.use('fivethirtyeight') plt.figure(facecolor='white') ax = main_committers['commits'].plot( kind='pie', figsize=(6,6), title="Main committers", autopct='%.2f', fontsize=12) # get rid of the distracting label for the y-axis ax.set_ylabel("") Explanation: Almost there, you redraw with some styling and minor adjustments. End of explanation
7,367
Given the following text description, write Python code to implement the functionality described below step by step Description: Input from the keyboard In Pytho, the keyboard is the default input device. <a id='input'></a> 1. Input from the code Step1: <a id='prompt'></a> 2. Input from the OS prompt Step2: Another posibility is to use Fire
Python Code: a = input('Please, enter something: ') print('You entered:', a) Explanation: Input from the keyboard In Pytho, the keyboard is the default input device. <a id='input'></a> 1. Input from the code End of explanation !cat argparse_example.py !python argparse_example.py -h !python argparse_example.py -i abc Explanation: <a id='prompt'></a> 2. Input from the OS prompt End of explanation %%writefile using_fire.py import fire class A(): def do_something(self, x, y): print('Doing something with:', y, x) fire.Fire(A) !python using_fire.py !python using_fire.py do-something hola caracola Explanation: Another posibility is to use Fire: End of explanation
7,368
Given the following text description, write Python code to implement the functionality described below step by step Description: Searching for packages As explained in "Uploading a Package", packages are managed using registries. There is a one local registry on your machine, and potentially many remote registries elsewhere "in the world". Use list_packages to see the packages available on a registry Step1: Installing a package To make a remote package and all of its data available locally, install it. The examples in this section use the examples/hurdat demo package Step2: Note that unless this registry is public, you will need to be logged into a user who has read access to this registry in order to install from it Step3: Finally, you can install a specific version of a package by specifying the corresponding top hash Step4: Browsing a package manifest An alternative to install is browse. browse downloads a package manifest without also downloading the data in the package. Step5: browse is advantageous when you don't want to download everything in a package at once. For example if you just want to look at a package's metadata. Importing a package You can import a local package from within Python
Python Code: import quilt3 # list local packages list(quilt3.list_packages()) # list remote packages list(quilt3.list_packages("s3://quilt-example")) Explanation: Searching for packages As explained in "Uploading a Package", packages are managed using registries. There is a one local registry on your machine, and potentially many remote registries elsewhere "in the world". Use list_packages to see the packages available on a registry: End of explanation quilt3.Package.install( "examples/hurdat", "s3://quilt-example", ) Explanation: Installing a package To make a remote package and all of its data available locally, install it. The examples in this section use the examples/hurdat demo package: End of explanation quilt3.Package.install( "examples/hurdat", "s3://quilt-example", dest="./" ) Explanation: Note that unless this registry is public, you will need to be logged into a user who has read access to this registry in order to install from it: ```python only need to run this once ie quilt3.config('https://your-catalog-homepage/') quilt3.config('https://open.quiltdata.com/') follow the instructions to finish login quilt3.login() ``` Data files that you download are written to a folder in your local registry by default. You can specify an alternative destination using dest: End of explanation quilt3.Package.install( "examples/hurdat", "s3://quilt-example", top_hash="058e62c" ) Explanation: Finally, you can install a specific version of a package by specifying the corresponding top hash: End of explanation # load a package manifest from a remote registry p = quilt3.Package.browse("examples/hurdat", "s3://quilt-example") # load a package manifest from the default remote registry quilt3.config(default_remote_registry="s3://quilt-example") p = quilt3.Package.browse("examples/hurdat") Explanation: Browsing a package manifest An alternative to install is browse. browse downloads a package manifest without also downloading the data in the package. End of explanation from quilt3.data.examples import hurdat Explanation: browse is advantageous when you don't want to download everything in a package at once. For example if you just want to look at a package's metadata. Importing a package You can import a local package from within Python: End of explanation
7,369
Given the following text description, write Python code to implement the functionality described below step by step Description: Machine Learning Engineer Nanodegree Model Evaluation & Validation Project 1 Step1: Statistical Analysis and Data Exploration In this first section of the project, you will quickly investigate a few basic statistics about the dataset you are working with. In addition, you'll look at the client's feature set in CLIENT_FEATURES and see how this particular sample relates to the features of the dataset. Familiarizing yourself with the data through an explorative process is a fundamental practice to help you better understand your results. Step 1 In the code block below, use the imported numpy library to calculate the requested statistics. You will need to replace each None you find with the appropriate numpy coding for the proper statistic to be printed. Be sure to execute the code block each time to test if your implementation is working successfully. The print statements will show the statistics you calculate! Step2: Question 1 As a reminder, you can view a description of the Boston Housing dataset here, where you can find the different features under Attribute Information. The MEDV attribute relates to the values stored in our housing_prices variable, so we do not consider that a feature of the data. Of the features available for each data point, choose three that you feel are significant and give a brief description for each of what they measure. Remember, you can double click the text box below to add your answer! Step3: CRIM - the per-capita crime rate. INDUS - the proportion of non-retail business acres per town. LSTAT - the percentage of the population that is of lower status. Question 2 Using your client's feature set CLIENT_FEATURES, which values correspond with the features you've chosen above? Hint Step5: CRIM Step7: Question 4 Why do we split the data into training and testing subsets for our model? So that we can assess the model using a different data-set than what it was trained on, thus reducing the likelihood of overfitting the model to the training data and increasing the likelihood that it will generalize to other data. Step 3 In the code block below, you will need to implement code so that the performance_metric function does the following Step9: Question 4 Which performance metric below did you find was most appropriate for predicting housing prices and analyzing the total error. Why? - Accuracy - Precision - Recall - F1 Score - Mean Squared Error (MSE) - Mean Absolute Error (MAE) Mean Squared Error was the most appropriate performance metric for predicting housing prices because we are predicting a numeric value (this is a regression problem) and while Mean Absolute Error could also be used, the MSE emphasizes larger errors more (due to the squaring) and so is preferable. Step 4 (Final Step) In the code block below, you will need to implement code so that the fit_model function does the following Step12: Question 5 What is the grid search algorithm and when is it applicable? The GridSearchCV algorithm exhaustively works through the parameters it is given to tune the model. Because it is exhaustive it is appropriate when the parameters are relatively limited and the model-creation is not computationally intensive, otherwise its run-time might be infeasible. Question 6 What is cross-validation, and how is it performed on a model? Why would cross-validation be helpful when using grid search? Cross-validation is a method of testing a model by partitioning the data into subsets, with each subset taking a turn as the test set while the data not being used as a test-set is used as the training set. This allows the model to be tested against all the data-points, rather than having some data reserved exclusively as training data and the remainder exclusively as testing data. Because grid-search attempts to find the optimal parameters for a model, it's advantageous to use the same training and testing data in each case (case meaning a particular permutation of the parameters) so that the comparisons are equitable. One could simply perform an initial train-validation-test split and use this throughout the grid search, but this then risks the possibility that there was something in the initial split that will bias the outcome. By using all the partitions of the data as both test and training data, as cross-validation does, the chance of a bias in the splitting is reduced and at the same time all the parameter permutations are given the same data to be tested against. Checkpoint! You have now successfully completed your last code implementation section. Pat yourself on the back! All of your functions written above will be executed in the remaining sections below, and questions will be asked about various results for you to analyze. To prepare the Analysis and Prediction sections, you will need to intialize the two functions below. Remember, there's no need to implement any more code, so sit back and execute the code blocks! Some code comments are provided if you find yourself interested in the functionality. Step13: Analyzing Model Performance In this third section of the project, you'll take a look at several models' learning and testing error rates on various subsets of training data. Additionally, you'll investigate one particular algorithm with an increasing max_depth parameter on the full training set to observe how model complexity affects learning and testing errors. Graphing your model's performance based on varying criteria can be beneficial in the analysis process, such as visualizing behavior that may not have been apparent from the results alone. Step14: Question 7 Choose one of the learning curve graphs that are created above. What is the max depth for the chosen model? As the size of the training set increases, what happens to the training error? What happens to the testing error? Looking at the model with max-depth of 3, as the size of the training set increases, the training error gradually increases. The testing error initially decreases, the seems to more or less stabilize. Question 8 Look at the learning curve graphs for the model with a max depth of 1 and a max depth of 10. When the model is using the full training set, does it suffer from high bias or high variance when the max depth is 1? What about when the max depth is 10? The training and testing plots for the model with max-depth 1 move toward convergence with an error near 50, indicating a high bias (the model is too simple, and the additional data isn't improving the generalization of the model). For the model with max-depth 1, the curves haven't converged, and the training error remains near 0, indicating that it suffers from high variance, and should be improved with more data. Step15: Question 9 From the model complexity graph above, describe the training and testing errors as the max depth increases. Based on your interpretation of the graph, which max depth results in a model that best generalizes the dataset? Why? As max-depth increases the training error improves, while the testing error decreases up until a depth of 6 and then begins a slight increase as the depth is increased. Based on this I would say that the max-depth of 6 created the model that best generalized the dataset, as it minimized the testing error. Model Prediction In this final section of the project, you will make a prediction on the client's feature set using an optimized model from fit_model. To answer the following questions, it is recommended that you run the code blocks several times and use the median or mean value of the results. Question 10 Using grid search on the entire dataset, what is the optimal max_depth parameter for your model? How does this result compare to your intial intuition? Hint Step16: While a max-depth of 3 was the most common best-parameter, the max-depth of 5 was the median max-depth, had the highest median score, and had the highest overall score, so I will say that the optimal max_depth parameter is 5. This is slightly lower than my guess of 6, but doesn't seem too far off, although a max-depth of 7 seems to be a slight improvement over 6 as well. Question 11 With your parameter-tuned model, what is the best selling price for your client's home? How does this selling price compare to the basic statistics you calculated on the dataset? Hint
Python Code: # Importing a few necessary libraries # python standard library import warnings # third party import numpy as np import numpy import matplotlib.pyplot as pl from matplotlib import pylab import pandas import seaborn from sklearn import datasets from sklearn.tree import DecisionTreeRegressor # Make matplotlib show our plots inline (nicely formatted in the notebook) %matplotlib inline # Create our client's feature set for which we will be predicting a selling price CLIENT_FEATURES = [[11.95, 0.00, 18.100, 0, 0.6590, 5.6090, 90.00, 1.385, 24, 680.0, 20.20, 332.09, 12.13]] # Load the Boston Housing dataset into the city_data variable city_data = datasets.load_boston() # Initialize the housing prices and housing features housing_prices = city_data.target housing_features = city_data.data print "Boston Housing dataset loaded successfully!" pylab.rcParams['figure.figsize'] = (10, 8) columns = 'crime big_lots industrial charles_river nox rooms old distance highway_access tax_rate pupil_teacher_ratio blacks lower_status'.split() assert len(columns) == housing_features.shape[1], len(columns) assert len(CLIENT_FEATURES[0]) == len(columns) client_data = pandas.DataFrame(CLIENT_FEATURES, columns=columns) housing_data = pandas.DataFrame(housing_features, columns=columns) housing_data['median_value'] = housing_prices housing_data.describe() Explanation: Machine Learning Engineer Nanodegree Model Evaluation & Validation Project 1: Predicting Boston Housing Prices Welcome to the first project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been written. You will need to implement additional functionality to successfully answer all of the questions for this project. Unless it is requested, do not modify any of the code that has already been included. In this template code, there are four sections which you must complete to successfully produce a prediction with your model. Each section where you will write code is preceded by a STEP X header with comments describing what must be done. Please read the instructions carefully! In addition to implementing code, there will be questions that you must answer that relate to the project and your implementation. Each section where you will answer a question is preceded by a QUESTION X header. Be sure that you have carefully read each question and provide thorough answers in the text boxes that begin with "Answer:". Your project submission will be evaluated based on your answers to each of the questions. A description of the dataset can be found here, which is provided by the UCI Machine Learning Repository. Getting Started To familiarize yourself with an iPython Notebook, try double clicking on this cell. You will notice that the text changes so that all the formatting is removed. This allows you to make edits to the block of text you see here. This block of text (and mostly anything that's not code) is written using Markdown, which is a way to format text using headers, links, italics, and many other options! Whether you're editing a Markdown text block or a code block (like the one below), you can use the keyboard shortcut Shift + Enter or Shift + Return to execute the code or text block. In this case, it will show the formatted text. Let's start by setting up some code we will need to get the rest of the project up and running. Use the keyboard shortcut mentioned above on the following code block to execute it. Alternatively, depending on your iPython Notebook program, you can press the Play button in the hotbar. You'll know the code block executes successfully if the message "Boston Housing dataset loaded successfully!" is printed. End of explanation # Number of houses in the dataset total_houses = housing_features.shape[0] # Number of features in the dataset total_features = housing_features.shape[1] # Minimum housing value in the dataset minimum_price = housing_prices.min() # Maximum housing value in the dataset maximum_price = housing_prices.max() # Mean house value of the dataset mean_price = housing_prices.mean() # Median house value of the dataset median_price = numpy.median(housing_prices) # Standard deviation of housing values of the dataset std_dev = numpy.std(housing_prices) # Show the calculated statistics print "Boston Housing dataset statistics (in $1000's):\n" print "Total number of houses:", total_houses print "Total number of features:", total_features print "Minimum house price:", minimum_price print "Maximum house price:", maximum_price print "Mean house price: {0:.3f}".format(mean_price) print "Median house price:", median_price print "Standard deviation of house price: {0:.3f}".format(std_dev) axe = seaborn.distplot(housing_data.median_value) title = axe.set_title('Median Housing Prices') Explanation: Statistical Analysis and Data Exploration In this first section of the project, you will quickly investigate a few basic statistics about the dataset you are working with. In addition, you'll look at the client's feature set in CLIENT_FEATURES and see how this particular sample relates to the features of the dataset. Familiarizing yourself with the data through an explorative process is a fundamental practice to help you better understand your results. Step 1 In the code block below, use the imported numpy library to calculate the requested statistics. You will need to replace each None you find with the appropriate numpy coding for the proper statistic to be printed. Be sure to execute the code block each time to test if your implementation is working successfully. The print statements will show the statistics you calculate! End of explanation seaborn.set_style('whitegrid', {'figure.figsize': (10, 8)}) with warnings.catch_warnings(): warnings.simplefilter('ignore') for column in housing_data.columns: grid = seaborn.lmplot(column, 'median_value', data=housing_data, size=8) axe = grid.fig.gca() title = axe.set_title('{0} vs price'.format(column)) Explanation: Question 1 As a reminder, you can view a description of the Boston Housing dataset here, where you can find the different features under Attribute Information. The MEDV attribute relates to the values stored in our housing_prices variable, so we do not consider that a feature of the data. Of the features available for each data point, choose three that you feel are significant and give a brief description for each of what they measure. Remember, you can double click the text box below to add your answer! End of explanation print CLIENT_FEATURES print(client_data.crime) print(client_data.industrial) print(client_data.lower_status) Explanation: CRIM - the per-capita crime rate. INDUS - the proportion of non-retail business acres per town. LSTAT - the percentage of the population that is of lower status. Question 2 Using your client's feature set CLIENT_FEATURES, which values correspond with the features you've chosen above? Hint: Run the code block below to see the client's data. End of explanation # Put any import statements you need for this code block here from sklearn import cross_validation def shuffle_split_data(X, y): Shuffles and splits data into 70% training and 30% testing subsets, then returns the training and testing subsets. # Shuffle and split the data X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=.3, random_state=0) # Return the training and testing data subsets return X_train, y_train, X_test, y_test # Test shuffle_split_data X_train, y_train, X_test, y_test = shuffle_split_data(housing_features, housing_prices) feature_length = len(housing_features) train_length = round(.7 * feature_length) test_length = round(.3 * feature_length) assert len(X_train) == train_length, "Expected: {0} Actual: {1}".format(.7 * feature_length, len(X_train)) assert len(X_test) == test_length, "Expected: {0} Actual: {1}".format(int(.3 * feature_length), len(X_test)) assert len(y_train) == train_length assert len(y_test) == test_length print "Successfully shuffled and split the data!" Explanation: CRIM : 11.95, INDUS: 18.1, LSTAT: 12.13 Evaluating Model Performance In this second section of the project, you will begin to develop the tools necessary for a model to make a prediction. Being able to accurately evaluate each model's performance through the use of these tools helps to greatly reinforce the confidence in your predictions. Step 2 In the code block below, you will need to implement code so that the shuffle_split_data function does the following: - Randomly shuffle the input data X and target labels (housing values) y. - Split the data into training and testing subsets, holding 30% of the data for testing. If you use any functions not already acessible from the imported libraries above, remember to include your import statement below as well! Ensure that you have executed the code block once you are done. You'll know if the shuffle_split_data function is working if the statement "Successfully shuffled and split the data!" is printed. End of explanation # Put any import statements you need for this code block here from sklearn.metrics import mean_squared_error def performance_metric(y_true, y_predict): Calculates and returns the total error between true and predicted values based on a performance metric chosen by the student. error = mean_squared_error(y_true, y_predict) return error # Test performance_metric try: total_error = performance_metric(y_train, y_train) print "Successfully performed a metric calculation!" except: print "Something went wrong with performing a metric calculation." Explanation: Question 4 Why do we split the data into training and testing subsets for our model? So that we can assess the model using a different data-set than what it was trained on, thus reducing the likelihood of overfitting the model to the training data and increasing the likelihood that it will generalize to other data. Step 3 In the code block below, you will need to implement code so that the performance_metric function does the following: - Perform a total error calculation between the true values of the y labels y_true and the predicted values of the y labels y_predict. You will need to first choose an appropriate performance metric for this problem. See the sklearn metrics documentation to view a list of available metric functions. Hint: Look at the question below to see a list of the metrics that were covered in the supporting course for this project. Once you have determined which metric you will use, remember to include the necessary import statement as well! Ensure that you have executed the code block once you are done. You'll know if the performance_metric function is working if the statement "Successfully performed a metric calculation!" is printed. End of explanation # Put any import statements you need for this code block from sklearn.metrics import make_scorer from sklearn.grid_search import GridSearchCV def fit_model(X, y): Tunes a decision tree regressor model using GridSearchCV on the input data X and target labels y and returns this optimal model. # Create a decision tree regressor object regressor = DecisionTreeRegressor() # Set up the parameters we wish to tune parameters = {'max_depth':(1,2,3,4,5,6,7,8,9,10)} # Make an appropriate scoring function scoring_function = make_scorer(mean_squared_error, greater_is_better=False) # Make the GridSearchCV object reg = GridSearchCV(regressor, param_grid=parameters, scoring=scoring_function, cv=10) # Fit the learner to the data to obtain the optimal model with tuned parameters reg.fit(X, y) # Return the optimal model return reg # Test fit_model on entire dataset reg = fit_model(housing_features, housing_prices) print "Successfully fit a model!" Explanation: Question 4 Which performance metric below did you find was most appropriate for predicting housing prices and analyzing the total error. Why? - Accuracy - Precision - Recall - F1 Score - Mean Squared Error (MSE) - Mean Absolute Error (MAE) Mean Squared Error was the most appropriate performance metric for predicting housing prices because we are predicting a numeric value (this is a regression problem) and while Mean Absolute Error could also be used, the MSE emphasizes larger errors more (due to the squaring) and so is preferable. Step 4 (Final Step) In the code block below, you will need to implement code so that the fit_model function does the following: - Create a scoring function using the same performance metric as in Step 2. See the sklearn make_scorer documentation. - Build a GridSearchCV object using regressor, parameters, and scoring_function. See the sklearn documentation on GridSearchCV. When building the scoring function and GridSearchCV object, be sure that you read the parameters documentation thoroughly. It is not always the case that a default parameter for a function is the appropriate setting for the problem you are working on. Since you are using sklearn functions, remember to include the necessary import statements below as well! Ensure that you have executed the code block once you are done. You'll know if the fit_model function is working if the statement "Successfully fit a model to the data!" is printed. End of explanation def learning_curves(X_train, y_train, X_test, y_test): Calculates the performance of several models with varying sizes of training data. The learning and testing error rates for each model are then plotted. print "Creating learning curve graphs for max_depths of 1, 3, 6, and 10. . ." # Create the figure window fig = pl.figure(figsize=(10,8)) # We will vary the training set size so that we have 50 different sizes sizes = np.round(np.linspace(1, len(X_train), 50)) train_err = np.zeros(len(sizes)) test_err = np.zeros(len(sizes)) # Create four different models based on max_depth for k, depth in enumerate([1,3,6,10]): for i, s in enumerate(sizes): # Setup a decision tree regressor so that it learns a tree with max_depth = depth regressor = DecisionTreeRegressor(max_depth = depth) # Fit the learner to the training data regressor.fit(X_train[:s], y_train[:s]) # Find the performance on the training set train_err[i] = performance_metric(y_train[:s], regressor.predict(X_train[:s])) # Find the performance on the testing set test_err[i] = performance_metric(y_test, regressor.predict(X_test)) # Subplot the learning curve graph ax = fig.add_subplot(2, 2, k+1) ax.plot(sizes, test_err, lw = 2, label = 'Testing Error') ax.plot(sizes, train_err, lw = 2, label = 'Training Error') ax.legend() ax.set_title('max_depth = %s'%(depth)) ax.set_xlabel('Number of Data Points in Training Set') ax.set_ylabel('Total Error') ax.set_xlim([0, len(X_train)]) # Visual aesthetics fig.suptitle('Decision Tree Regressor Learning Performances', fontsize=18, y=1.03) fig.tight_layout() fig.show() def model_complexity(X_train, y_train, X_test, y_test): Calculates the performance of the model as model complexity increases. The learning and testing errors rates are then plotted. print "Creating a model complexity graph. . . " # We will vary the max_depth of a decision tree model from 1 to 14 max_depth = np.arange(1, 14) train_err = np.zeros(len(max_depth)) test_err = np.zeros(len(max_depth)) for i, d in enumerate(max_depth): # Setup a Decision Tree Regressor so that it learns a tree with depth d regressor = DecisionTreeRegressor(max_depth = d) # Fit the learner to the training data regressor.fit(X_train, y_train) # Find the performance on the training set train_err[i] = performance_metric(y_train, regressor.predict(X_train)) # Find the performance on the testing set test_err[i] = performance_metric(y_test, regressor.predict(X_test)) # Plot the model complexity graph pl.figure(figsize=(7, 5)) pl.title('Decision Tree Regressor Complexity Performance') pl.plot(max_depth, test_err, lw=2, label = 'Testing Error') pl.plot(max_depth, train_err, lw=2, label = 'Training Error') pl.legend() pl.xlabel('Maximum Depth') pl.ylabel('Total Error') pl.show() Explanation: Question 5 What is the grid search algorithm and when is it applicable? The GridSearchCV algorithm exhaustively works through the parameters it is given to tune the model. Because it is exhaustive it is appropriate when the parameters are relatively limited and the model-creation is not computationally intensive, otherwise its run-time might be infeasible. Question 6 What is cross-validation, and how is it performed on a model? Why would cross-validation be helpful when using grid search? Cross-validation is a method of testing a model by partitioning the data into subsets, with each subset taking a turn as the test set while the data not being used as a test-set is used as the training set. This allows the model to be tested against all the data-points, rather than having some data reserved exclusively as training data and the remainder exclusively as testing data. Because grid-search attempts to find the optimal parameters for a model, it's advantageous to use the same training and testing data in each case (case meaning a particular permutation of the parameters) so that the comparisons are equitable. One could simply perform an initial train-validation-test split and use this throughout the grid search, but this then risks the possibility that there was something in the initial split that will bias the outcome. By using all the partitions of the data as both test and training data, as cross-validation does, the chance of a bias in the splitting is reduced and at the same time all the parameter permutations are given the same data to be tested against. Checkpoint! You have now successfully completed your last code implementation section. Pat yourself on the back! All of your functions written above will be executed in the remaining sections below, and questions will be asked about various results for you to analyze. To prepare the Analysis and Prediction sections, you will need to intialize the two functions below. Remember, there's no need to implement any more code, so sit back and execute the code blocks! Some code comments are provided if you find yourself interested in the functionality. End of explanation with warnings.catch_warnings(): warnings.simplefilter('ignore') learning_curves(X_train, y_train, X_test, y_test) Explanation: Analyzing Model Performance In this third section of the project, you'll take a look at several models' learning and testing error rates on various subsets of training data. Additionally, you'll investigate one particular algorithm with an increasing max_depth parameter on the full training set to observe how model complexity affects learning and testing errors. Graphing your model's performance based on varying criteria can be beneficial in the analysis process, such as visualizing behavior that may not have been apparent from the results alone. End of explanation model_complexity(X_train, y_train, X_test, y_test) Explanation: Question 7 Choose one of the learning curve graphs that are created above. What is the max depth for the chosen model? As the size of the training set increases, what happens to the training error? What happens to the testing error? Looking at the model with max-depth of 3, as the size of the training set increases, the training error gradually increases. The testing error initially decreases, the seems to more or less stabilize. Question 8 Look at the learning curve graphs for the model with a max depth of 1 and a max depth of 10. When the model is using the full training set, does it suffer from high bias or high variance when the max depth is 1? What about when the max depth is 10? The training and testing plots for the model with max-depth 1 move toward convergence with an error near 50, indicating a high bias (the model is too simple, and the additional data isn't improving the generalization of the model). For the model with max-depth 1, the curves haven't converged, and the training error remains near 0, indicating that it suffers from high variance, and should be improved with more data. End of explanation print "Final model optimal parameters:", reg.best_params_ reg.best_score_ models = (fit_model(housing_features, housing_prices) for model in range(1000)) params_scores = [(model.best_params_, model.best_score_) for model in models] parameters = numpy.array([param_score[0]['max_depth'] for param_score in params_scores]) scores = numpy.array([param_score[1] for param_score in params_scores]) grid = seaborn.distplot(parameters) grid = seaborn.boxplot(parameters) import matplotlib.pyplot as plot grid = plot.plot(sorted(parameters), numpy.linspace(0, 1, len(parameters))) best_models = pandas.DataFrame.from_dict({'parameter':parameters, 'score': scores}) x_labels = sorted(best_models.parameter.unique()) figure = plot.figure() axe = figure.gca() grid = seaborn.boxplot('parameter', 'score', data = best_models, order=x_labels, ax=axe) grid = seaborn.swarmplot('parameter', 'score', data = best_models, order=x_labels, ax=axe, color='w', alpha=0.5) title = axe.set_title("Best Parameters vs Best Scores") grid = seaborn.distplot(scores) print('min parameter: {0}'.format(numpy.min(parameters))) print('median parameter: {0}'.format(numpy.median(parameters))) print('mean parameter: {0}'.format(numpy.mean(parameters))) print('max parameter: {0}'.format(numpy.max(parameters))) # since the goal is to minimize the errors, sklearn negates the MSE # so the highest score (the least negative) is the best score print('min score: {0}'.format(numpy.min(scores))) print('max score: {0}'.format(numpy.max(scores))) best_index = numpy.where(scores==numpy.max(scores)) print(scores[best_index]) print(parameters[best_index]) bin_range = best_models.parameter.max() - best_models.parameter.min() bins = pandas.cut(best_models.parameter, bin_range) print(bins.value_counts()) parameter_group = pandas.groupby(best_models, 'parameter') parameter_group.median() parameter_group.max() Explanation: Question 9 From the model complexity graph above, describe the training and testing errors as the max depth increases. Based on your interpretation of the graph, which max depth results in a model that best generalizes the dataset? Why? As max-depth increases the training error improves, while the testing error decreases up until a depth of 6 and then begins a slight increase as the depth is increased. Based on this I would say that the max-depth of 6 created the model that best generalized the dataset, as it minimized the testing error. Model Prediction In this final section of the project, you will make a prediction on the client's feature set using an optimized model from fit_model. To answer the following questions, it is recommended that you run the code blocks several times and use the median or mean value of the results. Question 10 Using grid search on the entire dataset, what is the optimal max_depth parameter for your model? How does this result compare to your intial intuition? Hint: Run the code block below to see the max depth produced by your optimized model. End of explanation sale_price = reg.predict(CLIENT_FEATURES) print "Predicted value of client's home: {0:.3f}".format(sale_price[0]) Explanation: While a max-depth of 3 was the most common best-parameter, the max-depth of 5 was the median max-depth, had the highest median score, and had the highest overall score, so I will say that the optimal max_depth parameter is 5. This is slightly lower than my guess of 6, but doesn't seem too far off, although a max-depth of 7 seems to be a slight improvement over 6 as well. Question 11 With your parameter-tuned model, what is the best selling price for your client's home? How does this selling price compare to the basic statistics you calculated on the dataset? Hint: Run the code block below to have your parameter-tuned model make a prediction on the client's home. End of explanation
7,370
Given the following text description, write Python code to implement the functionality described below step by step Description: WAve Models (WAM) Usage Example WAM wave models are most widely used wave models in the world. This notebook illustrates ways of using WAM models data via Planet OS Datahub API, including Step1: <font color='red'>Please put your datahub API key into a file called APIKEY and place it to the notebook folder or assign your API key directly to the variable API_key!</font> Step2: Change latitude and longitude to your desired location. Longitude/latitude west/east are for raster API example. Step3: If you don't want to choose location by yourself, default locations will be used. Step4: Making dropdown for WAM dataset keys, where you can choose WAM model you would like to use. Note that when using Europe/ North-Atlantic/ North-Pacific/ Mediterranean Sea data points have to be from that area! Step5: Point data API By point data we mean data that is given at a single point (or from single measurement device) at different timesteps. For WAM, this means selection of one single geographic point and getting data for one or more parameters. Note that you need to choose point which has coverage on that area. To follow the examples better, we suggest to pay attention to following API keywords, which may not seem obvious in first place Step6: Getting variables for choosen dataset Step7: Now let's plot the data. We are making two dropdown lists. From first you have to choose level type. It means that data is separated by contexts. Context here means just a set of spatial and temporal dimensions for particular variable, like NetCDF dimensions. Each variable has values only in one context. So the NaN's do not come from the API request, but from the current way we use to create the Dataframe. It is not difficult to filter out variables from the dataframe, but for any use case besides observing the data, it is more reasonable to query only the right data from the server. Step8: Raster API Now we are using raster API. Please note that the data size returned by raster API is limited, to keep the JSON string size reasonable. If you want to get larger data, please try our new asynchronous API to download NetCDF files Step9: Longitude and latitude data is necessary for map and it is defined at the beginning of the notebook by user. Map projection can easily be changed by user as well. Step10: Now let's map our data! Step11: As time slider for image above does not work in GitHub preview, let's make image from first time moment. Although, it will work in your local environment.
Python Code: %matplotlib notebook import urllib.request import numpy as np import simplejson as json import pandas as pd from netCDF4 import Dataset, date2num, num2date import ipywidgets as widgets from IPython.display import display, clear_output import dateutil.parser import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap import time from po_data_process import get_data_from_raster_API,get_data_from_point_API,get_variables_from_detail_api,read_data_to_json,generate_raster_api_query,get_units import warnings import matplotlib.cbook warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation) dataset_keys = ['cmc_gdwps_wave_model_global','dwd_wam_europe','dwd_wam_global', 'cmems_medsea_wave_analysis_forecast_0042','noaa_ww3_global_0.5d'] server = "http://api.planetos.com/v1/datasets/" Explanation: WAve Models (WAM) Usage Example WAM wave models are most widely used wave models in the world. This notebook illustrates ways of using WAM models data via Planet OS Datahub API, including: point and raster API options API documentation is available at http://docs.planetos.com. If you have questions or comments, join the Planet OS Slack community to chat with our development team. For general information on usage of IPython/Jupyter and Matplotlib, please refer to their corresponding documentation. https://ipython.org/ and http://matplotlib.org/ First, you have to define usable API endpoint, which consists of server name, dataset name, API key and query details. It is necessary to provide location details, for point API single point and raster API, four courners. Also, please make sure you have downloaded all the python modules that are imported below. Note that this example is using Python 3 End of explanation API_key = open('APIKEY').readlines()[0].strip() #'<YOUR API KEY HERE>' Explanation: <font color='red'>Please put your datahub API key into a file called APIKEY and place it to the notebook folder or assign your API key directly to the variable API_key!</font> End of explanation latitude = 'Please add location for point data' longitude = 'Please add location for point data' longitude_west = 'Please add location for raster data' longitude_east = 'Please add location for raster data' latitude_south = 'Please add location for raster data' latitude_north = 'Please add location for raster data' Explanation: Change latitude and longitude to your desired location. Longitude/latitude west/east are for raster API example. End of explanation default_point_api_loc = {'cmc_gdwps_wave_model_global':['39','-69'],'dwd_wam_europe':['56.3','17.8'], 'dwd_wam_global':['39','-69'],'cmems_medsea_wave_analysis_forecast_0042':['38.3','5.8'],'noaa_ww3_global_0.5d':['39','-69']} default_raster_api_loc = {'cmc_gdwps_wave_model_global':['36','39','-62','-70'],'dwd_wam_europe':['55.2','56.5','17.4','20.2'], 'dwd_wam_global':['36','39','-62','-70'],'cmems_medsea_wave_analysis_forecast_0042':['35.8','37.8','16.5','19.5'], 'noaa_ww3_global_0.5d':['36','39','-62','-70']} Explanation: If you don't want to choose location by yourself, default locations will be used. End of explanation droplist0 = list(dataset_keys) selecter0 = widgets.Dropdown( options=droplist0, value=droplist0[0], description='Select dataset:', disabled=False, button_style='' ) display(selecter0) dataset_key = selecter0.value if latitude.isdigit() == False or longitude.isdigit() == False: latitude = default_point_api_loc[dataset_key][0] longitude = default_point_api_loc[dataset_key][1] if latitude_south.isdigit() == False or latitude_north.isdigit() == False or longitude_east.isdigit == False \ or longitude_west.isdigit() == False: latitude_south = default_raster_api_loc[dataset_key][0] latitude_north = default_raster_api_loc[dataset_key][1] longitude_east = default_raster_api_loc[dataset_key][2] longitude_west = default_raster_api_loc[dataset_key][3] def get_sample_var_name(variables, selected_variable, selected_level): ## The human readable variable name is not the same as the compact one in API request for i in variables: if i['longName'] == selected_variable: var = i['name'] elif i["longName"] == selected_variable + "@" + selected_level: var = i['name'] return var Explanation: Making dropdown for WAM dataset keys, where you can choose WAM model you would like to use. Note that when using Europe/ North-Atlantic/ North-Pacific/ Mediterranean Sea data points have to be from that area! End of explanation point_data_frame = get_data_from_point_API(dataset_key,longitude,latitude,API_key) Explanation: Point data API By point data we mean data that is given at a single point (or from single measurement device) at different timesteps. For WAM, this means selection of one single geographic point and getting data for one or more parameters. Note that you need to choose point which has coverage on that area. To follow the examples better, we suggest to pay attention to following API keywords, which may not seem obvious in first place: count -- how many values for particular context (set of spatial and temporal dimensions) are returned z -- selection of vertical levels (some variables have values on different heights) End of explanation dataset_variables = get_variables_from_detail_api(server,dataset_key,API_key) vardict = {} levelset = [] for i in dataset_variables: if '@' in i['longName']: if not i['longName'].split("@")[1] in levelset: levelset.append(i['longName'].split("@")[1]) varname, varlevel = i['longName'].split("@") else: if not 'Ground or water surface' in levelset: levelset.append('Ground or water surface') varname, varlevel = i['longName'], 'Ground or water surface' if not varlevel in vardict: vardict[varlevel] = [] vardict[varlevel].append(varname) else: vardict[varlevel].append(varname) Explanation: Getting variables for choosen dataset End of explanation droplist = list(levelset) selecter = widgets.Dropdown( options = droplist, value = droplist[0], description = 'Select level type:', disabled = False, button_style = '' ) selecter2 = widgets.Dropdown( options = sorted(vardict[selecter.value]), value = vardict[selecter.value][0], description = 'Select variable:', disabled = False, button_style = '' ) def select_from_list2(sender): selecter2.options = vardict[selecter.value] def plot_selected_variable(sender): clear_output() sample_var_name = get_sample_var_name(dataset_variables, selecter2.value, selecter.value) #sample_point_data_json = read_data_to_json(generate_point_api_query(**{'var':sample_var_name,'count':100000})) sample_point_data_pd = get_data_from_point_API(dataset_key,longitude,latitude,API_key,var=sample_var_name,count=100000) unit = get_units(dataset_key,sample_var_name,API_key) fig = plt.figure(figsize=(11,4)) ## find how many vertical levels we have if 'z' in sample_point_data_pd: zlevels = sample_point_data_pd['z'].unique() if len(zlevels) != 1: print("Warning: more than one vertical level detected ", zlevels) for i in zlevels: pdata=np.array(sample_point_data_pd[sample_point_data_pd['z'] == i][sample_var_name],dtype=np.float) if np.sum(np.isnan(pdata)) != pdata.shape[0]: plt.plot(sample_point_data_pd[sample_point_data_pd['z'] == i]['time'].apply(dateutil.parser.parse),pdata,label=i) else: print("Cannot plot all empty values!") else: pdata = np.array(sample_point_data_pd[sample_var_name],dtype = np.float) if np.sum(np.isnan(pdata)) != pdata.shape[0]: plt.plot(sample_point_data_pd['time'].apply(dateutil.parser.parse), pdata, '*-', label=sample_var_name) else: print("Cannot plot all empty values!") plt.legend() plt.grid() fig.autofmt_xdate() plt.xlabel('Date') plt.title(sample_var_name) plt.ylabel(unit) plt.show() display(selecter) display(selecter2) selecter.observe(select_from_list2) selecter2.observe(plot_selected_variable, names='value') Explanation: Now let's plot the data. We are making two dropdown lists. From first you have to choose level type. It means that data is separated by contexts. Context here means just a set of spatial and temporal dimensions for particular variable, like NetCDF dimensions. Each variable has values only in one context. So the NaN's do not come from the API request, but from the current way we use to create the Dataframe. It is not difficult to filter out variables from the dataframe, but for any use case besides observing the data, it is more reasonable to query only the right data from the server. End of explanation sample_var_name = get_sample_var_name(dataset_variables, selecter2.value, selecter.value) sample_raster_data = get_data_from_raster_API(dataset_key, longitude_west, latitude_south, longitude_east, latitude_north, API_key,var=sample_var_name, count=1000) data_min = np.amin([np.nanmin(np.array(i,dtype=float)) for i in sample_raster_data[sample_var_name]]) data_max = np.amax([np.nanmax(np.array(i,dtype=float)) for i in sample_raster_data[sample_var_name]]) Explanation: Raster API Now we are using raster API. Please note that the data size returned by raster API is limited, to keep the JSON string size reasonable. If you want to get larger data, please try our new asynchronous API to download NetCDF files: http://docs.planetos.com/?#bulk-data-packaging End of explanation raster_latitude = sample_raster_data['indexAxes'][0][0][1] raster_longitude = sample_raster_data['indexAxes'][0][1][1] m = Basemap(projection='merc',llcrnrlat=float(latitude_south),urcrnrlat=float(latitude_north),\ llcrnrlon=float(longitude_west),urcrnrlon=float(longitude_east),lat_ts=(float(latitude_south)+float(latitude_north))/2,resolution='i') lonmap, latmap = m(np.meshgrid(raster_longitude,raster_latitude)[0],np.meshgrid(raster_longitude, raster_latitude)[1]) Explanation: Longitude and latitude data is necessary for map and it is defined at the beginning of the notebook by user. Map projection can easily be changed by user as well. End of explanation def loadimg(k): unit = get_units(dataset_key,sample_var_name,API_key) fig=plt.figure(figsize=(7,5)) data = np.ma.masked_invalid(np.array(sample_raster_data[sample_var_name][k],dtype=float)) m.pcolormesh(lonmap,latmap,data,vmax=data_max,vmin=data_min) m.drawcoastlines() m.drawcountries() plt.title(selecter2.value + " " + sample_raster_data['time'][k],fontsize=10) cbar = plt.colorbar() cbar.set_label(unit) print("Maximum: ",np.nanmax(data)) print("Minimum: ",np.nanmin(data)) plt.show() widgets.interact(loadimg, k=widgets.IntSlider(min=0,max=(len(sample_raster_data)-1),step=1,value=0, layout=widgets.Layout(width='100%'))) Explanation: Now let's map our data! End of explanation loadimg(0) Explanation: As time slider for image above does not work in GitHub preview, let's make image from first time moment. Although, it will work in your local environment. End of explanation
7,371
Given the following text description, write Python code to implement the functionality described below step by step Description: Changes in religious affiliation and attendance Analysis based on data from the CIRP Freshman Survey Copyright Allen Downey MIT License Step1: Read the data. Note Step2: Compute time variables for regression analysis, centered on 1966 (which makes the estimated intercept more interpretable). Step4: The following functions fits a regression model and uses a permutation method to estimate uncertainty due to random sampling. Step6: Plot a region showing a confidence interval. Step8: Plot a line of best fit, a region showing the confidence interval of the estimate and the predictive interval. Step9: Plot the fraction of respondents with no religious preference along with a quadratic model. Step10: Put all figures on the same x-axis for easier comparison. Step11: Fitting a quadratic model to percentages is a bit nonsensical, since percentages can't exceed 1. It would probably be better to work in terms of log-odds, particularly if we are interested in forecasting what might happen after we cross the 50% line. But for now the simple model is fine. Step12: Plot the fraction of students reporting attendance at religious services, along with a quadratic model. Step13: Plot the gender gap along with a quadratic model. Step14: To see whether the gender gap is still increasing, we can fit a quadatic model to the most recent data. Step15: A linear model for the most recent data suggests that the gap might not be growing.
Python Code: %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt from utils import decorate, savefig import statsmodels.formula.api as smf import warnings warnings.filterwarnings('error') Explanation: Changes in religious affiliation and attendance Analysis based on data from the CIRP Freshman Survey Copyright Allen Downey MIT License End of explanation df = pd.read_csv('freshman_survey.csv', skiprows=2, index_col='year') df[df.columns] /= 10 df.head() df.tail() Explanation: Read the data. Note: I transcribed these data manually from published documents, so data entry errors are possible. End of explanation df['time'] = df.index - 1966 df['time2'] = df.time**2 Explanation: Compute time variables for regression analysis, centered on 1966 (which makes the estimated intercept more interpretable). End of explanation def make_error_model(df, y, formula, n=100): Makes a model that captures sample error and residual error. df: DataFrame y: Series formula: string representation of the regression model n: number of simulations to run returns: (fittedvalues, sample_error, total_error) # make the best fit df['y'] = y results = smf.ols(formula, data=df).fit() fittedvalues = results.fittedvalues resid = results.resid # permute residuals and generate hypothetical fits fits = [] for i in range(n): df['y'] = fittedvalues + np.random.permutation(results.resid) fake_results = smf.ols(formula, data=df).fit() fits.append(fake_results.fittedvalues) # compute the variance of the fits fits = np.array(fits) sample_var = fits.var(axis=0) # add sample_var and the variance of the residuals total_var = sample_var + resid.var() # standard errors are square roots of the variances return fittedvalues, np.sqrt(sample_var), np.sqrt(total_var) Explanation: The following functions fits a regression model and uses a permutation method to estimate uncertainty due to random sampling. End of explanation def fill_between(fittedvalues, stderr, **options): Fills in the 95% confidence interval. fittedvalues: series stderr: standard error low = fittedvalues - 2 * stderr high = fittedvalues + 2 * stderr plt.fill_between(fittedvalues.index, low, high, **options) Explanation: Plot a region showing a confidence interval. End of explanation def plot_model(df, y, formula, **options): Run a model and plot the results. df: DataFrame y: Series of actual data formula: Patsy string for the regression model options: dictional of options used to plot the data fittedvalues, sample_error, total_error = make_error_model( df, y, formula) fill_between(fittedvalues, total_error, color='0.9') fill_between(fittedvalues, sample_error, color='0.8') fittedvalues.plot(color='0.7', label='_nolegend') y.plot(**options) Explanation: Plot a line of best fit, a region showing the confidence interval of the estimate and the predictive interval. End of explanation y = df['noneall'] y1 = y.loc[1966:2014] y1 y2 = y.loc[2015:] y2 Explanation: Plot the fraction of respondents with no religious preference along with a quadratic model. End of explanation xlim = [1965, 2022] formula = 'y ~ time + time2' plot_model(df, y, formula, color='C0', alpha=0.7, label='None') y2.plot(color='C1', label='Atheist,Agnostic,None') decorate(title='No religious preference', xlabel='Year of survey', ylabel='Percent', xlim=xlim, ylim=[0, 38]) savefig('heri.1') Explanation: Put all figures on the same x-axis for easier comparison. End of explanation ps = df.noneall / 100 odds = ps / (1-ps) log_odds = np.log(odds) log_odds plot_model(df, log_odds, formula, color='C0', label='None') decorate(xlabel='Year of survey', xlim=xlim, ylabel='Log odds') Explanation: Fitting a quadratic model to percentages is a bit nonsensical, since percentages can't exceed 1. It would probably be better to work in terms of log-odds, particularly if we are interested in forecasting what might happen after we cross the 50% line. But for now the simple model is fine. End of explanation attend = df['attendedall'].copy() # I'm discarding the data point from 1966, # which seems unreasonably low attend[1966] = np.nan plot_model(df, attend, formula, color='C2', alpha=0.7, label='_nolegend') decorate(title='Attendance at religious services', xlabel='Year of survey', ylabel='Percent', xlim=xlim, ylim=[60, 100]) savefig('heri.3') Explanation: Plot the fraction of students reporting attendance at religious services, along with a quadratic model. End of explanation diff = df.nonemen - df.nonewomen diff = diff.loc[1973:] plot_model(df, diff, formula, color='C4', alpha=1, label='_nolegend') decorate(title='Gender gap', xlabel='Year of survey', ylabel='Difference (percentage points)', xlim=xlim) savefig('heri.2') Explanation: Plot the gender gap along with a quadratic model. End of explanation diff = df.nonemen - df.nonewomen diff = diff.loc[1986:] plot_model(df, diff, formula, color='C4', label='Gender gap') decorate(xlabel='Year of survey', ylabel='Difference (percentage points)') Explanation: To see whether the gender gap is still increasing, we can fit a quadatic model to the most recent data. End of explanation diff = df.nonemen - df.nonewomen diff = diff.loc[1986:] plot_model(df, diff, 'y ~ time', color='C4', label='Gender gap') decorate(xlabel='Year of survey', ylabel='Difference (percentage points)') Explanation: A linear model for the most recent data suggests that the gap might not be growing. End of explanation
7,372
Given the following text description, write Python code to implement the functionality described below step by step Description: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the data, plot, and create a logistic regression model Step1: 2. Read in the hanford.csv file in the data/ folder Step2: <img src="../../images/hanford_variables.png"></img> 3. Calculate the basic descriptive statistics on the data Step3: 4. Find a reasonable threshold to say exposure is high and recode the data Step4: 5. Create a logistic regression model Step5: 6. Predict whether the mortality rate (Cancer per 100,000 man years) will be high at an exposure level of 50
Python Code: import pandas as pd %matplotlib inline import numpy as np from sklearn.linear_model import LogisticRegression Explanation: Apply logistic regression to categorize whether a county had high mortality rate due to contamination 1. Import the necessary packages to read in the data, plot, and create a logistic regression model End of explanation df = pd.read_csv("../data/hanford.csv") Explanation: 2. Read in the hanford.csv file in the data/ folder End of explanation df.describe() Explanation: <img src="../../images/hanford_variables.png"></img> 3. Calculate the basic descriptive statistics on the data End of explanation df['Mortality'].hist(bins=5) df['Mortality'].mean() df['Mort_high'] = df['Mortality'].apply(lambda x:1 if x>=147.1 else 0) df['Expo_high'] = df['Exposure'].apply(lambda x:1 if x>=3.41 else 0) def exposure_high(x): if x >= 3.41: return 1 else: return 0 df Explanation: 4. Find a reasonable threshold to say exposure is high and recode the data End of explanation lm = LogisticRegression() x = np.asarray(df[['Exposure']]) y = np.asarray(df['Mort_high']) lm = lm.fit(x,y) Explanation: 5. Create a logistic regression model End of explanation lm.predict([50]) Explanation: 6. Predict whether the mortality rate (Cancer per 100,000 man years) will be high at an exposure level of 50 End of explanation
7,373
Given the following text description, write Python code to implement the functionality described below step by step Description: Table of Contents <p><div class="lev1 toc-item"><a href="#Générer-des-fausses-citations-latines-du-Roi-Loth,-avec-Python,-Wikiquote-et-des-chaînes-de-Markov" data-toc-modified-id="Générer-des-fausses-citations-latines-du-Roi-Loth,-avec-Python,-Wikiquote-et-des-chaînes-de-Markov-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Générer des fausses citations latines du Roi Loth, avec Python, Wikiquote et des chaînes de Markov</a></div><div class="lev2 toc-item"><a href="#Dépendances" data-toc-modified-id="Dépendances-11"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Dépendances</a></div><div class="lev2 toc-item"><a href="#Récupérer-et-nettoyer-les-données" data-toc-modified-id="Récupérer-et-nettoyer-les-données-12"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Récupérer et nettoyer les données</a></div><div class="lev2 toc-item"><a href="#Exploration-de-chaînes-de-Markov-pour-la-génération-aléatoire" data-toc-modified-id="Exploration-de-chaînes-de-Markov-pour-la-génération-aléatoire-13"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>Exploration de chaînes de Markov pour la génération aléatoire</a></div><div class="lev2 toc-item"><a href="#Fausses-locutions-latines" data-toc-modified-id="Fausses-locutions-latines-14"><span class="toc-item-num">1.4&nbsp;&nbsp;</span>Fausses locutions latines</a></div><div class="lev2 toc-item"><a href="#Fausses-citations-du-Roi-Loth" data-toc-modified-id="Fausses-citations-du-Roi-Loth-15"><span class="toc-item-num">1.5&nbsp;&nbsp;</span>Fausses citations du Roi Loth</a></div><div class="lev3 toc-item"><a href="#Premier-exemple" data-toc-modified-id="Premier-exemple-151"><span class="toc-item-num">1.5.1&nbsp;&nbsp;</span>Premier exemple</a></div><div class="lev3 toc-item"><a href="#Exemples" data-toc-modified-id="Exemples-152"><span class="toc-item-num">1.5.2&nbsp;&nbsp;</span>Exemples</a></div><div class="lev3 toc-item"><a href="#Générer-aléatoirement-les-métadonnées-de-l'épisode" data-toc-modified-id="Générer-aléatoirement-les-métadonnées-de-l'épisode-153"><span class="toc-item-num">1.5.3&nbsp;&nbsp;</span>Générer aléatoirement les métadonnées de l'épisode</a></div><div class="lev3 toc-item"><a href="#Générer-aléatoirement-les-explications-foireuses-du-Roi-Loth" data-toc-modified-id="Générer-aléatoirement-les-explications-foireuses-du-Roi-Loth-154"><span class="toc-item-num">1.5.4&nbsp;&nbsp;</span>Générer aléatoirement les explications foireuses du Roi Loth</a></div><div class="lev3 toc-item"><a href="#Combiner-le-tout-!" data-toc-modified-id="Combiner-le-tout-!-155"><span class="toc-item-num">1.5.5&nbsp;&nbsp;</span>Combiner le tout !</a></div><div class="lev3 toc-item"><a href="#Exemples" data-toc-modified-id="Exemples-156"><span class="toc-item-num">1.5.6&nbsp;&nbsp;</span>Exemples</a></div><div class="lev3 toc-item"><a href="#Joli-affichage" data-toc-modified-id="Joli-affichage-157"><span class="toc-item-num">1.5.7&nbsp;&nbsp;</span>Joli affichage</a></div><div class="lev3 toc-item"><a href="#Conclusion" data-toc-modified-id="Conclusion-158"><span class="toc-item-num">1.5.8&nbsp;&nbsp;</span>Conclusion</a></div> # Générer des fausses citations latines du Roi Loth, avec Python, Wikiquote et des chaînes de Markov J'aimerai montrer ici comment générer des fausses citations latines, dignes du [Roi Loth](https Step1: Dépendances Step2: Le module lea sera très pratique pour manipuler les probabilités pour les chaînes de Markov. Step3: Récupérer et nettoyer les données J'ai utilisé cette page Wikipédia et deux lignes de Bash Step4: Ensuite il faut un peu de nettoyage pour enlever les lignes qui ont été incorrectement ajoutées dans le fichier (j'ai fait ça à la main). Step5: On a 1571 citations latines, c'est déjà un corpus conséquent ! Exploration de chaînes de Markov pour la génération aléatoire J'utilise cette fonction markov écrite par Jill-Jênn Vie. Step6: Par exemple Step7: Et on peut générer 3 phrases aléatoires Step8: Fausses locutions latines On va extraire le corpus, la liste des premiers mots, et la probabilité qu'un mot en début de citation commence par une majuscule. Step9: Mais en fait, le Roi Loth commence toujours ses citations latines par une majuscule Step10: On va générer des locutions de 3 à 6 mots Step11: On a bientôt ce qu'il faut pour générer une locution latine aléatoire. Il arrive que la chaîne de Markov se bloque, donc on va juste essayer plusieurs fois avec des débuts différents. Step12: On peut essayer Step13: Ça a déjà l'air pas mal latin ! Fausses citations du Roi Loth Pour générer une citation du Roi Loth, il ne suffit pas d'avoir des locutions latines. Il faut le contexte, l'explication, une fausse citation d'un épisode de Kaamelott etc... Premier exemple Ecouter celle là Step15: Générer aléatoirement les explications foireuses du Roi Loth C'est moins facile... Mais sans chercher à être parfait, on va juste prendre une explication parmi celles qui existent Step18: Et quelques variations Step19: Combiner le tout ! C'est très facile Step20: Exemples Step21: Joli affichage
Python Code: citation = citation_aleatoire(italic=True) display(Markdown("> {}".format(citation))) Explanation: Table of Contents <p><div class="lev1 toc-item"><a href="#Générer-des-fausses-citations-latines-du-Roi-Loth,-avec-Python,-Wikiquote-et-des-chaînes-de-Markov" data-toc-modified-id="Générer-des-fausses-citations-latines-du-Roi-Loth,-avec-Python,-Wikiquote-et-des-chaînes-de-Markov-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Générer des fausses citations latines du Roi Loth, avec Python, Wikiquote et des chaînes de Markov</a></div><div class="lev2 toc-item"><a href="#Dépendances" data-toc-modified-id="Dépendances-11"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Dépendances</a></div><div class="lev2 toc-item"><a href="#Récupérer-et-nettoyer-les-données" data-toc-modified-id="Récupérer-et-nettoyer-les-données-12"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Récupérer et nettoyer les données</a></div><div class="lev2 toc-item"><a href="#Exploration-de-chaînes-de-Markov-pour-la-génération-aléatoire" data-toc-modified-id="Exploration-de-chaînes-de-Markov-pour-la-génération-aléatoire-13"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>Exploration de chaînes de Markov pour la génération aléatoire</a></div><div class="lev2 toc-item"><a href="#Fausses-locutions-latines" data-toc-modified-id="Fausses-locutions-latines-14"><span class="toc-item-num">1.4&nbsp;&nbsp;</span>Fausses locutions latines</a></div><div class="lev2 toc-item"><a href="#Fausses-citations-du-Roi-Loth" data-toc-modified-id="Fausses-citations-du-Roi-Loth-15"><span class="toc-item-num">1.5&nbsp;&nbsp;</span>Fausses citations du Roi Loth</a></div><div class="lev3 toc-item"><a href="#Premier-exemple" data-toc-modified-id="Premier-exemple-151"><span class="toc-item-num">1.5.1&nbsp;&nbsp;</span>Premier exemple</a></div><div class="lev3 toc-item"><a href="#Exemples" data-toc-modified-id="Exemples-152"><span class="toc-item-num">1.5.2&nbsp;&nbsp;</span>Exemples</a></div><div class="lev3 toc-item"><a href="#Générer-aléatoirement-les-métadonnées-de-l'épisode" data-toc-modified-id="Générer-aléatoirement-les-métadonnées-de-l'épisode-153"><span class="toc-item-num">1.5.3&nbsp;&nbsp;</span>Générer aléatoirement les métadonnées de l'épisode</a></div><div class="lev3 toc-item"><a href="#Générer-aléatoirement-les-explications-foireuses-du-Roi-Loth" data-toc-modified-id="Générer-aléatoirement-les-explications-foireuses-du-Roi-Loth-154"><span class="toc-item-num">1.5.4&nbsp;&nbsp;</span>Générer aléatoirement les explications foireuses du Roi Loth</a></div><div class="lev3 toc-item"><a href="#Combiner-le-tout-!" data-toc-modified-id="Combiner-le-tout-!-155"><span class="toc-item-num">1.5.5&nbsp;&nbsp;</span>Combiner le tout !</a></div><div class="lev3 toc-item"><a href="#Exemples" data-toc-modified-id="Exemples-156"><span class="toc-item-num">1.5.6&nbsp;&nbsp;</span>Exemples</a></div><div class="lev3 toc-item"><a href="#Joli-affichage" data-toc-modified-id="Joli-affichage-157"><span class="toc-item-num">1.5.7&nbsp;&nbsp;</span>Joli affichage</a></div><div class="lev3 toc-item"><a href="#Conclusion" data-toc-modified-id="Conclusion-158"><span class="toc-item-num">1.5.8&nbsp;&nbsp;</span>Conclusion</a></div> # Générer des fausses citations latines du Roi Loth, avec Python, Wikiquote et des chaînes de Markov J'aimerai montrer ici comment générer des fausses citations latines, dignes du [Roi Loth](https://fr.wikipedia.org/wiki/Personnages_de_Kaamelott#Loth_d%E2%80%99Orcanie) de [Kaamelott](https://fr.wikiquote.org/wiki/Kaamelott), avec Python, des données extraites de [sa page Wikiquote](https://fr.wikiquote.org/wiki/Kaamelott/Loth) et des [chaînes de Markov](https://github.com/jilljenn/markov.py). > Cf. [ce ticket](https://github.com/Naereen/notebooks/issues/13) pour l'idée initiale. Exemple de sortie : End of explanation %load_ext watermark %watermark -v -m -a "Lilian Besson (Naereen)" -p lea -g import os import random from string import ascii_lowercase from collections import Counter, defaultdict Explanation: Dépendances End of explanation from lea import Lea Explanation: Le module lea sera très pratique pour manipuler les probabilités pour les chaînes de Markov. End of explanation %%bash wget --no-verbose "https://en.wikipedia.org/wiki/List_of_Latin_phrases_(full)" -O /tmp/latin.html grep -o '<b>[^<]*</b>' /tmp/latin.html | sed s_'</\?b>'_''_g | sort | uniq | sort | uniq > /tmp/data_latin.txt !head data/latin.txt Explanation: Récupérer et nettoyer les données J'ai utilisé cette page Wikipédia et deux lignes de Bash : End of explanation !head data/latin.txt !ls -larth data/latin.txt !wc data/latin.txt Explanation: Ensuite il faut un peu de nettoyage pour enlever les lignes qui ont été incorrectement ajoutées dans le fichier (j'ai fait ça à la main). End of explanation def markov(corpus, start, length): # Counting occurrences next_one = defaultdict(Counter) for sentence in corpus: words = sentence.split() nb_words = len(words) for i in range(nb_words - 1): next_one[words[i]][words[i + 1]] += 1 # Initializing states states = {} for word in next_one: states[word] = Lea.fromValFreqsDict(next_one[word]) # Outputting visited states word = start words = [word] for _ in range(length - 1): word = states[word].random() words.append(word) return(words) Explanation: On a 1571 citations latines, c'est déjà un corpus conséquent ! Exploration de chaînes de Markov pour la génération aléatoire J'utilise cette fonction markov écrite par Jill-Jênn Vie. End of explanation corpus = [ 'je mange des cerises', 'je mange des bananes', 'je conduis des camions', ] start = 'je' length = 4 Explanation: Par exemple : End of explanation for _ in range(3): words = markov(corpus, start, length) print(' '.join(words)) Explanation: Et on peut générer 3 phrases aléatoires : End of explanation WORD_LIST = "data/latin.txt" corpus = open(WORD_LIST).readlines() print("Exemple d'une citation :", corpus[0]) print("Il y a", len(corpus), "citations.") starts = [c.split()[0] for c in corpus] start = random.choice(starts) print("Exemple d'un mot de début de citation :", start) print("Il y a", len(starts), "mots de débuts de citations.") proba_title = len([1 for s in starts if s.istitle()]) / len(starts) print("Il y a {:.3%} chance de commencer une citation par une majuscule.".format(proba_title)) Explanation: Fausses locutions latines On va extraire le corpus, la liste des premiers mots, et la probabilité qu'un mot en début de citation commence par une majuscule. End of explanation proba_title = 1 Explanation: Mais en fait, le Roi Loth commence toujours ses citations latines par une majuscule : End of explanation length_min = 3 length_max = 6 Explanation: On va générer des locutions de 3 à 6 mots : End of explanation def markov_try_while_failing(corpus, starts, length_min, length_max, proba_title, nb_max_trial=100): # Try 100 times to generate a sentence start = random.choice(starts) length = random.randint(length_min, length_max) for trial in range(nb_max_trial): try: words = markov(corpus, start, length) if random.random() <= proba_title: words[0] = words[0].title() return words # comment to debug print(' '.join(words)) break except KeyError: start = random.choice(starts) length = random.randint(length_min, length_max) continue raise ValueError("Echec") Explanation: On a bientôt ce qu'il faut pour générer une locution latine aléatoire. Il arrive que la chaîne de Markov se bloque, donc on va juste essayer plusieurs fois avec des débuts différents. End of explanation for _ in range(10): words = markov_try_while_failing(corpus, starts, length_min, length_max, proba_title) print(' '.join(words)) Explanation: On peut essayer : End of explanation episodes = [ "Livre III, L’Assemblée des rois 2e partie, écrit par Alexandre Astier.", "Livre III, L’Assemblée des rois 2e partie, écrit par Alexandre Astier.", # présent deux fois "Livre IV, Le désordre et la nuit, écrit par Alexandre Astier.", "Livre V, Misère noire, écrit par Alexandre Astier.", "Livre VI, Arturus Rex, écrit par Alexandre Astier.", "Livre VI, Lacrimosa, écrit par Alexandre Astier." ] def metadonnee_aleatoire(episodes=episodes): episode = random.choice(episodes) return "D'après François Rollin, inspiré par Kaamelott, " + episode Explanation: Ça a déjà l'air pas mal latin ! Fausses citations du Roi Loth Pour générer une citation du Roi Loth, il ne suffit pas d'avoir des locutions latines. Il faut le contexte, l'explication, une fausse citation d'un épisode de Kaamelott etc... Premier exemple Ecouter celle là : Misa brevis, et spiritus maxima. <audio src="data/tres_en_colere.mp3" controls="controls">Your browser does not support the audio element.</audio> Exemples Ave Cesar, rosae rosam, et spiritus rex ! Ah non, parce que là, j’en ai marre ! -- François Rollin, Kaamelott, Livre III, L’Assemblée des rois 2e partie, écrit par Alexandre Astier. Tempora mori, tempora mundis recorda. Voilà. Eh bien ça, par exemple, ça veut absolument rien dire, mais l’effet reste le même, et pourtant j’ai jamais foutu les pieds dans une salle de classe attention ! -- François Rollin, Kaamelott, Livre III, L’Assemblée des rois 2e partie, écrit par Alexandre Astier. Victoriae mundis et mundis lacrima. Bon, ça ne veut absolument rien dire, mais je trouve que c’est assez dans le ton. -- François Rollin, Kaamelott, Livre IV, Le désordre et la nuit, écrit par Alexandre Astier. Misa brevis et spiritus maxima, ça veut rien dire, mais je suis très en colère contre moi-même. -- François Rollin, Kaamelott, Livre V, Misère noire, écrit par Alexandre Astier. Deus minimi placet : seul les dieux décident. -- François Rollin, Kaamelott, Livre VI, Arturus Rex, écrit par Alexandre Astier. "Mundi placet et spiritus minima", ça n'a aucun sens mais on pourrait très bien imaginer une traduction du type : "Le roseau plie, mais ne cède... qu'en cas de pépin" ce qui ne veut rien dire non plus. -- François Rollin, Kaamelott, Livre VI, Lacrimosa, écrit par Alexandre Astier. Générer aléatoirement les métadonnées de l'épisode C'est facile. End of explanation explications = [ ". Ah non, parce que là, j’en ai marre !", ". Voilà. Eh bien ça, par exemple, ça veut absolument rien dire, mais l’effet reste le même, et pourtant j’ai jamais foutu les pieds dans une salle de classe attention !", ". Bon, ça ne veut absolument rien dire, mais je trouve que c’est assez dans le ton.", ", ça veut rien dire, mais je suis très en colère contre moi-même.", " : seul les dieux décident.", , ça n'a aucun sens mais on pourrait très bien imaginer une traduction du type : "Le roseau plie, mais ne cède... qu'en cas de pépin", ce qui ne veut rien dire non plus., ] Explanation: Générer aléatoirement les explications foireuses du Roi Loth C'est moins facile... Mais sans chercher à être parfait, on va juste prendre une explication parmi celles qui existent : End of explanation explications += [ ". Ah non, parce qu'au bout d'un moment, zut !", ". Voilà, ça ne veut rien dire, mais c'est assez dans le ton !", ". Bon, ça n'a aucun sens, mais j'aime bien ce petit ton décalé.", ". Le latin, ça impressionne ! Surtout les grouillots.", ", ça n'a aucun sens, mais je suis très en colère contre moi-même.", ", ça n'a aucun sens, mais je fais ça par amour.", " : la victoire par la sagesse.", " : les livres contiennent la sagesse des anciens.", " : à Rome seul compte le pouvoir.", " : seul les puissants agissent.", " : le mariage est une bénédiction.", " : ça veut rien dire, mais ça impressionne !", , ça veut rien dire mais on pourrait très bien imaginer une traduction du type : "Le vent tourne pour ceux qui savent écouter", ce qui ne veut rien dire non plus., , ça n'a aucun sens mais pourquoi pas une traduction du genre : "Les imbéciles dorment, les forts agissent mais dorment aussi", ce qui n'a aucun sens non plus., ] def explication_aleatoire(): return random.choice(explications) Explanation: Et quelques variations : End of explanation def citation_aleatoire(italic=False): metadonnee = metadonnee_aleatoire() explication = explication_aleatoire() words = markov_try_while_failing(corpus, starts, length_min, length_max, proba_title) locution = ' '.join(words) if italic: citation = '"*{}*"{} -- {}'.format(locution, explication, metadonnee) else: citation = '"{}"{} -- {}'.format(locution, explication, metadonnee) return citation Explanation: Combiner le tout ! C'est très facile : End of explanation for _ in range(10): print(">", citation_aleatoire(italic=True)) Explanation: Exemples End of explanation from IPython.display import display, Markdown for _ in range(10): citation = citation_aleatoire(italic=True) display(Markdown("> {}".format(citation))) Explanation: Joli affichage End of explanation
7,374
Given the following text description, write Python code to implement the functionality described below step by step Description: Chapter 14 Step1: Python also has a module called types, which has the definitions of the basic types of the interpreter. Example Step2: Through introspection, it is possible to determine the fields of a database table, for example. Inspect The module inspect provides a set of high-level functions that allow for introspection to investigate types, collection items, classes, functions, source code and the runtime stack of the interpreter. Example
Python Code: trospection or reflection is the ability of software to identify and report their own internal structures, such as types, variabl# Getting some information # about global objects in the program from types import ModuleType def info(n_obj): # Create a referênce to the object obj = globals()[n_obj] # Show object information print ('Name of object:', n_obj) print ('Identifier:', id(obj)) print ('Typo:', type(obj)) print ('Representation:', repr(obj)) # If it is a module if isinstance(obj, ModuleType): print( 'itens:') for item in dir(obj): print (item) print # Showing information for n_obj in dir()[:10]: # The slice [:10] is used just to limit objects info(n_obj) Explanation: Chapter 14: Introspection Introspection or reflection is the ability of software to identify and report their own internal structures, such as types, variable scope, methods and attributes. Native interpreter functions for introspection: <table> <tr> <th>Function</th> <th>Returns</th> </tr> <tr> <td><code>type(object)</code></td> <td>The typo (class) of the object</td> </tr> <tr> <td><code>id(object)</code></td> <td>object identifier</td> </tr> <tr> <td><code>locals()</code></td> <td>local variables dictionary</td> </tr> <tr> <td><code>globals()</code></td> <td>global variables dictionary</td> </tr> <tr> <td><code>vars(object)</code></td> <td>object symbols dictionary</td> </tr> <tr> <td><code>len(object)</code></td> <td>size of an object</td> </tr> <tr> <td><code>dir(object)</code></td> <td>A list of object structures</td> </tr> <tr> <td><code>help(object)</code></td> <td>Object doc strings</td> </tr> <tr> <td><code>repr(object)</code></td> <td>Object representation</td> </tr> <tr> <td><code>isinstance(object, class)</code></td> <td>True if object is derived from class</td> </tr> <tr> <td><code>issubclass(subclass, class)</code></td> <td>True if object inherits the class</td> </tr> </table> The object identifier is a unique number that is used by the interpreter for identifying the objects internally. Example: End of explanation import types s = '' if isinstance(s, types.StringType): print 's is a string.' Explanation: Python also has a module called types, which has the definitions of the basic types of the interpreter. Example: End of explanation import os.path # inspect: "friendly" introspection module import inspect print 'Object:', inspect.getmodule(os.path) print 'Class?', inspect.isclass(str) # Lists all functions that exist in "os.path" print 'Member:', for name, struct in inspect.getmembers(os.path): if inspect.isfunction(struct): print name, Explanation: Through introspection, it is possible to determine the fields of a database table, for example. Inspect The module inspect provides a set of high-level functions that allow for introspection to investigate types, collection items, classes, functions, source code and the runtime stack of the interpreter. Example: End of explanation
7,375
Given the following text description, write Python code to implement the functionality described below step by step Description: Полезные практики, неочевидные моменты Неоднозная грамматика Есть примитивная рекурсивная грамматика Step1: Число вариантов быстро растёт. Для строки "a x 10", парсер переберёт 89 разборов. Для "a x 20" — 979 и потратит заметное количество времени. При работе с естественным русским языком, мы построянно сталкиваемся с неоднозначными грамматиками. Например, список из трёх взысканий по арбиражному делу Step2: Порядок аргументов в or_ имеет значение Когда разборов больше одного, парсер возвращает самый левый вариант Step3: Переставим местами a a и a, результат поменяется Step4: На практике это важно. В примере со взыскиниями грамматика Step5: ValueError Step6: Ожидаем F(a='a'), получаем ValueError Step7: Создадим прокси-факт Step8: TypeError Step9: Явно завернём предикат в rule Step10: Машинное обучение и Yargy Есть текст размеченный BIO-тегами Step11: Parser принимает необязательный аргумент tagger Step12: Пропустить часть текста Есть текст "взыскать 5 тыс. р. штрафа, а также пени и неустойку". Нужно выделить 3 взыскания "5 тыс. р. штраф", "пени", "неустойка", пропустить подстроки ", а также", "и". Запустить парсер 2 раза Step13: Генерация правил В Yargy все правила описываются на языке Python. Создадим функцию, которая генерирует правило. Например, правило для текста в скобочка и кавычках Step14: Правило — аналог join в Python Step15: Правило для BIO-разметки Step16: Генерация pipeline Создадим pipeline из словаря пар "полное название", "сокращение" Step17: Наследование fact fact создаёт Python-класс, отнаследуемся, добавим методы и атрибуты. Например, есть ссылка на статьи "ст. 15-17 п.1", результат список объектов Ref(art=15, punkt=1), Ref(art=16, punkt=1), ... Step18: Есть периоды "1917-1918г.", "21 век", приведём их к единому формату
Python Code: from yargy.parser import prepare_trees from yargy import Parser, or_, rule A = or_( rule('a'), rule('a', 'a') ) B = A.repeatable() display(B.normalized.as_bnf) parser = Parser(B) matches = parser.extract('a a a') for match in matches: # кроме 3-х полных разборов, парсёр найдёт ещё 7 частичных: (a) _ _, (a a) _, (a) (a) _, ... # не будем их показывать if len(match.tokens) == 3: display(match.tree.as_dot) Explanation: Полезные практики, неочевидные моменты Неоднозная грамматика Есть примитивная рекурсивная грамматика: A -&gt; a | a a B -&gt; A B | A Есть строка "a a a". Парсер может разобрать её 3 способами: (a) (a) (a) (a) (a a) (a a) (a) Yargy парсер перебирает все варианты разбора. Используем непубличный метод extract, посмотрим все варианты: End of explanation class TooManyStates(Exception): pass def capped(method): def wrap(self, column, *args): before = len(column.states) method(self, column, *args) after = len(column.states) self.states += (after - before) if self.cap and self.states > self.cap: raise TooManyStates return wrap class CappedParser(Parser): def reset(self): self.states = 0 def __init__(self, *args, cap=None, **kwargs): self.cap = cap self.reset() Parser.__init__(self, *args, **kwargs) def chart(self, *args, **kwargs): self.reset() return Parser.chart(self, *args, **kwargs) predict = capped(Parser.predict) scan = capped(Parser.scan) complete = capped(Parser.complete) parser = CappedParser(B, cap=100) for size in range(3, 10): text = 'a ' * size print(text) try: parser.match(text) except TooManyStates: print('TooManyStates') else: print('OK') Explanation: Число вариантов быстро растёт. Для строки "a x 10", парсер переберёт 89 разборов. Для "a x 20" — 979 и потратит заметное количество времени. При работе с естественным русским языком, мы построянно сталкиваемся с неоднозначными грамматиками. Например, список из трёх взысканий по арбиражному делу: "5 тыс. р. штраф пени 3 тыс. р. необоснованного обогащения". Эскиз грамматики: ``` MONEY -> INT тыс. р. TYPE -> штраф | пени | необоснованное обогащение 1. "5 тыс. р. штраф" 2. "штраф 5 тыс. р." 3. "3 тыс. р." — только сумма 4. "пени" — только тип PENALTY -> MONEY TYPE | TYPE MONEY | MONEY | TYPE PENALTIES -> PENALTY+ ``` Получаем много вариантов разбора: (5 тыс. р. штраф) (пени) (3 тыс. р. необоснованного обогащения) (5 тыс. р. штраф) (пени) (3 тыс. р.) (необоснованного обогащения) (5 тыс. р.) (штраф) (пени) (3 тыс. р.) (необоснованного обогащения) (5 тыс. р. штраф) (пени 3 тыс. р.) (необоснованного обогащения) ... Самый просто способ избежать комбинаторного взрыва числа разборов — ограничить repeatable. Вместо PENALTIES = PENALTY.repeatable(), напишем PENALTIES = PENALTY.repeatable(max=5). Такое правило отбросить 6-е и последующие взыскания, но завершится в ограниченное время. CappedParser Есть ещё один способ избежать комбинаторного взрыва числа разборов: выключать парсер, когда число состояний превысило порог. CappedParser наследует Parser, оборачивает внутренние методы chart, predict, scan, complete — шаги алгоритма Earley-парсера: End of explanation A = or_( rule('a'), rule('a', 'a') ) B = A.repeatable() parser = Parser(B) match = parser.match('a a a') match.tree.as_dot Explanation: Порядок аргументов в or_ имеет значение Когда разборов больше одного, парсер возвращает самый левый вариант: End of explanation A = or_( rule('a', 'a'), rule('a') ) B = A.repeatable() parser = Parser(B) match = parser.match('a a a') match.tree.as_dot Explanation: Переставим местами a a и a, результат поменяется: End of explanation from yargy.tokenizer import ( Tokenizer, MorphTokenizer, EOL ) # Стандартный токенизатор. Удаляем правило для переводом строк. # Обычно токены с '\n' только мешаются. TOKENIZER = MorphTokenizer().remove_types(EOL) class IdTokenizer(Tokenizer): def __init__(self, tokenizer): self.tokenizer = tokenizer # Используется при инициализации morph_pipeline, caseless_pipeline. # Строки-аргументы pipeline нужно разделить на слова. Как разделить, # например, "кейс| |dvd-диска" или "кейс| |dvd|-|диска"? Используем стандартный токенизатор. def split(self, text): return self.tokenizer.split(text) # Используется при инициализации предикатов. Например, есть предикат type('INT'). # Поддерживает ли токенизатор тип INT? def check_type(self, type): return self.tokenizer.check_type(type) @property def morph(self): return self.tokenizer.morph def __call__(self, tokens): return tokens ID_TOKENIZER = IdTokenizer(TOKENIZER) tokens = TOKENIZER('a a a a') parser = Parser(B, tokenizer=ID_TOKENIZER) parser.match(tokens); Explanation: На практике это важно. В примере со взыскиниями грамматика: PENALTY -&gt; MONEY TYPE | TYPE MONEY | MONEY | TYPE Левый разбор, не то, что ожидалось: (5 тыс. р. штраф) (пени 3 тыс. р.) (необоснованного обогащения)` Переставим аргументы: PENALTY -&gt; MONEY TYPE | TYPE | TYPE MONEY | MONEY Получим: (5 тыс. р. штраф) (пени) (3 тыс. р. необоснованного обогащения)` IdTokenizer Parser принимает на вход текст. Первым делом парсер разделяет текст на токены. Токенизатор передаётся необязательным аргументом tokenizer: Parser(RULE, tokenizer=Tokenizer()). Токенизатор по-умолчанию — yargy.tokenizer.MorphTokenizer. Бывает нужно обработать уже токенизированный текст. Например, есть два парсера, нужно обоими обработать один текст. Хотим сэкономить время, не токенизировать текст дважды. Заведём парсер-обёртку, он ничего не делает, принимает и возращает токены: End of explanation from yargy.interpretation import fact F = fact('F', ['a']) G = fact('G', ['b']) A = rule('a').interpretation(F.a).interpretation(F) B = rule('b').interpretation(G.b).interpretation(G) C = or_(A, B) parser = Parser(C) match = parser.match('a') # match.fact ValueError Explanation: ValueError: no .interpretation(...) for root rule Есть два правила, хотим найти факты, где сработало одно из них: End of explanation C.as_dot Explanation: Ожидаем F(a='a'), получаем ValueError: no .interpretation(...) for root rule. На вершине-корне нет пометки контруктора факта: End of explanation Proxy = fact('Proxy', ['value']) C = or_(A, B).interpretation(Proxy.value).interpretation(Proxy) display(C.as_dot) parser = Parser(C) match = parser.match('a') match.fact.value Explanation: Создадим прокси-факт: End of explanation from yargy.predicates import caseless A = rule('a') B = caseless('b') # or_(A, B) # TypeError: mixed types: [<class 'yargy.rule.constructors.Rule'>, <class 'yargy.predicates.bank.eq'>] Explanation: TypeError: mixed types Набор аргументов or_ бывает двух видов: 1. Все предикаты, тогда результат — предикат 2. Все rule, тогда результат — rule Иногда правило состоит из одного предиката, передаём его в or_, получаем ошибку: End of explanation B = rule(caseless('b')) C = or_(A, B) Explanation: Явно завернём предикат в rule: End of explanation text = '15 апреля в Симферополе Леонид Рожков ...' tags = 'B I O B B I O'.split() Explanation: Машинное обучение и Yargy Есть текст размеченный BIO-тегами: End of explanation from yargy.tagger import Tagger from yargy.predicates import tag class Tagger(Tagger): # Все возможные теги. Используется при инициализации предиката tag. # Если пользователь создаст tag('FOO'), будет ошибка tags = {'B', 'I', 'O'} def __call__(self, tokens): for token, tag in zip(tokens, tags): yield token.tagged(tag) RULE = rule( tag('B'), tag('I').repeatable().optional() ) parser = Parser(RULE, tagger=Tagger()) matches = parser.findall(text) for match in matches: print([_.value for _ in match.tokens]) Explanation: Parser принимает необязательный аргумент tagger: Parser(RULE, tagger=Tagger). Tagger принимает и возвращает список токенов. Добавим внешнюю разметку tags в токены. Используем предикат tag, извлечём сущности: End of explanation from yargy.pipelines import morph_pipeline text = 'взыскать 5 тыс. р. штрафа, а также пени и неустойку' tokens = list(TOKENIZER(text)) PAYMENT = morph_pipeline([ '5 тыс. р. штраф', 'пени', 'неустойка' ]) parser = Parser(PAYMENT, tokenizer=ID_TOKENIZER) matches = parser.findall(tokens) spans = [_.span for _ in matches] print(spans) def is_inside_span(token, span): token_span = token.span return span.start <= token_span.start and token_span.stop <= span.stop def select_span_tokens(tokens, spans): for token in tokens: if any(is_inside_span(token, _) for _ in spans): yield token tokens = list(select_span_tokens(tokens, spans)) print([_.value for _ in tokens]) PAYMENTS = PAYMENT.repeatable() parser = Parser(PAYMENTS, tokenizer=ID_TOKENIZER) match = parser.match(tokens) Explanation: Пропустить часть текста Есть текст "взыскать 5 тыс. р. штрафа, а также пени и неустойку". Нужно выделить 3 взыскания "5 тыс. р. штраф", "пени", "неустойка", пропустить подстроки ", а также", "и". Запустить парсер 2 раза: сначала выделим взыскания, удалим лишние токены, запустим парсер ещё раз: End of explanation from yargy import not_ from yargy.predicates import eq def bounded(start, stop): return rule( eq(start), not_(eq(stop)).repeatable(), eq(stop) ) BOUNDED = or_( bounded('[', ']'), bounded('«', '»') ) parser = Parser(BOUNDED) matches = parser.findall('[a b] {c d} «e f»') for match in matches: print([_.value for _ in match.tokens]) Explanation: Генерация правил В Yargy все правила описываются на языке Python. Создадим функцию, которая генерирует правило. Например, правило для текста в скобочка и кавычках: End of explanation from yargy.predicates import in_ def joined(ITEM, SEP): return rule( ITEM, rule( SEP, ITEM ).repeatable().optional() ) SEP = in_(',;') JOINED = joined(BOUNDED, SEP) parser = Parser(JOINED) match = parser.match('[a b], [c d], [e f g]') Explanation: Правило — аналог join в Python: End of explanation def bio(type): return rule( tag('B-%s' % type), tag('I-%s' % type).repeatable().optional() ) PER = bio('PER') LOC = bio('LOC') text = '15 апреля в Симферополе Леонид Рожков ...' tags = 'B-DATE I-DATE O B-LOC B-PER I-PER O'.split() class Tagger(Tagger): tags = {'B-PER', 'I-PER', 'B-LOC', 'I-LOC', 'O'} def __call__(self, tokens): for token, tag in zip(tokens, tags): yield token.tagged(tag) RULE = or_(PER, LOC) parser = Parser(RULE, tagger=Tagger()) matches = parser.findall(text) for match in matches: print([_.value for _ in match.tokens]) Explanation: Правило для BIO-разметки: End of explanation from yargy.pipelines import ( morph_pipeline, pipeline ) from yargy import interpretation as interp TYPES = [ ('Общество с ограниченной ответственностью', 'ООО'), ('Акционерное общество', 'АО'), ('Страховая компания', 'СК'), ('Строительная компания', 'СК') ] TYPE = or_( morph_pipeline([ name for name, abbr in TYPES ]), pipeline([ abbr for name, abbr in TYPES ]) ) RULE = TYPE.repeatable() parser = Parser(RULE) matches = parser.findall('Акционерное общество, в Акционерном обществе; АО, СК') for match in matches: print([_.value for _ in match.tokens]) Explanation: Генерация pipeline Создадим pipeline из словаря пар "полное название", "сокращение": End of explanation from collections import namedtuple from yargy.predicates import type Ref_ = namedtuple( 'Ref', ['art', 'punkt'] ) Art = fact( 'Art', ['start', 'stop'] ) class Art(Art): def range(self): if self.stop: return range(self.start, self.stop + 1) else: return [self.start] Punkt = fact( 'Punkt', ['number'] ) Ref = fact( 'Ref', ['art', 'punkt'] ) class Ref(Ref): def range(self): for art in self.art.range(): punkt = ( self.punkt.number if self.punkt else None ) yield Ref_(art, punkt) INT = type('INT') ART = rule( 'ст', '.', INT.interpretation(Art.start.custom(int)), rule( '-', INT.interpretation(Art.stop.custom(int)) ).optional() ).interpretation(Art) PUNKT = rule( 'п', '.', INT.interpretation(Punkt.number.custom(int)) ).interpretation(Punkt) REF = rule( ART.interpretation(Ref.art), PUNKT.optional().interpretation(Ref.punkt) ).interpretation(Ref) parser = Parser(REF) lines = [ 'ст. 15-17 п.1', 'ст. 15 п.2', 'ст. 16' ] for line in lines: print(line) match = parser.match(line) print(list(match.fact.range())) Explanation: Наследование fact fact создаёт Python-класс, отнаследуемся, добавим методы и атрибуты. Например, есть ссылка на статьи "ст. 15-17 п.1", результат список объектов Ref(art=15, punkt=1), Ref(art=16, punkt=1), ...: End of explanation Period_ = namedtuple('Period', ['start', 'stop']) Year = fact( 'Year', ['value'] ) class Year(Year): @property def normalized(self): return Period_(self.value, self.value + 1) YearRange = fact( 'YearRange', ['start', 'stop'] ) class YearRange(YearRange): @property def normalized(self): return Period_(self.start, self.stop + 1) Century = fact( 'Century', ['value'] ) class Century(Century): @property def normalized(self): start = (self.value - 1) * 100 return Period_(start, start + 100) Period = fact( 'Period', ['value'] ) class Period(Period): @property def normalized(self): return self.value.normalized YEAR = rule( INT.interpretation(Year.value.custom(int)), 'г', '.' ).interpretation(Year) YEAR_RANGE = rule( INT.interpretation(YearRange.start.custom(int)), '-', INT.interpretation(YearRange.stop.custom(int)), 'г', '.' ).interpretation(YearRange) CENTURY = rule( INT.interpretation(Century.value.custom(int)), 'век' ).interpretation(Century) PERIOD = or_( YEAR, YEAR_RANGE, CENTURY ).interpretation(Period.value).interpretation(Period) parser = Parser(PERIOD) lines = [ '1917-1918г.', '21 век', '1990г.' ] for line in lines: match = parser.match(line) print(line) print(match.fact.normalized) Explanation: Есть периоды "1917-1918г.", "21 век", приведём их к единому формату: Period(1917, 1919), Period(2000, 2100). End of explanation
7,376
Given the following text description, write Python code to implement the functionality described below step by step Description: BigQuery Dataset Create and permission a dataset in BigQuery. License Copyright 2020 Google LLC, 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 https Step1: 2. Set Configuration This code is required to initialize the project. Fill in required fields and press play. If the recipe uses a Google Cloud Project Step2: 3. Enter BigQuery Dataset Recipe Parameters Specify the name of the dataset. If dataset exists, it is inchanged. Add emails and / or groups to add read permission. CAUTION Step3: 4. Execute BigQuery Dataset This does NOT need to be modified unless you are changing the recipe, click play.
Python Code: !pip install git+https://github.com/google/starthinker Explanation: BigQuery Dataset Create and permission a dataset in BigQuery. License Copyright 2020 Google LLC, 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 https://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. Disclaimer This is not an officially supported Google product. It is a reference implementation. There is absolutely NO WARRANTY provided for using this code. The code is Apache Licensed and CAN BE fully modified, white labeled, and disassembled by your team. This code generated (see starthinker/scripts for possible source): - Command: "python starthinker_ui/manage.py colab" - Command: "python starthinker/tools/colab.py [JSON RECIPE]" 1. Install Dependencies First install the libraries needed to execute recipes, this only needs to be done once, then click play. End of explanation from starthinker.util.configuration import Configuration CONFIG = Configuration( project="", client={}, service={}, user="/content/user.json", verbose=True ) Explanation: 2. Set Configuration This code is required to initialize the project. Fill in required fields and press play. If the recipe uses a Google Cloud Project: Set the configuration project value to the project identifier from these instructions. If the recipe has auth set to user: If you have user credentials: Set the configuration user value to your user credentials JSON. If you DO NOT have user credentials: Set the configuration client value to downloaded client credentials. If the recipe has auth set to service: Set the configuration service value to downloaded service credentials. End of explanation FIELDS = { 'auth_write':'service', # Credentials used for writing data. 'dataset_dataset':'', # Name of Google BigQuery dataset to create. 'dataset_emails':[], # Comma separated emails. 'dataset_groups':[], # Comma separated groups. } print("Parameters Set To: %s" % FIELDS) Explanation: 3. Enter BigQuery Dataset Recipe Parameters Specify the name of the dataset. If dataset exists, it is inchanged. Add emails and / or groups to add read permission. CAUTION: Removing permissions in StarThinker has no effect. CAUTION: To remove permissions you have to edit the dataset. Modify the values below for your use case, can be done multiple times, then click play. End of explanation from starthinker.util.configuration import execute from starthinker.util.recipe import json_set_fields TASKS = [ { 'dataset':{ 'auth':{'field':{'name':'auth_write','kind':'authentication','order':1,'default':'service','description':'Credentials used for writing data.'}}, 'dataset':{'field':{'name':'dataset_dataset','kind':'string','order':1,'default':'','description':'Name of Google BigQuery dataset to create.'}}, 'emails':{'field':{'name':'dataset_emails','kind':'string_list','order':2,'default':[],'description':'Comma separated emails.'}}, 'groups':{'field':{'name':'dataset_groups','kind':'string_list','order':3,'default':[],'description':'Comma separated groups.'}} } } ] json_set_fields(TASKS, FIELDS) execute(CONFIG, TASKS, force=True) Explanation: 4. Execute BigQuery Dataset This does NOT need to be modified unless you are changing the recipe, click play. End of explanation
7,377
Given the following text description, write Python code to implement the functionality described below step by step Description: Pôle Emploi Agencies Date Step1: OK, this sounds pretty cool. However there are a lot of fields (63) so let's check them vertically Step2: OK, it's a bit easier to read, but not enough to our taste. Let's try to cut out the fields for opening hours Step3: Alright, and let's try to have it in a nicer format. First let's see what are the patterns of the field names. It seems that most of them end with SLOT_1 or SLOT_2 Step4: OK, this is confirmed, and do we have the same fields for both slots? Step5: OK, that's clearer Step6: Cool, now let's check that we can recreate the same fields by using the 4 variables Step7: Indeed we can! So now here comes the magic Step8: OK, this is now more readable Step9: OK, all those fields seem pretty straight forward. Now let's check the actual content. Content Step10: So there are 881 agencies in this dataset. The agency names and "Aurore" codes are unique. They all have addresses, but few of them (12) are missing an email address, and some of them (11) do not have a latitude longitude. Hmm however it seems that there are a few fields that are considered as integer but should actually be strings Step11: Cool, that's better. We can see that SAFIR Agency codes are unique as well. As we saw in the description above there are 2 types of agencies Step12: OK, so some of them are "specialized". What does that mean? Let's check out some of them Step13: According to their names they are specialized in executives ("cadres") and/or in certain sectors ("scenes et images"). There are also 2 establishment types Step14: Hmm, apparently some agencies seem not to have any appointment possible. Let's make sure this corresponds to the number of hours opened for appointments Step15: Perfect, the different establishment type is due to not having any appointments. By the way, let's check that the weekly number hours correspond to the actual schedule proposed. First let's re-compute the total number of weekly opening hours, both for appointments and for self-service Step16: OK, now that we have the same format, let's check the difference with the columns already in the dataset Step17: There's a difference but it looks more like a rounding error (.03 hours correspond to less than 2 minutes), so we can just trust the WEEKLY_NUMBER_HOURS fields. Another field with a low cardinality is the phone number Step18: So there's a global phone number to call Pôle emploi, but for some reason 3 agencies have published a local phone number. What about the email field? Looking at the first examples, it seemed that they were all of the format &lt;name&gt;.&lt;id&gt;@pole-emploi.fr and that the ID matched the SAFIR_AGENCY_CODE. Let's check it Step19: Hmm the third one looks like it has a typo. What about the prefixes Step20: Right on! Most of the email addresses contains the SAFIR agency code in it. What about the other email addresses? Step21: OK, so apparently it's not always the case so it's a good thing that the dataset contains the address to contact. Let's check the distribution by region Step22: 13 regions in Metropolitan France, and 4 for overseas (Guyane, Martinique, Guadeloupe and Réunion-Mayotte). It looks like they're all here with a decent number of agencies Step23: Hmm, I see no good reasons why they do not have their geographic coordinates. Google Maps seem to be able to find them, see the one in Rouen, and the one in Cergy. We should probably tell Pôle emploi about those. In the meantime let's plot the others Step24: Cool Step25: OK, it is indeed in Saint-Pierre et Miquelon, it's just that it's joined with the Normandie region. Let's zoom in Metropolitan France Step26: That sounds like a good view of major cities in France! Finally, let's check that we have precise addresses and not only the center of cities. For instance let's check the agencies in Paris Step27: Cool! Obviously they don't have all the same coordinates so most probably they would relate to actual addresses and not just cities. Finally let's do a point check for an agency we went to physically (Arles)
Python Code: import os from os import path import pandas as pd import seaborn as _ DATA_FOLDER = os.getenv('DATA_FOLDER') agencies = pd.read_csv(path.join(DATA_FOLDER, 'pole-emploi-agencies.csv')) agencies.head() Explanation: Pôle Emploi Agencies Date: 2017-11-19 Author: Pascal pascal@bayesimpact.org In Pôle emploi Open Data (from Emploi Store Dev), since at least July 2017, one can find the list of Pôle emploi agencies. This notebook is an overview of this dataset. You can download the csv file from the dataset by using the following command: bash docker-compose run --rm data-analysis-prepare make data/pole-emploi-agencies.csv Import and Format First let's import the CSV and check the format of the various columns: End of explanation agencies.head(2).transpose() Explanation: OK, this sounds pretty cool. However there are a lot of fields (63) so let's check them vertically: End of explanation agencies_opening_hours = agencies[[column for column in agencies.columns if '_HOUR_' in column]] agencies_opening_hours.head() Explanation: OK, it's a bit easier to read, but not enough to our taste. Let's try to cut out the fields for opening hours: End of explanation all_slots = {column[-len('_SLOT_1'):] for column in agencies_opening_hours.columns} all_slots Explanation: Alright, and let's try to have it in a nicer format. First let's see what are the patterns of the field names. It seems that most of them end with SLOT_1 or SLOT_2: End of explanation def _columns_for_slot(columns, slot_id): return {column[:-len(slot_id)] for column in columns if column.endswith(slot_id)} if _columns_for_slot(agencies_opening_hours.columns, '_SLOT_1') != \ _columns_for_slot(agencies_opening_hours.columns, '_SLOT_2'): raise ValueError("Slots don't have the same fields") _columns_for_slot(agencies_opening_hours.columns, '_SLOT_1') Explanation: OK, this is confirmed, and do we have the same fields for both slots? End of explanation all_days = {column[-len('FRI'):] for column in _columns_for_slot(agencies_opening_hours.columns, '_SLOT_1')} all_days Explanation: OK, that's clearer: for each day, there are two possible slots of openings (probably morning and afternoon), and for each slot there are opening and close hours, and appointment opening and closing hours. We're going to pivot this to have one row per slot instead of one row per agency. First let's extract the list of days: End of explanation slot_fields = { '{slot_type}{limit}_HOUR_{day}{slot}'.format( slot_type=slot_type, limit=limit, day=day, slot=slot, ) for day in all_days for slot in all_slots for slot_type in {'' , 'APPT_'} for limit in {'OPENING', 'CLOSING'} } slot_fields == set(agencies_opening_hours.columns) Explanation: Cool, now let's check that we can recreate the same fields by using the 4 variables: day, slot (1 or 2), slot type (appointment or not) and limit (opening or closing): End of explanation agencies_opening_hours_flatten = pd.melt(agencies_opening_hours.reset_index(), id_vars=['index']) agencies_opening_hours_flatten['appointment'] = agencies_opening_hours_flatten.variable.str.startswith('APPT_') agencies_opening_hours_flatten['slot'] = agencies_opening_hours_flatten.variable.str[-1:] agencies_opening_hours_flatten['day'] = agencies_opening_hours_flatten.variable.str[-len('FRI_SLOT_1'):-len('_SLOT_1')] agencies_opening_hours_flatten['limit'] = agencies_opening_hours_flatten.variable.apply(lambda var: 'opening' if 'OPENING' in var else 'closing') agencies_opening_slots = agencies_opening_hours_flatten\ .set_index(['index', 'appointment', 'day', 'slot', 'limit'])\ .value.unstack()[['opening', 'closing']]\ .dropna()\ .reset_index(level=[1, 2, 3]) # Sorting the days of the week for better readability: agencies_opening_slots['day_value'] = agencies_opening_slots.day.map({ 'MON': 0, 'TUE': 1, 'WED': 2, 'THU': 3, 'FRI': 4, }) agencies_opening_slots = agencies_opening_slots\ .reset_index()\ .sort_values(['index', 'day_value', 'appointment', 'slot'])\ .set_index('index')\ .drop('day_value', 'columns') agencies_opening_slots.head(10) Explanation: Indeed we can! So now here comes the magic: * first we flatten the dataframe with one row per time, * then we extract the 4 variables from the original field name, * we drop the slots that have no opening nor closing time, * finally we join opening and closing for the same slots. End of explanation agencies_info = agencies[[column for column in agencies.columns if '_HOUR_' not in column]] agencies_info.head(2).transpose() Explanation: OK, this is now more readable: the agency with index 0 is open every morning without appointments, and in the afternoon for appointments (except Thursday, and on Friday only up to 15:30). Alright, now what about the other fields (non hours): End of explanation agencies_info.describe(include='all').head(2).transpose() Explanation: OK, all those fields seem pretty straight forward. Now let's check the actual content. Content End of explanation agencies = pd.read_csv(path.join(DATA_FOLDER, 'pole-emploi-agencies.csv'), dtype={ 'POSTCODE': str, 'SAFIR_AGENCY_CODE': str, 'ESTABLISHMENT_TYPE': str, }) agencies_info = agencies[[column for column in agencies.columns if '_HOUR_' not in column]] agencies_info[['POSTCODE', 'SAFIR_AGENCY_CODE', 'ESTABLISHMENT_TYPE']].describe(include='all').head(2).transpose() Explanation: So there are 881 agencies in this dataset. The agency names and "Aurore" codes are unique. They all have addresses, but few of them (12) are missing an email address, and some of them (11) do not have a latitude longitude. Hmm however it seems that there are a few fields that are considered as integer but should actually be strings: POSTCODE, SAFIR_AGENCY_CODE and ESTABLISHMENT_TYPE. Let's reimport properly: End of explanation agencies_info[['AGENCY_TYPE_CODE', 'AGENCY_TYPE_NAME']].drop_duplicates() Explanation: Cool, that's better. We can see that SAFIR Agency codes are unique as well. As we saw in the description above there are 2 types of agencies: End of explanation agencies_info[agencies_info.AGENCY_TYPE_CODE == 'APES'].head() Explanation: OK, so some of them are "specialized". What does that mean? Let's check out some of them: End of explanation agencies_info[['ESTABLISHMENT_TYPE', 'ESTABLISHMENT_TYPE_NAME']].drop_duplicates() Explanation: According to their names they are specialized in executives ("cadres") and/or in certain sectors ("scenes et images"). There are also 2 establishment types: End of explanation agencies_info[['ESTABLISHMENT_TYPE', 'ESTABLISHMENT_TYPE_NAME', 'APPT_WEEKLY_NUMBER_HOURS']]\ .drop_duplicates()\ .sort_values('APPT_WEEKLY_NUMBER_HOURS') Explanation: Hmm, apparently some agencies seem not to have any appointment possible. Let's make sure this corresponds to the number of hours opened for appointments: End of explanation def _time_to_hours(time): hours, minutes = time.split(':') return int(hours) + round(int(minutes) / 60 * 100) / 100 agencies_opening_slots['duration'] =\ agencies_opening_slots.closing.map(_time_to_hours) - \ agencies_opening_slots.opening.map(_time_to_hours) weekly_number_hours = agencies_opening_slots\ .reset_index()\ .groupby(by=['index', 'appointment'])\ .sum()\ .reset_index(level=1)\ .pivot(columns='appointment', values='duration') weekly_number_hours.head() Explanation: Perfect, the different establishment type is due to not having any appointments. By the way, let's check that the weekly number hours correspond to the actual schedule proposed. First let's re-compute the total number of weekly opening hours, both for appointments and for self-service: End of explanation { 'weekly': ((weekly_number_hours.iloc[:, 0] - agencies_info.WEEKLY_NUMBER_HOURS)).abs().max(), 'appointment': ((weekly_number_hours.iloc[:, 1] - agencies_info.APPT_WEEKLY_NUMBER_HOURS)).abs().max(), } Explanation: OK, now that we have the same format, let's check the difference with the columns already in the dataset: End of explanation agencies_info.PUBLIC_PHONE_NUMBER.value_counts().to_frame() Explanation: There's a difference but it looks more like a rounding error (.03 hours correspond to less than 2 minutes), so we can just trust the WEEKLY_NUMBER_HOURS fields. Another field with a low cardinality is the phone number: End of explanation email_domains = agencies_info.EMAIL.dropna().str.split('@', 1).apply(lambda parts: parts[1]) email_domains.value_counts().to_frame() Explanation: So there's a global phone number to call Pôle emploi, but for some reason 3 agencies have published a local phone number. What about the email field? Looking at the first examples, it seemed that they were all of the format &lt;name&gt;.&lt;id&gt;@pole-emploi.fr and that the ID matched the SAFIR_AGENCY_CODE. Let's check it: End of explanation email_after_dot = agencies_info.EMAIL.dropna()\ .str.split('@', 1).apply(lambda parts: parts[0])\ .str.split('.', 1).apply(lambda parts: parts[1] if len(parts)> 1 else '') safir_agency_code = agencies_info.SAFIR_AGENCY_CODE.astype(str) (email_after_dot == safir_agency_code.loc[email_after_dot.index]).sum() Explanation: Hmm the third one looks like it has a typo. What about the prefixes: End of explanation emails_not_matching = \ email_after_dot[email_after_dot != safir_agency_code.loc[email_after_dot.index]] agencies_info.loc[emails_not_matching.index, ['AGENCY_NAME', 'EMAIL']].head() Explanation: Right on! Most of the email addresses contains the SAFIR agency code in it. What about the other email addresses? End of explanation agencies_info.REG_DIRECTION_NAME.value_counts().to_frame().plot(kind='barh') agencies_info.REG_DIRECTION_NAME.nunique() Explanation: OK, so apparently it's not always the case so it's a good thing that the dataset contains the address to contact. Let's check the distribution by region: End of explanation agencies_info[agencies_info.LONGITUDE.isnull()].head() Explanation: 13 regions in Metropolitan France, and 4 for overseas (Guyane, Martinique, Guadeloupe and Réunion-Mayotte). It looks like they're all here with a decent number of agencies: densily populated regions have a lot of agencies, others have less. Geo Locations Now let's check the geographic locations. First why are some of them missing? End of explanation agencies_info.plot(kind='scatter', x='LONGITUDE', y='LATITUDE'); Explanation: Hmm, I see no good reasons why they do not have their geographic coordinates. Google Maps seem to be able to find them, see the one in Rouen, and the one in Cergy. We should probably tell Pôle emploi about those. In the meantime let's plot the others: End of explanation agencies_info[ (agencies_info.LATITUDE > 40) & (agencies_info.LONGITUDE < -40) ][['AGENCY_NAME', 'REG_DIRECTION_NAME']] Explanation: Cool: pretty neat and obvious. We have the location of Pôle emploi agencies including the ones in DOM/TOM. Awesome! Wait a minute, there seems to be an agency next to Saint-Pierre et Miquelon whereas we did not see any corresponding region before. Let's check: End of explanation agencies_info[(agencies_info.LONGITUDE < 10) & (agencies_info.LONGITUDE > -5)]\ .plot(kind='scatter', x='LONGITUDE', y='LATITUDE', xlim=(-5, 10), ylim=(41, 52), # Fix figsize to have a good aspect ratio: 1.414 ~= 1/cos(45°). figsize=(8, 8 * 1.414 * (52 - 41) / (10 - -5))); Explanation: OK, it is indeed in Saint-Pierre et Miquelon, it's just that it's joined with the Normandie region. Let's zoom in Metropolitan France: End of explanation agencies_info[(agencies_info.POSTCODE.astype(str).str.startswith('75'))]\ [['AGENCY_NAME', 'LONGITUDE', 'LATITUDE']].head() Explanation: That sounds like a good view of major cities in France! Finally, let's check that we have precise addresses and not only the center of cities. For instance let's check the agencies in Paris: End of explanation agencies_info[agencies_info.AGENCY_NAME == 'ARLES'][['LATITUDE', 'LONGITUDE']] Explanation: Cool! Obviously they don't have all the same coordinates so most probably they would relate to actual addresses and not just cities. Finally let's do a point check for an agency we went to physically (Arles): End of explanation
7,378
Given the following text description, write Python code to implement the functionality described below step by step Description: Composite Glyph One or more actual glyphs that have been grouped together to represent some set of data, which respond to some standardized set of graphics operations. In a chart, a composite glyph is generated for each group of data. For example, a box glyph will produce one box for a box plot. This is composed of multiple glyphs, but represents a single group of data. This guide walks through the creation and use of composite glyphs. BarGlyph A simple bar has two components. It has some location along an axis, then it has some height from that axis. A bar can be created from a single value, or it can be created through aggregation. For example Step1: Bar from multiple values Notice the difference in height. Step2: Simplified input using same order Step3: Operations on Composite Glyphs Grammar of Graphics describes some common graphical operations that each glyph type would respond differently to. A common operation for bars would be stacking Un-Stacked Step4: Stacked Step5: Producing Combined Data Source Step6: Standalone Use of Composite Glyphs Setup Step7: Build Bars and Add Them Manually to Chart In the chart below, the bars corresponding to foo overlap. Step8: Stack the Bars, then Show Chart One potential way to handle overlapping bars is to stack them. See below that stacking the bars results in a stacked bar chart.
Python Code: bar = BarGlyph(label='a', values=[1]) bar.data Explanation: Composite Glyph One or more actual glyphs that have been grouped together to represent some set of data, which respond to some standardized set of graphics operations. In a chart, a composite glyph is generated for each group of data. For example, a box glyph will produce one box for a box plot. This is composed of multiple glyphs, but represents a single group of data. This guide walks through the creation and use of composite glyphs. BarGlyph A simple bar has two components. It has some location along an axis, then it has some height from that axis. A bar can be created from a single value, or it can be created through aggregation. For example: Bar from single value End of explanation bar = BarGlyph(label='a', values=[1, 2, 3, 4]) bar.data Explanation: Bar from multiple values Notice the difference in height. End of explanation bar = BarGlyph('a', 1) bar.data Explanation: Simplified input using same order End of explanation bar1 = BarGlyph('foo', 1) bar2 = BarGlyph('foo', 2) print('No stacking') print('bar1 y: %s, bar2 y: %s' % (bar1.data['y'], bar2.data['y']) ) Explanation: Operations on Composite Glyphs Grammar of Graphics describes some common graphical operations that each glyph type would respond differently to. A common operation for bars would be stacking Un-Stacked End of explanation from bokeh.charts.operations import stack bar1, bar2 = stack(bar1, bar2) print('With Stacking') print('bar1 y: %s, bar2 y: %s' % (bar1.data['y'], bar2.data['y']) ) Explanation: Stacked End of explanation from bokeh.charts.utils import comp_glyphs_to_df # utility that uses pandas.concat to concatenate each CompositeGlyph.df comp_glyphs_to_df(bar1, bar2) Explanation: Producing Combined Data Source End of explanation from bokeh.charts.chart import Chart from bokeh.models.ranges import DataRange1d, FactorRange from bokeh.io import curdoc, curstate def add_chart_to_doc(chart): "Handle adding chart to doc." curdoc()._current_plot = chart if curstate().autoadd: curdoc().add_root(chart) Explanation: Standalone Use of Composite Glyphs Setup End of explanation # two bars overlap on the same label/index bar1 = BarGlyph(label='foo', values=[1]) bar2 = BarGlyph('foo', 2) # only the third bar doesn't overlap bar3 = BarGlyph('bar', 3) # composite glyphs can have multiple renderers, so we get them all renderers = [] for bar in [bar1, bar2, bar3]: renderers += bar.renderers # create a chart and directly add the renderers c = Chart(renderers=renderers) # add ranges/scales (typically handled by builder) c.add_ranges('x', FactorRange(factors=['foo', 'bar'])) c.add_ranges('y', DataRange1d(start=0, end=4)) c.add_scales('x', 'auto') c.add_scales('y', 'auto') # build the chart (typically called by create_and_build) c.start_plot() # add chart to doc (typically handled by create_and_build) add_chart_to_doc(c) show(c) Explanation: Build Bars and Add Them Manually to Chart In the chart below, the bars corresponding to foo overlap. End of explanation stack(bar1, bar2, bar3) show(c) Explanation: Stack the Bars, then Show Chart One potential way to handle overlapping bars is to stack them. See below that stacking the bars results in a stacked bar chart. End of explanation
7,379
Given the following text description, write Python code to implement the functionality described below step by step Description: Step1: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Network you'll build will generate a new TV script for a scene at Moe's Tavern. Get the Data The data is already provided for you. You'll be using a subset of the original dataset. It consists of only the scenes in Moe's Tavern. This doesn't include other versions of the tavern, like "Moe's Cavern", "Flaming Moe's", "Uncle Moe's Family Feed-Bag", etc.. Step3: Explore the Data Play around with view_sentence_range to view different parts of the data. Step6: Implement Preprocessing Functions The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below Step9: Tokenize Punctuation We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!". Implement the function token_lookup to return a dict that will be used to tokenize symbols like "!" into "||Exclamation_Mark||". Create a dictionary for the following symbols where the symbol is the key and value is the token Step11: Preprocess all the data and save it Running the code cell below will preprocess all the data and save it to file. Step13: Check Point This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. Step15: Build the Neural Network You'll build the components necessary to build a RNN by implementing the following functions below Step18: Input Implement the get_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders Step21: Build RNN Cell and Initialize Stack one or more BasicLSTMCells in a MultiRNNCell. - The Rnn size should be set using rnn_size - Initalize Cell State using the MultiRNNCell's zero_state() function - Apply the name "initial_state" to the initial state using tf.identity() Return the cell and initial state in the following tuple (Cell, InitialState) Step24: Word Embedding Apply embedding to input_data using TensorFlow. Return the embedded sequence. Step27: Build RNN You created a RNN Cell in the get_init_cell() function. Time to use the cell to create a RNN. - Build the RNN using the tf.nn.dynamic_rnn() - Apply the name "final_state" to the final state using tf.identity() Return the outputs and final_state state in the following tuple (Outputs, FinalState) Step30: Build the Neural Network Apply the functions you implemented above to Step33: Batches Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements Step35: Neural Network Training Hyperparameters Tune the following parameters Step37: Build the Graph Build the graph using the neural network you implemented. Step40: Train Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem. Step42: Checkpoint Step45: Implement Generate Functions Get Tensors Get tensors from loaded_graph using the function get_tensor_by_name(). Get the tensors using the following names Step48: Choose Word Implement the pick_word() function to select the next word using probabilities. Step50: Generate TV Script This will generate the TV script for you. Set gen_length to the length of TV script you want to generate.
Python Code: DON'T MODIFY ANYTHING IN THIS CELL import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:] Explanation: TV Script Generation In this project, you'll generate your own Simpsons TV scripts using RNNs. You'll be using part of the Simpsons dataset of scripts from 27 seasons. The Neural Network you'll build will generate a new TV script for a scene at Moe's Tavern. Get the Data The data is already provided for you. You'll be using a subset of the original dataset. It consists of only the scenes in Moe's Tavern. This doesn't include other versions of the tavern, like "Moe's Cavern", "Flaming Moe's", "Uncle Moe's Family Feed-Bag", etc.. End of explanation view_sentence_range = (0, 10) DON'T MODIFY ANYTHING IN THIS CELL import numpy as np print('Dataset Stats') print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()}))) scenes = text.split('\n\n') print('Number of scenes: {}'.format(len(scenes))) sentence_count_scene = [scene.count('\n') for scene in scenes] print('Average number of sentences in each scene: {}'.format(np.average(sentence_count_scene))) sentences = [sentence for scene in scenes for sentence in scene.split('\n')] print('Number of lines: {}'.format(len(sentences))) word_count_sentence = [len(sentence.split()) for sentence in sentences] print('Average number of words in each line: {}'.format(np.average(word_count_sentence))) print() print('The sentences {} to {}:'.format(*view_sentence_range)) print('\n'.join(text.split('\n')[view_sentence_range[0]:view_sentence_range[1]])) Explanation: Explore the Data Play around with view_sentence_range to view different parts of the data. End of explanation import numpy as np import problem_unittests as tests def create_lookup_tables(text): Create lookup tables for vocabulary :param text: The text of tv scripts split into words :return: A tuple of dicts (vocab_to_int, int_to_vocab) # TODO: Implement Function vocab = list(set(text)) vocab_to_int = {} int_to_vocab = {} vocab_to_int = {word: i for i, word in enumerate(vocab, 0)} int_to_vocab = {i: word for word, i in vocab_to_int.items()} return vocab_to_int, int_to_vocab DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_create_lookup_tables(create_lookup_tables) Explanation: Implement Preprocessing Functions The first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below: - Lookup Table - Tokenize Punctuation Lookup Table To create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries: - Dictionary to go from the words to an id, we'll call vocab_to_int - Dictionary to go from the id to word, we'll call int_to_vocab Return these dictionaries in the following tuple (vocab_to_int, int_to_vocab) End of explanation def token_lookup(): Generate a dict to turn punctuation into a token. :return: Tokenize dictionary where the key is the punctuation and the value is the token # TODO: Implement Function punc_tokens = {'.':"||period||", \ ',': "||comma||",\ '"': "||quotationmark||",\ ';': "||semicolon||",\ '!': "||exclamationmark||",\ '?': "||questionmark||",\ '(': "||leftparentheses||",\ ')': "||rightparentheses||",\ '--': "||dash||",\ '\n': "||return||"\ } return punc_tokens DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_tokenize(token_lookup) Explanation: Tokenize Punctuation We'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!". Implement the function token_lookup to return a dict that will be used to tokenize symbols like "!" into "||Exclamation_Mark||". Create a dictionary for the following symbols where the symbol is the key and value is the token: - Period ( . ) - Comma ( , ) - Quotation Mark ( " ) - Semicolon ( ; ) - Exclamation mark ( ! ) - Question mark ( ? ) - Left Parentheses ( ( ) - Right Parentheses ( ) ) - Dash ( -- ) - Return ( \n ) This dictionary will be used to token the symbols and add the delimiter (space) around it. This separates the symbols as it's own word, making it easier for the neural network to predict on the next word. Make sure you don't use a token that could be confused as a word. Instead of using the token "dash", try using something like "||dash||". End of explanation DON'T MODIFY ANYTHING IN THIS CELL # Preprocess Training, Validation, and Testing Data helper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables) Explanation: Preprocess all the data and save it Running the code cell below will preprocess all the data and save it to file. End of explanation DON'T MODIFY ANYTHING IN THIS CELL import helper import numpy as np import problem_unittests as tests int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() Explanation: Check Point This is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk. End of explanation DON'T MODIFY ANYTHING IN THIS CELL from distutils.version import LooseVersion import warnings import tensorflow as tf # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer' print('TensorFlow Version: {}'.format(tf.__version__)) # Check for a GPU if not tf.test.gpu_device_name(): warnings.warn('No GPU found. Please use a GPU to train your neural network.') else: print('Default GPU Device: {}'.format(tf.test.gpu_device_name())) Explanation: Build the Neural Network You'll build the components necessary to build a RNN by implementing the following functions below: - get_inputs - get_init_cell - get_embed - build_rnn - build_nn - get_batches Check the Version of TensorFlow and Access to GPU End of explanation def get_inputs(): Create TF Placeholders for input, targets, and learning rate. :return: Tuple (input, targets, learning rate) # TODO: Implement Function input_ = tf.placeholder(tf.int32, shape=(None, None), name="input") targets_ = tf.placeholder(tf.int32, shape=(None, None), name="targets") learning_rate_ = tf.placeholder(tf.float32, shape=None, name="learning_rate") return input_, targets_, learning_rate_ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_get_inputs(get_inputs) Explanation: Input Implement the get_inputs() function to create TF Placeholders for the Neural Network. It should create the following placeholders: - Input text placeholder named "input" using the TF Placeholder name parameter. - Targets placeholder - Learning Rate placeholder Return the placeholders in the following tuple (Input, Targets, LearningRate) End of explanation def get_init_cell(batch_size, rnn_size): Create an RNN Cell and initialize it. :param batch_size: Size of batches :param rnn_size: Size of RNNs :return: Tuple (cell, initialize state) # TODO: Implement Function lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size) #drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=0.5) cell = tf.contrib.rnn.MultiRNNCell([lstm]) initial_state = tf.identity(cell.zero_state(batch_size, tf.int32), name="initial_state") return cell, initial_state DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_get_init_cell(get_init_cell) Explanation: Build RNN Cell and Initialize Stack one or more BasicLSTMCells in a MultiRNNCell. - The Rnn size should be set using rnn_size - Initalize Cell State using the MultiRNNCell's zero_state() function - Apply the name "initial_state" to the initial state using tf.identity() Return the cell and initial state in the following tuple (Cell, InitialState) End of explanation def get_embed(input_data, vocab_size, embed_dim): Create embedding for <input_data>. :param input_data: TF placeholder for text input. :param vocab_size: Number of words in vocabulary. :param embed_dim: Number of embedding dimensions :return: Embedded input. # TODO: Implement Function embedding = tf.Variable(tf.random_uniform((vocab_size, embed_dim), -1, 1)) embed = tf.nn.embedding_lookup(embedding, input_data) return embed DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_get_embed(get_embed) Explanation: Word Embedding Apply embedding to input_data using TensorFlow. Return the embedded sequence. End of explanation def build_rnn(cell, inputs): Create a RNN using a RNN Cell :param cell: RNN Cell :param inputs: Input text data :return: Tuple (Outputs, Final State) # TODO: Implement Function #initial_state = tf.placeholder(tf.float32, [None, None], name="initial_state") outputs, states = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32) final_state = tf.identity(states, name="final_state") return outputs, final_state DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_build_rnn(build_rnn) Explanation: Build RNN You created a RNN Cell in the get_init_cell() function. Time to use the cell to create a RNN. - Build the RNN using the tf.nn.dynamic_rnn() - Apply the name "final_state" to the final state using tf.identity() Return the outputs and final_state state in the following tuple (Outputs, FinalState) End of explanation def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim): Build part of the neural network :param cell: RNN cell :param rnn_size: Size of rnns :param input_data: Input data :param vocab_size: Vocabulary size :param embed_dim: Number of embedding dimensions :return: Tuple (Logits, FinalState) # TODO: Implement Function embed = get_embed(input_data, vocab_size, embed_dim) outputs, final_state = build_rnn(cell, embed) logits = tf.contrib.layers.fully_connected(outputs, vocab_size, activation_fn=None) return logits, final_state DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_build_nn(build_nn) Explanation: Build the Neural Network Apply the functions you implemented above to: - Apply embedding to input_data using your get_embed(input_data, vocab_size, embed_dim) function. - Build RNN using cell and your build_rnn(cell, inputs) function. - Apply a fully connected layer with a linear activation and vocab_size as the number of outputs. Return the logits and final state in the following tuple (Logits, FinalState) End of explanation def get_batches(int_text, batch_size, seq_length): Return batches of input and target :param int_text: Text with the words replaced by their ids :param batch_size: The size of batch :param seq_length: The length of sequence :return: Batches as a Numpy array # TODO: Implement Function int_text_size = len(int_text) batch_len = batch_size * seq_length no_of_batches = int(int_text_size/(batch_size * seq_length)) int_text_batch_size = batch_len * no_of_batches batches = list() input_batches = list() target_batches = list() iteration = 1 #print("Text length is {}. No. of Batches {}.".format(int_text_size, no_of_batches)) #print("Batch length is {}. Batch size is {} and length {}".format(batch_len, batch_size, seq_length)) for i in range(0, int_text_batch_size, batch_len): input_array = np.array(int_text[i:i+batch_len]).reshape(batch_size, seq_length) target_array = np.array(int_text[i+1:i+batch_len+1]).reshape(batch_size, seq_length) batches.append(np.stack((input_array, target_array), 0)) #print("Finished batch: {}".format(iteration)) iteration += 1 print("No. of batches is {}".format(iteration)) return np.array(batches) DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_get_batches(get_batches) Explanation: Batches Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements: - The first element is a single batch of input with the shape [batch size, sequence length] - The second element is a single batch of targets with the shape [batch size, sequence length] If you can't fill the last batch with enough data, drop the last batch. For exmple, get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 3, 2) would return a Numpy array of the following: ``` [ # First Batch [ # Batch of Input [[ 1 2], [ 7 8], [13 14]] # Batch of targets [[ 2 3], [ 8 9], [14 15]] ] # Second Batch [ # Batch of Input [[ 3 4], [ 9 10], [15 16]] # Batch of targets [[ 4 5], [10 11], [16 17]] ] # Third Batch [ # Batch of Input [[ 5 6], [11 12], [17 18]] # Batch of targets [[ 6 7], [12 13], [18 1]] ] ] ``` Notice that the last target value in the last batch is the first input value of the first batch. In this case, 1. This is a common technique used when creating sequence batches, although it is rather unintuitive. End of explanation # Number of Epochs num_epochs = 64 # Batch Size batch_size = 100 # RNN Size rnn_size = 256 # Embedding Dimension Size embed_dim = 256 # Sequence Length seq_length = 10 # Learning Rate learning_rate = 0.01 # Show stats for every n number of batches show_every_n_batches = 100 DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE save_dir = './save' Explanation: Neural Network Training Hyperparameters Tune the following parameters: Set num_epochs to the number of epochs. Set batch_size to the batch size. Set rnn_size to the size of the RNNs. Set embed_dim to the size of the embedding. Set seq_length to the length of sequence. Set learning_rate to the learning rate. Set show_every_n_batches to the number of batches the neural network should print progress. End of explanation DON'T MODIFY ANYTHING IN THIS CELL from tensorflow.contrib import seq2seq train_graph = tf.Graph() with train_graph.as_default(): vocab_size = len(int_to_vocab) input_text, targets, lr = get_inputs() input_data_shape = tf.shape(input_text) cell, initial_state = get_init_cell(input_data_shape[0], rnn_size) logits, final_state = build_nn(cell, rnn_size, input_text, vocab_size, embed_dim) # Probabilities for generating words probs = tf.nn.softmax(logits, name='probs') # Loss function cost = seq2seq.sequence_loss( logits, targets, tf.ones([input_data_shape[0], input_data_shape[1]])) # Optimizer optimizer = tf.train.AdamOptimizer(lr) # Gradient Clipping gradients = optimizer.compute_gradients(cost) capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None] train_op = optimizer.apply_gradients(capped_gradients) Explanation: Build the Graph Build the graph using the neural network you implemented. End of explanation DON'T MODIFY ANYTHING IN THIS CELL batches = get_batches(int_text, batch_size, seq_length) with tf.Session(graph=train_graph) as sess: sess.run(tf.global_variables_initializer()) for epoch_i in range(num_epochs): state = sess.run(initial_state, {input_text: batches[0][0]}) for batch_i, (x, y) in enumerate(batches): feed = { input_text: x, targets: y, initial_state: state, lr: learning_rate} train_loss, state, _ = sess.run([cost, final_state, train_op], feed) # Show every <show_every_n_batches> batches if (epoch_i * len(batches) + batch_i) % show_every_n_batches == 0: print('Epoch {:>3} Batch {:>4}/{} train_loss = {:.3f}'.format( epoch_i, batch_i, len(batches), train_loss)) # Save Model saver = tf.train.Saver() saver.save(sess, save_dir) print('Model Trained and Saved') DON'T MODIFY ANYTHING IN THIS CELL # Save parameters for checkpoint helper.save_params((seq_length, save_dir)) Explanation: Train Train the neural network on the preprocessed data. If you have a hard time getting a good loss, check the forms to see if anyone is having the same problem. End of explanation DON'T MODIFY ANYTHING IN THIS CELL import tensorflow as tf import numpy as np import helper import problem_unittests as tests _, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() seq_length, load_dir = helper.load_params() Explanation: Checkpoint End of explanation def get_tensors(loaded_graph): Get input, initial state, final state, and probabilities tensor from <loaded_graph> :param loaded_graph: TensorFlow graph loaded from file :return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor) # TODO: Implement Function input_tensor = loaded_graph.get_tensor_by_name("input:0") initial_state_tensor = loaded_graph.get_tensor_by_name("initial_state:0") final_state_tensor = loaded_graph.get_tensor_by_name("final_state:0") probs_tensor = loaded_graph.get_tensor_by_name("probs:0") return input_tensor, initial_state_tensor, final_state_tensor, probs_tensor DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_get_tensors(get_tensors) Explanation: Implement Generate Functions Get Tensors Get tensors from loaded_graph using the function get_tensor_by_name(). Get the tensors using the following names: - "input:0" - "initial_state:0" - "final_state:0" - "probs:0" Return the tensors in the following tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor) End of explanation def pick_word(probabilities, int_to_vocab): Pick the next word in the generated text :param probabilities: Probabilites of the next word :param int_to_vocab: Dictionary of word ids as the keys and words as the values :return: String of the predicted word # TODO: Implement Function p = np.squeeze(probabilities) p[np.argsort(p)[:-seq_length]] = 0 p = p / np.sum(p) #print("Sanitized probabilities {}".format(p)) x=np.random.choice(len(probabilities), seq_length, p=p) return int_to_vocab[x[0]] DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE tests.test_pick_word(pick_word) Explanation: Choose Word Implement the pick_word() function to select the next word using probabilities. End of explanation gen_length = 200 # homer_simpson, moe_szyslak, or Barney_Gumble prime_word = 'moe_szyslak' DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load saved model loader = tf.train.import_meta_graph(load_dir + '.meta') loader.restore(sess, load_dir) # Get Tensors from loaded model input_text, initial_state, final_state, probs = get_tensors(loaded_graph) # Sentences generation setup gen_sentences = [prime_word + ':'] prev_state = sess.run(initial_state, {input_text: np.array([[1]])}) #print("Sequence length is {}".format(seq_length)) #print("gen sentences length: {}".format(len(gen_sentences))) #print("gen sentences content from sequence steps behind is {}".format(gen_sentences[-seq_length:])) #print("gen sentences content is {}".format(gen_sentences)) #print(vocab_to_int['moe_szyslak:']) #print("List example is {} \n".format(nums_ex[-seq_length:])) # Generate sentences for n in range(gen_length): # Dynamic Input dyn_input = [[vocab_to_int[word] for word in gen_sentences[-seq_length:]]] dyn_seq_length = len(dyn_input[0]) #print("Dynamic Input: {}".format(dyn_input)) #print("Dynamic seq length = {}".format(dyn_seq_length)) # Get Prediction probabilities, prev_state = sess.run( [probs, final_state], {input_text: dyn_input, initial_state: prev_state}) #print("Probabilities length before picking {}".format(len(probabilities))) pred_word = pick_word(probabilities[dyn_seq_length-1], int_to_vocab) gen_sentences.append(pred_word) # Remove tokens tv_script = ' '.join(gen_sentences) for key, token in token_dict.items(): ending = ' ' if key in ['\n', '(', '"'] else '' tv_script = tv_script.replace(' ' + token.lower(), key) tv_script = tv_script.replace('\n ', '\n') tv_script = tv_script.replace('( ', '(') print(tv_script) Explanation: Generate TV Script This will generate the TV script for you. Set gen_length to the length of TV script you want to generate. End of explanation
7,380
Given the following text description, write Python code to implement the functionality described below step by step Description: Title Step1: Create dataframe Step2: Create a pivot table of group means, by company and regiment Step3: Create a pivot table of group score counts, by company and regimensts
Python Code: import pandas as pd Explanation: Title: Pivot Tables In Pandas Slug: pandas_pivot_tables Summary: Pivot Tables In Pandas Date: 2016-05-01 12:00 Category: Python Tags: Data Wrangling Authors: Chris Albon import modules End of explanation raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'], 'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'], 'TestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3]} df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'TestScore']) df Explanation: Create dataframe End of explanation pd.pivot_table(df, index=['regiment','company'], aggfunc='mean') Explanation: Create a pivot table of group means, by company and regiment End of explanation df.pivot_table(index=['regiment','company'], aggfunc='count') Explanation: Create a pivot table of group score counts, by company and regimensts End of explanation
7,381
Given the following text description, write Python code to implement the functionality described below step by step Description: Skewness and symmetry By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie Part of the Quantopian Lecture Series Step1: A distribution which is not symmetric is called <i>skewed</i>. For instance, a distribution can have many small positive and a few large negative values (negatively skewed) or vice versa (positively skewed), and still have a mean of 0. A symmetric distribution has skewness 0. Positively skewed unimodal (one mode) distributions have the property that mean > median > mode. Negatively skewed unimodal distributions are the reverse, with mean < median < mode. All three are equal for a symmetric unimodal distribution. The explicit formula for skewness is $$ S_K = \frac{n}{(n-1)(n-2)} \frac{\sum_{i=1}^n (X_i - \mu)^3}{\sigma^3} $$ where $n$ is the number of observations, $\mu$ is the arithmetic mean, and $\sigma$ is the standard deviation. The sign of this quantity describes the direction of the skew as described above. We can plot a positively skewed and a negatively skewed distribution to see what they look like. Step2: Although skew is less obvious when graphing discrete data sets, we can still compute it. For example, below are the skew, mean, and median for S&P 500 returns 2012-2014. Note that the skew is negative, and so the mean is less than the median. Step3: Kurtosis Kurtosis attempts to measure the shape of the deviation from the mean. It's measured relative to a normal distribution, which is called mesokurtic. All normal distributions, regardless of mean and variance, have a kurtosis of 3. A leptokurtic distribution (kurtosis > 3) is highly peaked and has fat tails, while a platykurtic distribution (kurtosis < 3) is broad. Sometimes, however, kurtosis in excess of the normal distribution (kurtosis - 3) is used, and this is the default in scipy. Step4: The formula for kurtosis is $$ K = \left ( \frac{n(n+1)}{(n-1)(n-2)(n-3)} \frac{\sum_{i=1}^n (X_i - \mu)^4}{\sigma^4} \right ) $$ while excess kurtosis is given by $$ K_E = \left ( \frac{n(n+1)}{(n-1)(n-2)(n-3)} \frac{\sum_{i=1}^n (X_i - \mu)^4}{\sigma^4} \right ) - \frac{3(n-1)^2}{(n-2)(n-3)} $$ For a large number of samples, the excess kurtosis becomes approximately $$ K_E \approx \frac{1}{n} \frac{\sum_{i=1}^n (X_i - \mu)^4}{\sigma^4} - 3 $$ Since above we were considering perfect, continuous distributions, this was the form that kurtosis took. However, for a set of samples drawn for the normal distribution, we would use the first definition, and (excess) kurtosis would only be approximately 0. We can use scipy to find the excess kurtosis of the S&P 500 returns from before. Step5: The histogram of the returns shows significant observations beyond 3 standard deviations away from the mean, so we shouldn't be surprised that the kurtosis is indicating a leptokurtic distribution. Other standardized moments It's no coincidence that the variance, skewness, and kurtosis take similar forms. They are the first and most important standardized moments, of which the $k$th has the form $$ \frac{E[(X - E[X])^k]}{\sigma^k} $$ The first standardized moment is always 0 $(E[X - E[X]] = E[X] - E[E[X]] = 0)$, so we only care about the second through fourth. All of the standardized moments are dimensionless numbers which describe the distribution, and in particular can be used to quantify how close to normal (having standardized moments $0, \sigma, 0, \sigma^2$) a distribution is. One method is the Jarque-Bera test, which we can run on the S&P 500 returns to find the p-value for them coming from a normal distribution.
Python Code: import matplotlib.pyplot as plt import numpy as np import scipy.stats as stats # Plot a normal distribution with mean = 0 and standard deviation = 2 xs = np.linspace(-6,6, 300) normal = stats.norm.pdf(xs) plt.plot(xs, normal); Explanation: Skewness and symmetry By Evgenia "Jenny" Nitishinskaya and Delaney Granizo-Mackenzie Part of the Quantopian Lecture Series: www.quantopian.com/lectures github.com/quantopian/research_public Notebook released under the Creative Commons Attribution 4.0 License. Skewness and symmetry, like mean and variance, are ways of describing distributions. A distribution is <i>symmetric</i> if the parts on either side of the mean are mirror images of each other. For example, the normal distribution is symmetric. The normal distribution with mean $\mu$ and standard deviation $\sigma$ is defined as $$ f(x) = \frac{1}{\sigma \sqrt{2 \pi}} e^{-\frac{(x - \mu)^2}{2 \sigma^2}} $$ We can plot it to confirm that it is symmetric: End of explanation # Generate x-values for which we will plot the distribution xs2 = np.linspace(stats.lognorm.ppf(0.01, .7, loc=-.1), stats.lognorm.ppf(0.99, .7, loc=-.1), 150) # Negatively skewed distribution lognormal = stats.lognorm.pdf(xs2, .7) plt.plot(xs2, lognormal, label='Skew < 0') # Positively skewed distribution plt.plot(xs2, lognormal[::-1], label='Skew > 0') plt.legend(); Explanation: A distribution which is not symmetric is called <i>skewed</i>. For instance, a distribution can have many small positive and a few large negative values (negatively skewed) or vice versa (positively skewed), and still have a mean of 0. A symmetric distribution has skewness 0. Positively skewed unimodal (one mode) distributions have the property that mean > median > mode. Negatively skewed unimodal distributions are the reverse, with mean < median < mode. All three are equal for a symmetric unimodal distribution. The explicit formula for skewness is $$ S_K = \frac{n}{(n-1)(n-2)} \frac{\sum_{i=1}^n (X_i - \mu)^3}{\sigma^3} $$ where $n$ is the number of observations, $\mu$ is the arithmetic mean, and $\sigma$ is the standard deviation. The sign of this quantity describes the direction of the skew as described above. We can plot a positively skewed and a negatively skewed distribution to see what they look like. End of explanation start = '2012-01-01' end = '2015-01-01' pricing = get_pricing('SPY', fields='price', start_date=start, end_date=end) returns = pricing.pct_change()[1:] print 'Skew:', stats.skew(returns) print 'Mean:', np.mean(returns) print 'Median:', np.median(returns) plt.hist(returns, 30); Explanation: Although skew is less obvious when graphing discrete data sets, we can still compute it. For example, below are the skew, mean, and median for S&P 500 returns 2012-2014. Note that the skew is negative, and so the mean is less than the median. End of explanation # Plot some example distributions plt.plot(xs,stats.laplace.pdf(xs), label='Leptokurtic') print 'Excess kurtosis of leptokurtic distribution:', (stats.laplace.stats(moments='k')) plt.plot(xs, normal, label='Mesokurtic (normal)') print 'Excess kurtosis of mesokurtic distribution:', (stats.norm.stats(moments='k')) plt.plot(xs,stats.cosine.pdf(xs), label='Platykurtic') print 'Excess kurtosis of platykurtic distribution:', (stats.cosine.stats(moments='k')) plt.legend(); Explanation: Kurtosis Kurtosis attempts to measure the shape of the deviation from the mean. It's measured relative to a normal distribution, which is called mesokurtic. All normal distributions, regardless of mean and variance, have a kurtosis of 3. A leptokurtic distribution (kurtosis > 3) is highly peaked and has fat tails, while a platykurtic distribution (kurtosis < 3) is broad. Sometimes, however, kurtosis in excess of the normal distribution (kurtosis - 3) is used, and this is the default in scipy. End of explanation print stats.kurtosis(returns) Explanation: The formula for kurtosis is $$ K = \left ( \frac{n(n+1)}{(n-1)(n-2)(n-3)} \frac{\sum_{i=1}^n (X_i - \mu)^4}{\sigma^4} \right ) $$ while excess kurtosis is given by $$ K_E = \left ( \frac{n(n+1)}{(n-1)(n-2)(n-3)} \frac{\sum_{i=1}^n (X_i - \mu)^4}{\sigma^4} \right ) - \frac{3(n-1)^2}{(n-2)(n-3)} $$ For a large number of samples, the excess kurtosis becomes approximately $$ K_E \approx \frac{1}{n} \frac{\sum_{i=1}^n (X_i - \mu)^4}{\sigma^4} - 3 $$ Since above we were considering perfect, continuous distributions, this was the form that kurtosis took. However, for a set of samples drawn for the normal distribution, we would use the first definition, and (excess) kurtosis would only be approximately 0. We can use scipy to find the excess kurtosis of the S&P 500 returns from before. End of explanation from statsmodels.stats.stattools import jarque_bera print jarque_bera(returns)[1] Explanation: The histogram of the returns shows significant observations beyond 3 standard deviations away from the mean, so we shouldn't be surprised that the kurtosis is indicating a leptokurtic distribution. Other standardized moments It's no coincidence that the variance, skewness, and kurtosis take similar forms. They are the first and most important standardized moments, of which the $k$th has the form $$ \frac{E[(X - E[X])^k]}{\sigma^k} $$ The first standardized moment is always 0 $(E[X - E[X]] = E[X] - E[E[X]] = 0)$, so we only care about the second through fourth. All of the standardized moments are dimensionless numbers which describe the distribution, and in particular can be used to quantify how close to normal (having standardized moments $0, \sigma, 0, \sigma^2$) a distribution is. One method is the Jarque-Bera test, which we can run on the S&P 500 returns to find the p-value for them coming from a normal distribution. End of explanation
7,382
Given the following text description, write Python code to implement the functionality described below step by step Description: Text Classification using TensorFlow and Google Cloud - Part 4 This bigquery-public-data Step1: Importing libraries Step2: 1. Define Metadata Step3: 2. Define Input Function Step4: 3. Create feature columns Step5: 4. Create a model using a premade DNNClassifer Step6: 5. Setup Experiment 5.1 HParams and RunConfig Step7: 5.2 Serving function Step8: 5.3 TrainSpec & EvalSpec Step9: 6. Run experiment Step10: 7. Evaluate the model Step11: 8. Use Saved Model for Predictions
Python Code: import os class Params: pass # Set to run on GCP Params.GCP_PROJECT_ID = 'ksalama-gcp-playground' Params.REGION = 'europe-west1' Params.BUCKET = 'ksalama-gcs-cloudml' Params.PLATFORM = 'local' # local | GCP Params.DATA_DIR = 'data/news' if Params.PLATFORM == 'local' else 'gs://{}/data/news'.format(Params.BUCKET) Params.TRANSFORMED_DATA_DIR = os.path.join(Params.DATA_DIR, 'transformed') Params.TRANSFORMED_TRAIN_DATA_FILE_PREFIX = os.path.join(Params.TRANSFORMED_DATA_DIR, 'train') Params.TRANSFORMED_EVAL_DATA_FILE_PREFIX = os.path.join(Params.TRANSFORMED_DATA_DIR, 'eval') Params.TEMP_DIR = os.path.join(Params.DATA_DIR, 'tmp') Params.MODELS_DIR = 'models/news' if Params.PLATFORM == 'local' else 'gs://{}/models/news'.format(Params.BUCKET) Params.TRANSFORM_ARTEFACTS_DIR = os.path.join(Params.MODELS_DIR,'transform') Params.TRAIN = True Params.RESUME_TRAINING = False Params.EAGER = False if Params.EAGER: tf.enable_eager_execution() Explanation: Text Classification using TensorFlow and Google Cloud - Part 4 This bigquery-public-data:hacker_news contains all stories and comments from Hacker News from its launch in 2006. Each story contains a story id, url, the title of the story, tthe author that made the post, when it was written, and the number of points the story received. The objective is, given the title of the story, we want to build an ML model that can predict the source of this story. TF DNNClassifier with TF.IDF Text Reprsentation This notebook illustrates how to build a TF premade estimator, namely DNNClassifier, while the input text will be repesented as TF.IDF computed during the preprocessing phase in Part 1. The overall steps are as follows: Define the metadata Define data input function Create feature columns (using the tfidf) Create the premade DNNClassifier estimator Setup experiement Hyper-parameters & RunConfig Serving function (for exported model) TrainSpec & EvalSpec Run experiement Evalute the model Use SavedModel for prediction Setting Global Parameters End of explanation import tensorflow as tf from tensorflow import data from tensorflow.contrib.learn.python.learn.utils import input_fn_utils from tensorflow_transform.beam.tft_beam_io import transform_fn_io from tensorflow_transform.tf_metadata import metadata_io from tensorflow_transform.tf_metadata import dataset_schema from tensorflow_transform.tf_metadata import dataset_metadata from tensorflow_transform.saved import saved_transform_io print tf.__version__ Explanation: Importing libraries End of explanation RAW_HEADER = 'key,title,source'.split(',') RAW_DEFAULTS = [['NA'],['NA'],['NA']] TARGET_FEATURE_NAME = 'source' TARGET_LABELS = ['github', 'nytimes', 'techcrunch'] TEXT_FEATURE_NAME = 'title' KEY_COLUMN = 'key' VOCAB_SIZE = 20000 TRAIN_SIZE = 73124 EVAL_SIZE = 23079 DELIMITERS = '.,!?() ' raw_metadata = dataset_metadata.DatasetMetadata(dataset_schema.Schema({ KEY_COLUMN: dataset_schema.ColumnSchema( tf.string, [], dataset_schema.FixedColumnRepresentation()), TEXT_FEATURE_NAME: dataset_schema.ColumnSchema( tf.string, [], dataset_schema.FixedColumnRepresentation()), TARGET_FEATURE_NAME: dataset_schema.ColumnSchema( tf.string, [], dataset_schema.FixedColumnRepresentation()), })) transformed_metadata = metadata_io.read_metadata( os.path.join(Params.TRANSFORM_ARTEFACTS_DIR,"transformed_metadata")) raw_feature_spec = raw_metadata.schema.as_feature_spec() transformed_feature_spec = transformed_metadata.schema.as_feature_spec() print transformed_feature_spec Explanation: 1. Define Metadata End of explanation def parse_tf_example(tf_example): parsed_features = tf.parse_single_example(serialized=tf_example, features=transformed_feature_spec) target = parsed_features.pop(TARGET_FEATURE_NAME) return parsed_features, target def generate_tfrecords_input_fn(files_pattern, mode=tf.estimator.ModeKeys.EVAL, num_epochs=1, batch_size=200): def _input_fn(): file_names = data.Dataset.list_files(files_pattern) if Params.EAGER: print file_names dataset = data.TFRecordDataset(file_names ) dataset = dataset.apply( tf.contrib.data.shuffle_and_repeat(count=num_epochs, buffer_size=batch_size*2) ) dataset = dataset.apply( tf.contrib.data.map_and_batch(parse_tf_example, batch_size=batch_size, num_parallel_batches=2) ) datset = dataset.prefetch(batch_size) if Params.EAGER: return dataset iterator = dataset.make_one_shot_iterator() features, target = iterator.get_next() return features, target return _input_fn Explanation: 2. Define Input Function End of explanation BOW_FEATURE_NAME = 'bow' TFIDF_FEATURE_NAME = 'weight' def create_feature_columns(): # Get word indecies from bow bow = tf.feature_column.categorical_column_with_identity( BOW_FEATURE_NAME, num_buckets=VOCAB_SIZE + 1) # Add weight to the word indecies weight_bow = tf.feature_column.weighted_categorical_column( bow, TFIDF_FEATURE_NAME) # Convert to indicator weight_bow_indicators = tf.feature_column.indicator_column(weight_bow) return [weight_bow_indicators] Explanation: 3. Create feature columns End of explanation def create_estimator(hparams, run_config): feature_columns = create_feature_columns() optimizer = tf.train.AdamOptimizer(learning_rate=hparams.learning_rate) estimator = tf.estimator.DNNClassifier( feature_columns=feature_columns, n_classes =len(TARGET_LABELS), label_vocabulary=TARGET_LABELS, hidden_units=hparams.hidden_units, optimizer=optimizer, config=run_config ) return estimator Explanation: 4. Create a model using a premade DNNClassifer End of explanation NUM_EPOCHS = 10 BATCH_SIZE = 1000 TOTAL_STEPS = (TRAIN_SIZE/BATCH_SIZE)*NUM_EPOCHS EVAL_EVERY_SEC = 60 hparams = tf.contrib.training.HParams( num_epochs = NUM_EPOCHS, batch_size = BATCH_SIZE, learning_rate = 0.01, hidden_units=[64, 32], max_steps = TOTAL_STEPS, ) MODEL_NAME = 'dnn_estimator_tfidf' model_dir = os.path.join(Params.MODELS_DIR, MODEL_NAME) run_config = tf.estimator.RunConfig( tf_random_seed=19830610, log_step_count_steps=1000, save_checkpoints_secs=EVAL_EVERY_SEC, keep_checkpoint_max=1, model_dir=model_dir ) print(hparams) print("") print("Model Directory:", run_config.model_dir) print("Dataset Size:", TRAIN_SIZE) print("Batch Size:", BATCH_SIZE) print("Steps per Epoch:",TRAIN_SIZE/BATCH_SIZE) print("Total Steps:", TOTAL_STEPS) Explanation: 5. Setup Experiment 5.1 HParams and RunConfig End of explanation def generate_serving_input_fn(): def _serving_fn(): receiver_tensor = { 'title': tf.placeholder(dtype=tf.string, shape=[None]) } _, transformed_features = ( saved_transform_io.partially_apply_saved_transform( os.path.join(Params.TRANSFORM_ARTEFACTS_DIR, transform_fn_io.TRANSFORM_FN_DIR), receiver_tensor) ) return tf.estimator.export.ServingInputReceiver( transformed_features, receiver_tensor) return _serving_fn Explanation: 5.2 Serving function End of explanation train_spec = tf.estimator.TrainSpec( input_fn = generate_tfrecords_input_fn( Params.TRANSFORMED_TRAIN_DATA_FILE_PREFIX+"*", mode = tf.estimator.ModeKeys.TRAIN, num_epochs=hparams.num_epochs, batch_size=hparams.batch_size ), max_steps=hparams.max_steps, hooks=None ) eval_spec = tf.estimator.EvalSpec( input_fn = generate_tfrecords_input_fn( Params.TRANSFORMED_EVAL_DATA_FILE_PREFIX+"*", mode=tf.estimator.ModeKeys.EVAL, num_epochs=1, batch_size=hparams.batch_size ), exporters=[tf.estimator.LatestExporter( name="estimate", # the name of the folder in which the model will be exported to under export serving_input_receiver_fn=generate_serving_input_fn(), exports_to_keep=1, as_text=False)], steps=None, throttle_secs=EVAL_EVERY_SEC ) Explanation: 5.3 TrainSpec & EvalSpec End of explanation from datetime import datetime import shutil if Params.TRAIN: if not Params.RESUME_TRAINING: print("Removing previous training artefacts...") shutil.rmtree(model_dir, ignore_errors=True) else: print("Resuming training...") tf.logging.set_verbosity(tf.logging.INFO) time_start = datetime.utcnow() print("Experiment started at {}".format(time_start.strftime("%H:%M:%S"))) print(".......................................") estimator = create_estimator(hparams, run_config) tf.estimator.train_and_evaluate( estimator=estimator, train_spec=train_spec, eval_spec=eval_spec ) time_end = datetime.utcnow() print(".......................................") print("Experiment finished at {}".format(time_end.strftime("%H:%M:%S"))) print("") time_elapsed = time_end - time_start print("Experiment elapsed time: {} seconds".format(time_elapsed.total_seconds())) else: print "Training was skipped!" Explanation: 6. Run experiment End of explanation tf.logging.set_verbosity(tf.logging.ERROR) estimator = create_estimator(hparams, run_config) train_metrics = estimator.evaluate( input_fn = generate_tfrecords_input_fn( files_pattern= Params.TRANSFORMED_TRAIN_DATA_FILE_PREFIX+"*", mode= tf.estimator.ModeKeys.EVAL, batch_size= TRAIN_SIZE), steps=1 ) print("############################################################################################") print("# Train Measures: {}".format(train_metrics)) print("############################################################################################") eval_metrics = estimator.evaluate( input_fn=generate_tfrecords_input_fn( files_pattern= Params.TRANSFORMED_EVAL_DATA_FILE_PREFIX+"*", mode= tf.estimator.ModeKeys.EVAL, batch_size= EVAL_SIZE), steps=1 ) print("") print("############################################################################################") print("# Eval Measures: {}".format(eval_metrics)) print("############################################################################################") Explanation: 7. Evaluate the model End of explanation import os export_dir = model_dir +"/export/estimate/" saved_model_dir = os.path.join(export_dir, os.listdir(export_dir)[0]) print(saved_model_dir) print("") predictor_fn = tf.contrib.predictor.from_saved_model( export_dir = saved_model_dir, signature_def_key="predict" ) output = predictor_fn( { 'title':[ 'Microsoft and Google are joining forces for a new AI framework', 'A new version of Python is mind blowing', 'EU is investigating new data privacy policies' ] } ) print(output) Explanation: 8. Use Saved Model for Predictions End of explanation
7,383
Given the following text description, write Python code to implement the functionality described below step by step Description: Structure and Angular Momentum Step1: Adding Structure So far we've looked at simple 2 and 3 level systems, but to accurately model a physical system we may need to consider complex structures. For example, the hyperfine structure of alkali metals used commonly in optical experiments. It is possible to define structure in MaxwellBloch and provide strength factors for the field couplings and decays between pairs of sublevels. We'll take the example of a Rubidium 87 atom addressed with a weak field resonant with the $5\mathrm{S}{1/2} F=1 \rightarrow 5\mathrm{P}{1/2} F=1$ transition. We can neglect the other upper level in the fine structure manifold, $5\mathrm{P}{1/2} F={2}$, as it is far from resonance. However, the decay to $5\mathrm{S}{1/2} F={2}$ should be considered. If we start with the case of an isotropic field (with equal components in all three polarizations), we can neglect the substructure and just add the hyperfine levels, as the coupling how the population is distributed among the sublevels. For now, the relative strengths of the transitions are given in the following table | | F'=1 | F'=2 | | --- | --- | --- | | F=1 | $\tfrac{1}{6}$ | $\tfrac{5}{6}$ | | F=2 | $\tfrac{1}{2}$ | $\tfrac{1}{2}$ | and below (see Note on Strength Factors) we'll see how these are computed. We will index the three hyperfine levels we require as in the following table. | idx | Hyperfine level | | --- | ----------------- | | 0 | $5\mathrm{S}{1/2} F~=~1$ | | 1 | $5\mathrm{S}{1/2} F~=~2$ | | 2 | $5\mathrm{P}_{1/2} F'~=~1$| How do we include those transition strengths in the system? Both the fields and decays have optional factors mapped to them for this purpose. For the decays, we have transitions $\left|0\right> \rightarrow \left|2\right>$ and $\left|1\right> \rightarrow \left|2\right>$. As per the table above, $S_{11} = \tfrac{1}{6}$ and $S_{21} = \tfrac{1}{2}$. Our factors for the isotropic field are then $\sqrt{\tfrac{1}{3}\cdot\tfrac{1}{6}}$ and $\sqrt{\tfrac{1}{3}\cdot\tfrac{1}{2}}$ respectively Step3: We'll put those channels and their respective factors into the MBSolve object. Step4: Output Step5: Hyperfine Structure for Single (Outer) Electron Atoms In experiments with single outer electron atoms like Rubidium involving polarised (non-isotropic) light, we may need to consider the effect of hyperfine pumping mechanisms. Our state basis must then include the hyperfine structure and magnetic substructure of these fine structure manifolds, consisting of $2F+1$ degenerate sublevels $m_F={F,−F+1, . . . ,F−1,F}$ within each hyperfine level. The coupling of each pair of hyperfine sublevels is factored by the reduced dipole matrix element for that pair. This is not the place to go into how we calculate those reduced dipole matrix elements, see Ogden 2016, chapter 5 for details. The good news is that MaxwellBloch has helper functions in the hyperfine module to build the hyperfine structure for us, and calculate the reduced dipole matrix element factors. First we can use the hyperfine module to create the hyperfine structure ($F$ levels). As before we will model a weak field resonant with the $5\mathrm{S}{1/2} F=1 \rightarrow 5\mathrm{P}{1/2} F=1$ transition. Again we can neglect the other upper level in the fine structure manifold, $5\mathrm{P}{1/2} F={2}$, as it is far from resonance, but the decay to $5\mathrm{S}{1/2} F={2}$ will be considered. Step6: We can see looking at the lower $F=1$ level that the hyperfine structure $m_F={-1, 0 ,1}$ is built automatically based on the angular moment numbers $I$, $J$ and $F$. Step7: If there are levels to be addressed that are off resonance, we would need to add $F$ level energies (e.g. if we included the $F'=2$ upper level). Note that these only need to be relative to the resonance freq. If the mF levels are split (for example with a magnetic field), the individual mf level energies can be added relative to the $F$ level energy. We add the $F$ levels to the atom structure object. Step8: We now have everything we need to build our MBSolve object. First, the total number of states Step9: Energies and Detuning Then the energies of these states, if they have been specified (no need in this case but here for completeness) Step10: As for the solvers without structure, if desired we can specify a detuning Step11: Now the levels to be coupled by the field are each F=1 to F'=1 combination pair. atom1e has a helper function for that (based on the order we added them above. F_level_idxs_a is for the lower level, F_level_idxs_b is for the upper) Step12: And now the important part, we need to calculate the Clebsch-Gordan coefficients that couple each $M_F$ substructure pair. The atom1e class has a method to calculate these for us. We need to specify the polarisation of the light using $q={-1, 0 ,1}$. In this case we'll choose $q=1$. Step13: Decay Channels and Factors Similarly to the levels coupled by the field, we need to specify the pairs of levels that will be channels for spontaneous decay. This time the lower levels are all in both F=1 and F=2, so there are more combinations. Step14: The spontaneous decay factors matching those channels (in order) can be obtained with the get_decay_factors method. This is equivalent to summing the get_clebsch_hf_factors_hf for all polarisations as decay photons are of all polarisations. Step15: Initial State In the two and three level models we didn't specify an initial state for the system, which defaults to all population in the first (i.e. ground state). Here we need to correctly distribute the population in the ground state $m_F$ levels, which should of course sum to one. Step17: Putting it all into MBSolve We now have everything we need to build the MBSolve object. Step18: Output We can output the field exactly as we would do for the two-level system. Step19: Plotting Populations and Coherences If we want to get the populations in all the levels coupled by a field, we have a helper function mbs.populations_field. For example, if we want to look at the total population of all the upper sublevels coupled by the field Step20: And for the sum of all the complex coherences on a field transition, we similarly have mbs.coherences_field Step21: Note on Stength Factors The strength factor gives the relative strength hyperfine transition. This is the sum $S_{FF'}$ of the matrix elements from a single ground-state sublevel to the levels in a particular $F'$ energy level, and the sum is independent of the ground state sublevel chosen. The sum of $S_{FF'}$ over upper $F'$ levels is $1$.
Python Code: import numpy as np Explanation: Structure and Angular Momentum End of explanation print(np.sqrt(1/6/3)) print(np.sqrt(1/2/3)) Explanation: Adding Structure So far we've looked at simple 2 and 3 level systems, but to accurately model a physical system we may need to consider complex structures. For example, the hyperfine structure of alkali metals used commonly in optical experiments. It is possible to define structure in MaxwellBloch and provide strength factors for the field couplings and decays between pairs of sublevels. We'll take the example of a Rubidium 87 atom addressed with a weak field resonant with the $5\mathrm{S}{1/2} F=1 \rightarrow 5\mathrm{P}{1/2} F=1$ transition. We can neglect the other upper level in the fine structure manifold, $5\mathrm{P}{1/2} F={2}$, as it is far from resonance. However, the decay to $5\mathrm{S}{1/2} F={2}$ should be considered. If we start with the case of an isotropic field (with equal components in all three polarizations), we can neglect the substructure and just add the hyperfine levels, as the coupling how the population is distributed among the sublevels. For now, the relative strengths of the transitions are given in the following table | | F'=1 | F'=2 | | --- | --- | --- | | F=1 | $\tfrac{1}{6}$ | $\tfrac{5}{6}$ | | F=2 | $\tfrac{1}{2}$ | $\tfrac{1}{2}$ | and below (see Note on Strength Factors) we'll see how these are computed. We will index the three hyperfine levels we require as in the following table. | idx | Hyperfine level | | --- | ----------------- | | 0 | $5\mathrm{S}{1/2} F~=~1$ | | 1 | $5\mathrm{S}{1/2} F~=~2$ | | 2 | $5\mathrm{P}_{1/2} F'~=~1$| How do we include those transition strengths in the system? Both the fields and decays have optional factors mapped to them for this purpose. For the decays, we have transitions $\left|0\right> \rightarrow \left|2\right>$ and $\left|1\right> \rightarrow \left|2\right>$. As per the table above, $S_{11} = \tfrac{1}{6}$ and $S_{21} = \tfrac{1}{2}$. Our factors for the isotropic field are then $\sqrt{\tfrac{1}{3}\cdot\tfrac{1}{6}}$ and $\sqrt{\tfrac{1}{3}\cdot\tfrac{1}{2}}$ respectively: the square roots of these strength factors multiplied by a third (as any given polarization of the field only interacts with one of the three components of the dipole moment. End of explanation mb_solve_json = { "atom": { "decays": [ { "rate": 1.0, "channels": [[0,2], [1,2]], "factors": [0.23570226039551587, 0.408248290463863] } ], "fields": [ { "coupled_levels": [[0, 2]], "factors": [0.23570226039551584], "rabi_freq": 1e-3, "rabi_freq_t_args": { "ampl": 1.0, "centre": 0.0, "fwhm": 1.0 }, "rabi_freq_t_func": "gaussian" } ], "num_states": 3, "initial_state": [0.5, 0.5, 0] }, "t_min": -2.0, "t_max": 10.0, "t_steps": 100, "z_min": -0.2, "z_max": 1.2, "z_steps": 100, "z_steps_inner": 1, "interaction_strengths": [ 1.0e2 ], "savefile": "structure-1" } from maxwellbloch import mb_solve mbs = mb_solve.MBSolve().from_json_str(mb_solve_json) Omegas_zt, states_zt = mbs.mbsolve(recalc=True) Explanation: We'll put those channels and their respective factors into the MBSolve object. End of explanation import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns sns.set_style('dark') fig = plt.figure(1, figsize=(16, 6)) ax = fig.add_subplot(111) # cmap_range = np.linspace(0.0, 1.0e-3, 11) cf = ax.contourf(mbs.tlist, mbs.zlist, np.abs(mbs.Omegas_zt[0]/(2*np.pi)), # cmap_range, cmap=plt.cm.Blues ) ax.set_title('Rabi Frequency ($\Gamma / 2\pi $)') ax.set_xlabel('Time ($1/\Gamma$)') ax.set_ylabel('Distance ($L$)') for y in [0.0, 1.0]: ax.axhline(y, c='grey', lw=1.0, ls='dotted') plt.colorbar(cf); Explanation: Output End of explanation from maxwellbloch import hyperfine # Init the two lower F levels Rb87_5s12_F1 = hyperfine.LevelF(I=1.5, J=0.5, F=1, energy=0.0, mF_energies=[]) Rb87_5s12_F2 = hyperfine.LevelF(I=1.5, J=0.5, F=2, energy=0.0, mF_energies=[]) # Init the upper F level Rb87_5p12_F1 = hyperfine.LevelF(I=1.5, J=0.5, F=1, energy=0.0, mF_energies=[]) Explanation: Hyperfine Structure for Single (Outer) Electron Atoms In experiments with single outer electron atoms like Rubidium involving polarised (non-isotropic) light, we may need to consider the effect of hyperfine pumping mechanisms. Our state basis must then include the hyperfine structure and magnetic substructure of these fine structure manifolds, consisting of $2F+1$ degenerate sublevels $m_F={F,−F+1, . . . ,F−1,F}$ within each hyperfine level. The coupling of each pair of hyperfine sublevels is factored by the reduced dipole matrix element for that pair. This is not the place to go into how we calculate those reduced dipole matrix elements, see Ogden 2016, chapter 5 for details. The good news is that MaxwellBloch has helper functions in the hyperfine module to build the hyperfine structure for us, and calculate the reduced dipole matrix element factors. First we can use the hyperfine module to create the hyperfine structure ($F$ levels). As before we will model a weak field resonant with the $5\mathrm{S}{1/2} F=1 \rightarrow 5\mathrm{P}{1/2} F=1$ transition. Again we can neglect the other upper level in the fine structure manifold, $5\mathrm{P}{1/2} F={2}$, as it is far from resonance, but the decay to $5\mathrm{S}{1/2} F={2}$ will be considered. End of explanation print(Rb87_5s12_F1) Explanation: We can see looking at the lower $F=1$ level that the hyperfine structure $m_F={-1, 0 ,1}$ is built automatically based on the angular moment numbers $I$, $J$ and $F$. End of explanation # Init the atom structure object and add the F levels atom1e = hyperfine.Atom1e() atom1e.add_F_level(Rb87_5s12_F1) atom1e.add_F_level(Rb87_5s12_F2) atom1e.add_F_level(Rb87_5p12_F1) Explanation: If there are levels to be addressed that are off resonance, we would need to add $F$ level energies (e.g. if we included the $F'=2$ upper level). Note that these only need to be relative to the resonance freq. If the mF levels are split (for example with a magnetic field), the individual mf level energies can be added relative to the $F$ level energy. We add the $F$ levels to the atom structure object. End of explanation NUM_STATES = atom1e.get_num_mF_levels() print(NUM_STATES) Explanation: We now have everything we need to build our MBSolve object. First, the total number of states: End of explanation ENERGIES = atom1e.get_energies() print(ENERGIES) Explanation: Energies and Detuning Then the energies of these states, if they have been specified (no need in this case but here for completeness): End of explanation # Tune to be on resonance with the F1 -> F1 transition DETUNING = 0 print(DETUNING) Explanation: As for the solvers without structure, if desired we can specify a detuning: End of explanation FIELD_CHANNELS = atom1e.get_coupled_levels(F_level_idxs_a=[0], F_level_idxs_b=[2]) print(FIELD_CHANNELS) Explanation: Now the levels to be coupled by the field are each F=1 to F'=1 combination pair. atom1e has a helper function for that (based on the order we added them above. F_level_idxs_a is for the lower level, F_level_idxs_b is for the upper): Field Channels and Factors End of explanation q = 1 # Field polarisation FIELD_FACTORS = atom1e.get_clebsch_hf_factors(F_level_idxs_a=[0], F_level_idxs_b=[2], q=q) print(FIELD_FACTORS) Explanation: And now the important part, we need to calculate the Clebsch-Gordan coefficients that couple each $M_F$ substructure pair. The atom1e class has a method to calculate these for us. We need to specify the polarisation of the light using $q={-1, 0 ,1}$. In this case we'll choose $q=1$. End of explanation DECAY_CHANNELS = atom1e.get_coupled_levels(F_level_idxs_a=[0,1], F_level_idxs_b=[2]) print(DECAY_CHANNELS) Explanation: Decay Channels and Factors Similarly to the levels coupled by the field, we need to specify the pairs of levels that will be channels for spontaneous decay. This time the lower levels are all in both F=1 and F=2, so there are more combinations. End of explanation DECAY_FACTORS = atom1e.get_decay_factors(F_level_idxs_a=[0, 1], F_level_idxs_b=[2]) print(DECAY_FACTORS) Explanation: The spontaneous decay factors matching those channels (in order) can be obtained with the get_decay_factors method. This is equivalent to summing the get_clebsch_hf_factors_hf for all polarisations as decay photons are of all polarisations. End of explanation INITIAL_STATE = ( [0.5/3.0]*3 + # s12_F1b [0.5/5.0]*5 + # s12_F2 [0.0]*3) # p12_F1 print(INITIAL_STATE) print(sum(INITIAL_STATE)) Explanation: Initial State In the two and three level models we didn't specify an initial state for the system, which defaults to all population in the first (i.e. ground state). Here we need to correctly distribute the population in the ground state $m_F$ levels, which should of course sum to one. End of explanation mb_solve_json = {{ "atom": {{ "decays": [ {{ "channels": {decay_channels}, "rate": 1.0, "factors": {decay_factors} }} ], "energies": {energies}, "fields": [ {{ "coupled_levels": {field_channels}, "factors": {field_factors}, "detuning": {detuning}, "detuning_positive": true, "label": "probe", "rabi_freq": 1e-3, "rabi_freq_t_args": {{ "ampl": 1.0, "centre": 0.0, "fwhm": 1.0 }}, "rabi_freq_t_func": "gaussian" }} ], "num_states": {num_states}, "initial_state": {initial_state} }}, "t_min": -2.0, "t_max": 10.0, "t_steps": 100, "z_min": -0.2, "z_max": 1.2, "z_steps": 100, "z_steps_inner": 1, "interaction_strengths": [ 1.0e2 ], "savefile": "structure-2" }} .format(num_states=NUM_STATES, energies=ENERGIES, initial_state=INITIAL_STATE, detuning=DETUNING, field_channels=FIELD_CHANNELS, field_factors=list(FIELD_FACTORS), decay_channels=DECAY_CHANNELS, decay_factors=list(DECAY_FACTORS)) from maxwellbloch import mb_solve mbs = mb_solve.MBSolve().from_json_str(mb_solve_json) Omegas_zt, states_zt = mbs.mbsolve(recalc=True) Explanation: Putting it all into MBSolve We now have everything we need to build the MBSolve object. End of explanation import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns sns.set_style('dark') fig = plt.figure(1, figsize=(16, 6)) ax = fig.add_subplot(111) # cmap_range = np.linspace(0.0, 1.0e-3, 11) cf = ax.contourf(mbs.tlist, mbs.zlist, np.abs(mbs.Omegas_zt[0]/(2*np.pi)), # cmap_range, cmap=plt.cm.Blues ) ax.set_title('Rabi Frequency ($\Gamma / 2\pi $)') ax.set_xlabel('Time ($1/\Gamma$)') ax.set_ylabel('Distance ($L$)') for y in [0.0, 1.0]: ax.axhline(y, c='grey', lw=1.0, ls='dotted') plt.colorbar(cf); Explanation: Output We can output the field exactly as we would do for the two-level system. End of explanation fig = plt.figure(1, figsize=(16, 6)) ax = fig.add_subplot(111) # cmap_range = np.linspace(0.0, 1.0e-3, 11) cf = ax.contourf(mbs.tlist, mbs.zlist, np.abs(mbs.populations_field(field_idx=0, upper=False)), # cmap_range, cmap=plt.cm.Reds ) ax.set_title('Rabi Frequency ($\Gamma / 2\pi $)') ax.set_xlabel('Time ($1/\Gamma$)') ax.set_ylabel('Distance ($L$)') for y in [0.0, 1.0]: ax.axhline(y, c='grey', lw=1.0, ls='dotted') plt.colorbar(cf); Explanation: Plotting Populations and Coherences If we want to get the populations in all the levels coupled by a field, we have a helper function mbs.populations_field. For example, if we want to look at the total population of all the upper sublevels coupled by the field: End of explanation fig = plt.figure(1, figsize=(16, 6)) ax = fig.add_subplot(111) # cmap_range = np.linspace(0.0, 1.0e-3, 11) cf = ax.contourf(mbs.tlist, mbs.zlist, np.imag(mbs.coherences_field(field_idx=0)), # cmap_range, cmap=plt.cm.Greens ) ax.set_title('Rabi Frequency ($\Gamma / 2\pi $)') ax.set_xlabel('Time ($1/\Gamma$)') ax.set_ylabel('Distance ($L$)') for y in [0.0, 1.0]: ax.axhline(y, c='grey', lw=1.0, ls='dotted') plt.colorbar(cf); Explanation: And for the sum of all the complex coherences on a field transition, we similarly have mbs.coherences_field: End of explanation s_11 = atom1e.get_strength_factor(F_level_idx_lower=0, F_level_idx_upper=2) print(s_11) s_12 = atom1e.get_strength_factor(F_level_idx_lower=1, F_level_idx_upper=2) print(s_12) Explanation: Note on Stength Factors The strength factor gives the relative strength hyperfine transition. This is the sum $S_{FF'}$ of the matrix elements from a single ground-state sublevel to the levels in a particular $F'$ energy level, and the sum is independent of the ground state sublevel chosen. The sum of $S_{FF'}$ over upper $F'$ levels is $1$. End of explanation
7,384
Given the following text description, write Python code to implement the functionality described below step by step Description: Scroll down the the analysis section to see the actual analysis Step1: Loading files Step2: Analysis Step3: Some thing seems to be up with the month of September in this data Step4: This fluctuates much more than I would expect, but I don't know if there is really much else to say about it.
Python Code: 1+1 import pandas as pd import numpy as np import glob import os Explanation: Scroll down the the analysis section to see the actual analysis End of explanation path=os.path.expanduser("~/Documents/TaxiTripData/2013taxi_trip_data/") files=glob.glob(path+'*.csv.zip.gz') countlist=[] cunk=100000 for i in files: print(i) iterate=pd.read_csv(i,usecols=[5],iterator=True,chunksize=cunk,names=['pickup_datetime'],header=0) counter=0 for chunk in iterate: a=pd.to_datetime(chunk['pickup_datetime']) if a.dtype==np.dtype('<M8[ns]'): countlist.append(a.dt.date.value_counts()) else: bads=[] for q in range(a.shape[0]): b=pd.to_datetime(a.iloc[q]) if type(b)!=pd.tslib.Timestamp: bads.append(q) a.drop(bads,axis=0,inplace=True) a=pd.to_datetime(a) if a.dtype==np.dtype('<M8[ns]'): countlist.append(a.dt.date.value_counts()) else: print('chunk ' + str(counter)+' of file '+i+' encountered a problem and was not processed.') counter+=1 cond=pd.concat(countlist) cond=cond.groupby(cond.index).sum() cond.index=pd.to_datetime(cond.index) %pwd cond.to_pickle('2013_taxi_date_counts.pkl') Explanation: Loading files End of explanation cond=pd.read_pickle('2013_taxi_date_counts.pkl') Explanation: Analysis End of explanation cond[cond.index.month==9]=np.nan cond.dropna(inplace=True) months=pd.DataFrame(cond) months['month']=months.index.month months['year']=months.index.year months=months.groupby(['year','month']).sum() months.columns=['Pickups'] months=months.append(pd.DataFrame({'year' : [2013], 'month' : [9], 'Pickups':[0]}).groupby(['year','month']).sum()).sort() plot=months.plot(kind='bar',title='Taxis trips fluctuate',color='gray',legend=False) #plot.set_xlabel('Days of the week') plot.set_ylabel('Trips') plot.get_figure().savefig('yellowcabyear.pdf') Explanation: Some thing seems to be up with the month of September in this data: it has almost double the counts of all the others. It also had some non-date data in the middle of the file. I expect that there may just be repeats in the middle of the file, but I just took it out for this analysis End of explanation dow=cond.copy() dow.index=dow.index.weekday dow=dow.groupby(dow.index).sum() dow.index=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] plot=dow.plot(kind='bar',title='Taxis are for parties too',color='gray',legend=False) plot.set_xlabel('Days of the week') plot.set_ylabel('Trips') plot.get_figure().savefig('yellowcabweek.pdf') Explanation: This fluctuates much more than I would expect, but I don't know if there is really much else to say about it. End of explanation
7,385
Given the following text description, write Python code to implement the functionality described below step by step Description: Predicting sentiment from product reviews Fire up GraphLab Create Step1: Read some product review data Loading reviews for a set of baby products. Step2: Let's explore this data together Data includes the product name, the review text and the rating of the review. Step3: Build the word count vector for each review Step4: Examining the reviews for most-sold product Step5: Build a sentiment classifier Step6: Define what's a positive and a negative sentiment We will ignore all reviews with rating = 3, since they tend to have a neutral sentiment. Reviews with a rating of 4 or higher will be considered positive, while the ones with rating of 2 or lower will have a negative sentiment. Step7: Let's train the sentiment classifier Step8: Evaluate the sentiment model Step9: Applying the learned model to understand sentiment for Giraffe Step10: Sort the reviews based on the predicted sentiment and explore Step11: Most positive reviews for the giraffe Step12: Show most negative reviews for giraffe
Python Code: import graphlab Explanation: Predicting sentiment from product reviews Fire up GraphLab Create End of explanation products = graphlab.SFrame('amazon_baby.gl/') Explanation: Read some product review data Loading reviews for a set of baby products. End of explanation products.head() Explanation: Let's explore this data together Data includes the product name, the review text and the rating of the review. End of explanation products['word_count'] = graphlab.text_analytics.count_words(products['review']) products.head() graphlab.canvas.set_target('ipynb') products['name'].show() Explanation: Build the word count vector for each review End of explanation giraffe_reviews = products[products['name'] == 'Vulli Sophie the Giraffe Teether'] len(giraffe_reviews) giraffe_reviews['rating'].show(view='Categorical') Explanation: Examining the reviews for most-sold product: 'Vulli Sophie the Giraffe Teether' End of explanation products['rating'].show(view='Categorical') Explanation: Build a sentiment classifier End of explanation #ignore all 3* reviews products = products[products['rating'] != 3] #positive sentiment = 4* or 5* reviews products['sentiment'] = products['rating'] >=4 products.head() Explanation: Define what's a positive and a negative sentiment We will ignore all reviews with rating = 3, since they tend to have a neutral sentiment. Reviews with a rating of 4 or higher will be considered positive, while the ones with rating of 2 or lower will have a negative sentiment. End of explanation train_data,test_data = products.random_split(.8, seed=0) sentiment_model = graphlab.logistic_classifier.create(train_data, target='sentiment', features=['word_count'], validation_set=test_data) Explanation: Let's train the sentiment classifier End of explanation sentiment_model.evaluate(test_data, metric='roc_curve') sentiment_model.show(view='Evaluation') Explanation: Evaluate the sentiment model End of explanation giraffe_reviews['predicted_sentiment'] = sentiment_model.predict(giraffe_reviews, output_type='probability') giraffe_reviews.head() Explanation: Applying the learned model to understand sentiment for Giraffe End of explanation giraffe_reviews = giraffe_reviews.sort('predicted_sentiment', ascending=False) giraffe_reviews.head() Explanation: Sort the reviews based on the predicted sentiment and explore End of explanation giraffe_reviews[0]['review'] giraffe_reviews[1]['review'] Explanation: Most positive reviews for the giraffe End of explanation giraffe_reviews[-1]['review'] giraffe_reviews[-2]['review'] diaper_champ_reviews = products[products['name'] == 'Baby Trend Diaper Champ'] diaper_champ_reviews['predicted_sentiment'] = sentiment_model.predict(diaper_champ_reviews, output_type='probability') diaper_champ_reviews = diaper_champ_reviews.sort('predicted_sentiment', ascending=False) diaper_champ_reviews.head() Explanation: Show most negative reviews for giraffe End of explanation
7,386
Given the following text description, write Python code to implement the functionality described below step by step Description: Earth temperature over time Is global temperature rising? How much? This is a question of burning importance in today's world! Data about global temperatures are available from several sources Step1: How would we go about understanding the trends from the data on global temperature? The first step in analyzing unknown data is to generate some simple plots using matplotlib. We are going to look at the temperature-anomaly history, contained in a file, and make our first plot to explore this data. We are going to plot the data and then we'll fit a line to it to find a trend. Let's get started! Step 1 Step2: Exercise Inspect the data by printing year and temp_anomaly Step 2 Step3: You can add a semicolon at the end of the plotting command to avoid that stuff that appeared on top of the figure, that Out[x] Step4: Now we have a plot but if I give you this plot without any information you would not be able to figure out what kind of data it is! We need labels on the axis, a title and why not a better color, font and size of the ticks. Publication quality plots should always be your standard for plotting. How you present your data will allow others (and probably you in the future) to better understand your work. Let's make the font of a specific size and type. We don't want to write this out every time we create a plot. Instead, the next few lines of code will apply for all the plots we create from now on. Step5: We are going to plot the same plot as before but now we will add a few things to make it prettier and publication quality. Step6: Better ah? Feel free to play around with the parameters and see how it changes. Step 3 Step7: Split regression We have the linear function that best fits our data but this doesn't look like a good approximation. If you look at the plot you might have noticed that around 1970 the data temperature starts increasing faster. What if we break the data in two (before and after 1970) and we do a liear regression in each segment? To do that, we need to find in which position of our year array is the year 1970 located. Thanksfully, numpy has a function called numpy.where() that can help us. We need to pass a condition and numpy.where will tells us where in the array the condition is True. Step8: To split the data, we can use a powerful instrument Step9: Now we know how to split our data in two sets, to get two regression lines
Python Code: from IPython.display import YouTubeVideo YouTubeVideo('gGOzHVUQCw0') Explanation: Earth temperature over time Is global temperature rising? How much? This is a question of burning importance in today's world! Data about global temperatures are available from several sources: NASA, the National Climatic Data Center (NCDC) and the University of East Anglia in the UK. Check out the University Corporation for Atmospheric Research (UCAR) for an in-depth discussion. The NASA Goddard Space Flight Center is one of our sources of global climate data. They produced this video showing a color map of the changing global surface temperature anomalies from 1880 to 2015. The term global temperature anomaly means the difference in temperature with respect to a reference value or a long-term average. It is a very useful way of looking at the problem and in many ways better than absolute temperature. For example, a winter month may be colder than average in Washington DC, and also in Miami, but the absolute temperatures will be different in both places. End of explanation import numpy year, temp_anomaly = numpy.loadtxt(fname='data/land_global_temperature_anomaly-1880-2016.csv', delimiter=',', skiprows=5, unpack=True) Explanation: How would we go about understanding the trends from the data on global temperature? The first step in analyzing unknown data is to generate some simple plots using matplotlib. We are going to look at the temperature-anomaly history, contained in a file, and make our first plot to explore this data. We are going to plot the data and then we'll fit a line to it to find a trend. Let's get started! Step 1: Read a data file. We took the data from the NOAA (National Oceanic and Atmospheric Administration) webpage. Feel free to play around with the webpage and analyze data on your own, but for now, let's make sure we're working with the same dataset. We have some sample data in the folder called data on the tutorial repository: Caminos. The file contains the year on the first column, and averages of land temperature anomaly listed sequentially on the second column, from 1880 to 2016. We will read the file, then make an initial plot to see what it looks like. Like in Lesson 2, we're assuming that you have all the files from this tutorial, or are working on the lesson after launching Binder. Executing the following cell will save the data in two arrays, one for each column. End of explanation from matplotlib import pyplot %matplotlib inline Explanation: Exercise Inspect the data by printing year and temp_anomaly Step 2: Plot the data. Let's first load our plotting library: the pyplot module of Matplotlib. To get the plots inside the notebook (rather than as popups), we use a special "magic" command, %matplotlib inline: End of explanation pyplot.plot(year, temp_anomaly); Explanation: You can add a semicolon at the end of the plotting command to avoid that stuff that appeared on top of the figure, that Out[x]: [&lt; ...&gt;] ugliness. Try it. End of explanation from matplotlib import rcParams rcParams['font.family'] = 'serif' rcParams['font.size'] = 16 Explanation: Now we have a plot but if I give you this plot without any information you would not be able to figure out what kind of data it is! We need labels on the axis, a title and why not a better color, font and size of the ticks. Publication quality plots should always be your standard for plotting. How you present your data will allow others (and probably you in the future) to better understand your work. Let's make the font of a specific size and type. We don't want to write this out every time we create a plot. Instead, the next few lines of code will apply for all the plots we create from now on. End of explanation #You can set the size of the figure by doing: pyplot.figure(figsize=(10,5)) #Plotting pyplot.plot(year, temp_anomaly, color='#2929a3', linestyle='-', linewidth=1) pyplot.title('Land global temperature anomalies. \n') pyplot.xlabel('Year') pyplot.ylabel('Land temperature anomaly [°C]') pyplot.grid(); Explanation: We are going to plot the same plot as before but now we will add a few things to make it prettier and publication quality. End of explanation m, b = numpy.polyfit(year, temp_anomaly, 1) f_linear = numpy.poly1d((m, b)) print(f_linear) pyplot.figure(figsize=(10, 5)) pyplot.plot(year, temp_anomaly, color='#2929a3', linestyle='-', linewidth=1, alpha=0.5) pyplot.plot(year, f_linear(year), 'k--', linewidth=2, label='Linear regression') pyplot.xlabel('Year') pyplot.ylabel('Land temperature anomaly [°C]') pyplot.legend(loc='best', fontsize=15) pyplot.grid(); Explanation: Better ah? Feel free to play around with the parameters and see how it changes. Step 3: Apply regression Let's now fit a straight line through the temperature-anomaly data, to see the trends. We need to perform a least-squares linear regression to find the slope and intercept of a line $$y = mx+b$$ that fits our data. Thankfully, Python and NumPy are here to help! With polyfit(), we get the slope and y-intercept of the line that best fits the data. With poly1d(), we can build the linear function from its slope and y-intercept. End of explanation numpy.where(year==1970) Explanation: Split regression We have the linear function that best fits our data but this doesn't look like a good approximation. If you look at the plot you might have noticed that around 1970 the data temperature starts increasing faster. What if we break the data in two (before and after 1970) and we do a liear regression in each segment? To do that, we need to find in which position of our year array is the year 1970 located. Thanksfully, numpy has a function called numpy.where() that can help us. We need to pass a condition and numpy.where will tells us where in the array the condition is True. End of explanation year[0:3] Explanation: To split the data, we can use a powerful instrument: the colon notation. A colon between two indices indicates a range of values from a start to an end. The rule is that [start:end] includes the element at index start but excludes the one at index end. For example, to grab the first 3 years in our year array, we do: End of explanation year_1 , temp_anomaly_1 = year[0:90], temp_anomaly[0:90] year_2 , temp_anomaly_2 = year[90:], temp_anomaly[90:] m1, b1 = numpy.polyfit(year_1, temp_anomaly_1, 1) m2, b2 = numpy.polyfit(year_2, temp_anomaly_2, 1) f_linear_1 = numpy.poly1d((m1, b1)) f_linear_2 = numpy.poly1d((m2, b2)) pyplot.figure(figsize=(10, 5)) pyplot.plot(year, temp_anomaly, color='#2929a3', linestyle='-', linewidth=1, alpha=0.5) pyplot.plot(year_1, f_linear_1(year_1), 'g--', linewidth=2, label='1880-1969') pyplot.plot(year_2, f_linear_2(year_2), 'r--', linewidth=2, label='1970-2016') pyplot.xlabel('Year') pyplot.ylabel('Land temperature anomaly [°C]') pyplot.legend(loc='best', fontsize=15) pyplot.grid(); Explanation: Now we know how to split our data in two sets, to get two regression lines End of explanation
7,387
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify document publication status Step4: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport 3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks 4. Key Properties --&gt; Transport Scheme 5. Key Properties --&gt; Boundary Forcing 6. Key Properties --&gt; Gas Exchange 7. Key Properties --&gt; Carbon Chemistry 8. Tracers 9. Tracers --&gt; Ecosystem 10. Tracers --&gt; Ecosystem --&gt; Phytoplankton 11. Tracers --&gt; Ecosystem --&gt; Zooplankton 12. Tracers --&gt; Disolved Organic Matter 13. Tracers --&gt; Particules 14. Tracers --&gt; Dic Alkalinity 1. Key Properties Ocean Biogeochemistry key properties 1.1. Model Overview Is Required Step5: 1.2. Model Name Is Required Step6: 1.3. Model Type Is Required Step7: 1.4. Elemental Stoichiometry Is Required Step8: 1.5. Elemental Stoichiometry Details Is Required Step9: 1.6. Prognostic Variables Is Required Step10: 1.7. Diagnostic Variables Is Required Step11: 1.8. Damping Is Required Step12: 2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport Time stepping method for passive tracers transport in ocean biogeochemistry 2.1. Method Is Required Step13: 2.2. Timestep If Not From Ocean Is Required Step14: 3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks Time stepping framework for biology sources and sinks in ocean biogeochemistry 3.1. Method Is Required Step15: 3.2. Timestep If Not From Ocean Is Required Step16: 4. Key Properties --&gt; Transport Scheme Transport scheme in ocean biogeochemistry 4.1. Type Is Required Step17: 4.2. Scheme Is Required Step18: 4.3. Use Different Scheme Is Required Step19: 5. Key Properties --&gt; Boundary Forcing Properties of biogeochemistry boundary forcing 5.1. Atmospheric Deposition Is Required Step20: 5.2. River Input Is Required Step21: 5.3. Sediments From Boundary Conditions Is Required Step22: 5.4. Sediments From Explicit Model Is Required Step23: 6. Key Properties --&gt; Gas Exchange *Properties of gas exchange in ocean biogeochemistry * 6.1. CO2 Exchange Present Is Required Step24: 6.2. CO2 Exchange Type Is Required Step25: 6.3. O2 Exchange Present Is Required Step26: 6.4. O2 Exchange Type Is Required Step27: 6.5. DMS Exchange Present Is Required Step28: 6.6. DMS Exchange Type Is Required Step29: 6.7. N2 Exchange Present Is Required Step30: 6.8. N2 Exchange Type Is Required Step31: 6.9. N2O Exchange Present Is Required Step32: 6.10. N2O Exchange Type Is Required Step33: 6.11. CFC11 Exchange Present Is Required Step34: 6.12. CFC11 Exchange Type Is Required Step35: 6.13. CFC12 Exchange Present Is Required Step36: 6.14. CFC12 Exchange Type Is Required Step37: 6.15. SF6 Exchange Present Is Required Step38: 6.16. SF6 Exchange Type Is Required Step39: 6.17. 13CO2 Exchange Present Is Required Step40: 6.18. 13CO2 Exchange Type Is Required Step41: 6.19. 14CO2 Exchange Present Is Required Step42: 6.20. 14CO2 Exchange Type Is Required Step43: 6.21. Other Gases Is Required Step44: 7. Key Properties --&gt; Carbon Chemistry Properties of carbon chemistry biogeochemistry 7.1. Type Is Required Step45: 7.2. PH Scale Is Required Step46: 7.3. Constants If Not OMIP Is Required Step47: 8. Tracers Ocean biogeochemistry tracers 8.1. Overview Is Required Step48: 8.2. Sulfur Cycle Present Is Required Step49: 8.3. Nutrients Present Is Required Step50: 8.4. Nitrous Species If N Is Required Step51: 8.5. Nitrous Processes If N Is Required Step52: 9. Tracers --&gt; Ecosystem Ecosystem properties in ocean biogeochemistry 9.1. Upper Trophic Levels Definition Is Required Step53: 9.2. Upper Trophic Levels Treatment Is Required Step54: 10. Tracers --&gt; Ecosystem --&gt; Phytoplankton Phytoplankton properties in ocean biogeochemistry 10.1. Type Is Required Step55: 10.2. Pft Is Required Step56: 10.3. Size Classes Is Required Step57: 11. Tracers --&gt; Ecosystem --&gt; Zooplankton Zooplankton properties in ocean biogeochemistry 11.1. Type Is Required Step58: 11.2. Size Classes Is Required Step59: 12. Tracers --&gt; Disolved Organic Matter Disolved organic matter properties in ocean biogeochemistry 12.1. Bacteria Present Is Required Step60: 12.2. Lability Is Required Step61: 13. Tracers --&gt; Particules Particulate carbon properties in ocean biogeochemistry 13.1. Method Is Required Step62: 13.2. Types If Prognostic Is Required Step63: 13.3. Size If Prognostic Is Required Step64: 13.4. Size If Discrete Is Required Step65: 13.5. Sinking Speed If Prognostic Is Required Step66: 14. Tracers --&gt; Dic Alkalinity DIC and alkalinity properties in ocean biogeochemistry 14.1. Carbon Isotopes Is Required Step67: 14.2. Abiotic Carbon Is Required Step68: 14.3. Alkalinity Is Required
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'cams', 'sandbox-3', 'ocnbgchem') Explanation: ES-DOC CMIP6 Model Properties - Ocnbgchem MIP Era: CMIP6 Institute: CAMS Source ID: SANDBOX-3 Topic: Ocnbgchem Sub-Topics: Tracers. Properties: 65 (37 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:53:43 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) Explanation: Document Authors Set document authors End of explanation # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) Explanation: Document Contributors Specify document contributors End of explanation # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) Explanation: Document Publication Specify document publication status End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: Document Table of Contents 1. Key Properties 2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport 3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks 4. Key Properties --&gt; Transport Scheme 5. Key Properties --&gt; Boundary Forcing 6. Key Properties --&gt; Gas Exchange 7. Key Properties --&gt; Carbon Chemistry 8. Tracers 9. Tracers --&gt; Ecosystem 10. Tracers --&gt; Ecosystem --&gt; Phytoplankton 11. Tracers --&gt; Ecosystem --&gt; Zooplankton 12. Tracers --&gt; Disolved Organic Matter 13. Tracers --&gt; Particules 14. Tracers --&gt; Dic Alkalinity 1. Key Properties Ocean Biogeochemistry key properties 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of ocean biogeochemistry model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of ocean biogeochemistry model code (PISCES 2.0,...) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.model_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Geochemical" # "NPZD" # "PFT" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 1.3. Model Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of ocean biogeochemistry model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.elemental_stoichiometry') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Fixed" # "Variable" # "Mix of both" # TODO - please enter value(s) Explanation: 1.4. Elemental Stoichiometry Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe elemental stoichiometry (fixed, variable, mix of the two) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.elemental_stoichiometry_details') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.5. Elemental Stoichiometry Details Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe which elements have fixed/variable stoichiometry End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.6. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of all prognostic tracer variables in the ocean biogeochemistry component End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.diagnostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.7. Diagnostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of all diagnotic tracer variables in the ocean biogeochemistry component End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.damping') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.8. Damping Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe any tracer damping used (such as artificial correction or relaxation to climatology,...) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.passive_tracers_transport.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "use ocean model transport time step" # "use specific time step" # TODO - please enter value(s) Explanation: 2. Key Properties --&gt; Time Stepping Framework --&gt; Passive Tracers Transport Time stepping method for passive tracers transport in ocean biogeochemistry 2.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time stepping framework for passive tracers End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.passive_tracers_transport.timestep_if_not_from_ocean') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 2.2. Timestep If Not From Ocean Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Time step for passive tracers (if different from ocean) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.biology_sources_sinks.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "use ocean model transport time step" # "use specific time step" # TODO - please enter value(s) Explanation: 3. Key Properties --&gt; Time Stepping Framework --&gt; Biology Sources Sinks Time stepping framework for biology sources and sinks in ocean biogeochemistry 3.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time stepping framework for biology sources and sinks End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.time_stepping_framework.biology_sources_sinks.timestep_if_not_from_ocean') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 3.2. Timestep If Not From Ocean Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Time step for biology sources and sinks (if different from ocean) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Offline" # "Online" # TODO - please enter value(s) Explanation: 4. Key Properties --&gt; Transport Scheme Transport scheme in ocean biogeochemistry 4.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of transport scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Use that of ocean model" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 4.2. Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Transport scheme used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.transport_scheme.use_different_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 4.3. Use Different Scheme Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Decribe transport scheme if different than that of ocean model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.atmospheric_deposition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "from file (climatology)" # "from file (interannual variations)" # "from Atmospheric Chemistry model" # TODO - please enter value(s) Explanation: 5. Key Properties --&gt; Boundary Forcing Properties of biogeochemistry boundary forcing 5.1. Atmospheric Deposition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how atmospheric deposition is modeled End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.river_input') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "from file (climatology)" # "from file (interannual variations)" # "from Land Surface model" # TODO - please enter value(s) Explanation: 5.2. River Input Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how river input is modeled End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.sediments_from_boundary_conditions') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 5.3. Sediments From Boundary Conditions Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List which sediments are speficied from boundary condition End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.boundary_forcing.sediments_from_explicit_model') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 5.4. Sediments From Explicit Model Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 List which sediments are speficied from explicit sediment model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CO2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6. Key Properties --&gt; Gas Exchange *Properties of gas exchange in ocean biogeochemistry * 6.1. CO2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is CO2 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CO2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OMIP protocol" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 6.2. CO2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe CO2 gas exchange End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.O2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.3. O2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is O2 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.O2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OMIP protocol" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 6.4. O2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Describe O2 gas exchange End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.DMS_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.5. DMS Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is DMS gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.DMS_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.6. DMS Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify DMS gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.7. N2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is N2 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.8. N2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify N2 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2O_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.9. N2O Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is N2O gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.N2O_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.10. N2O Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify N2O gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC11_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.11. CFC11 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is CFC11 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC11_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.12. CFC11 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify CFC11 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC12_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.13. CFC12 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is CFC12 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.CFC12_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.14. CFC12 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify CFC12 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.SF6_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.15. SF6 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is SF6 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.SF6_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.16. SF6 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify SF6 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.13CO2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.17. 13CO2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is 13CO2 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.13CO2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.18. 13CO2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify 13CO2 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.14CO2_exchange_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 6.19. 14CO2 Exchange Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is 14CO2 gas exchange modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.14CO2_exchange_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.20. 14CO2 Exchange Type Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify 14CO2 gas exchange scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.gas_exchange.other_gases') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 6.21. Other Gases Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Specify any other gas exchange End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "OMIP protocol" # "Other protocol" # TODO - please enter value(s) Explanation: 7. Key Properties --&gt; Carbon Chemistry Properties of carbon chemistry biogeochemistry 7.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe how carbon chemistry is modeled End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.pH_scale') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Sea water" # "Free" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 7.2. PH Scale Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If NOT OMIP protocol, describe pH scale. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.key_properties.carbon_chemistry.constants_if_not_OMIP') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 7.3. Constants If Not OMIP Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If NOT OMIP protocol, list carbon chemistry constants. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8. Tracers Ocean biogeochemistry tracers 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of tracers in ocean biogeochemistry End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.sulfur_cycle_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 8.2. Sulfur Cycle Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is sulfur cycle modeled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.nutrients_present') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Nitrogen (N)" # "Phosphorous (P)" # "Silicium (S)" # "Iron (Fe)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 8.3. Nutrients Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List nutrient species present in ocean biogeochemistry model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.nitrous_species_if_N') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Nitrates (NO3)" # "Amonium (NH4)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 8.4. Nitrous Species If N Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If nitrogen present, list nitrous species. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.nitrous_processes_if_N') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Dentrification" # "N fixation" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 8.5. Nitrous Processes If N Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If nitrogen present, list nitrous processes. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.upper_trophic_levels_definition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9. Tracers --&gt; Ecosystem Ecosystem properties in ocean biogeochemistry 9.1. Upper Trophic Levels Definition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Definition of upper trophic level (e.g. based on size) ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.upper_trophic_levels_treatment') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9.2. Upper Trophic Levels Treatment Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Define how upper trophic level are treated End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Generic" # "PFT including size based (specify both below)" # "Size based only (specify below)" # "PFT only (specify below)" # TODO - please enter value(s) Explanation: 10. Tracers --&gt; Ecosystem --&gt; Phytoplankton Phytoplankton properties in ocean biogeochemistry 10.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of phytoplankton End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.pft') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Diatoms" # "Nfixers" # "Calcifiers" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 10.2. Pft Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Phytoplankton functional types (PFT) (if applicable) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.phytoplankton.size_classes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Microphytoplankton" # "Nanophytoplankton" # "Picophytoplankton" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 10.3. Size Classes Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Phytoplankton size classes (if applicable) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.zooplankton.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Generic" # "Size based (specify below)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 11. Tracers --&gt; Ecosystem --&gt; Zooplankton Zooplankton properties in ocean biogeochemistry 11.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of zooplankton End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.ecosystem.zooplankton.size_classes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Microzooplankton" # "Mesozooplankton" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 11.2. Size Classes Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Zooplankton size classes (if applicable) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.disolved_organic_matter.bacteria_present') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 12. Tracers --&gt; Disolved Organic Matter Disolved organic matter properties in ocean biogeochemistry 12.1. Bacteria Present Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is there bacteria representation ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.disolved_organic_matter.lability') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "None" # "Labile" # "Semi-labile" # "Refractory" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 12.2. Lability Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Describe treatment of lability in dissolved organic matter End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Diagnostic" # "Diagnostic (Martin profile)" # "Diagnostic (Balast)" # "Prognostic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13. Tracers --&gt; Particules Particulate carbon properties in ocean biogeochemistry 13.1. Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How is particulate carbon represented in ocean biogeochemistry? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.types_if_prognostic') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "POC" # "PIC (calcite)" # "PIC (aragonite" # "BSi" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13.2. Types If Prognostic Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N If prognostic, type(s) of particulate matter taken into account End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.size_if_prognostic') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "No size spectrum used" # "Full size spectrum" # "Discrete size classes (specify which below)" # TODO - please enter value(s) Explanation: 13.3. Size If Prognostic Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic, describe if a particule size spectrum is used to represent distribution of particules in water volume End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.size_if_discrete') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 13.4. Size If Discrete Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic and discrete size, describe which size classes are used End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.particules.sinking_speed_if_prognostic') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Constant" # "Function of particule size" # "Function of particule type (balast)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13.5. Sinking Speed If Prognostic Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If prognostic, method for calculation of sinking speed of particules End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.carbon_isotopes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "C13" # "C14)" # TODO - please enter value(s) Explanation: 14. Tracers --&gt; Dic Alkalinity DIC and alkalinity properties in ocean biogeochemistry 14.1. Carbon Isotopes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Which carbon isotopes are modelled (C13, C14)? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.abiotic_carbon') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 14.2. Abiotic Carbon Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is abiotic carbon modelled ? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.ocnbgchem.tracers.dic_alkalinity.alkalinity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Prognostic" # "Diagnostic)" # TODO - please enter value(s) Explanation: 14.3. Alkalinity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How is alkalinity modelled ? End of explanation
7,388
Given the following text description, write Python code to implement the functionality described below step by step Description: Simulating CSTR Here a CSTR model simulation is demoed with pure surface phase mechanism focussed on Ammonia dehydrogenation. The mechanims consists of 18 species and 7 reactions. In conventional terms, Ammonia dehydrogenation can written as 2NH3 -> N2 + 3H2 In this demo, we showcase the effect of different operating conditions on the surface coverages and molar fractions. Note Step1: Influence of temperature Evaluate the effect of temperatures of 950 K and then 900 K on the NH3 dehydrogenation Step2: Mole fractions Step3: Surface Production Rates Step4: Comparison between temperatures Step5: Effect of catalyst loading Two different catalyst loadings 1500/cm A/V and 1000/cm A/V are evaluated.
Python Code: import os import matplotlib as mpl mpl.rcParams['figure.dpi'] = 500 import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'retina' Explanation: Simulating CSTR Here a CSTR model simulation is demoed with pure surface phase mechanism focussed on Ammonia dehydrogenation. The mechanims consists of 18 species and 7 reactions. In conventional terms, Ammonia dehydrogenation can written as 2NH3 -> N2 + 3H2 In this demo, we showcase the effect of different operating conditions on the surface coverages and molar fractions. Note: The actual simulations are executed from command line. In the jupyter notebook, analysis of the resulting data is carried out. End of explanation ls T-950K/ mole_df = pd.read_csv(os.path.join('T-950K','gas_mole_tr.csv')) msdot_df = pd.read_csv(os.path.join('T-950K','gas_msdot_tr.csv')) surf_cov_df = pd.read_csv(os.path.join('T-950K','surf_cov_tr.csv')) Explanation: Influence of temperature Evaluate the effect of temperatures of 950 K and then 900 K on the NH3 dehydrogenation End of explanation ax = plt.subplot(1, 1, 1) ax.plot('t(s)', 'H2', color='r', data=mole_df, marker='^', markersize=0.5, label="$H_2$") ax.plot('t(s)', 'N2', color='g', data=mole_df, marker='v', markersize=0.5, label="$N_2$") ax.plot('t(s)', 'NH3', color='b', data=mole_df, marker='*', markersize=0.5, label="$NH_3$") ax.set_xlabel('Time (s)') ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) ax.set_ylabel('Mole Fraction') #ax.set_xlim([0,50]) # Change time limit to 1 ax.set_xlim([0,0.04]) ax.legend(loc="upper left", bbox_to_anchor=(1,1)) plt.tight_layout() plt.show() #plt.savefig('Ammonia_gas_species_molefrac.png', dpi=500) Explanation: Mole fractions End of explanation ax3 = plt.subplot(1, 1, 1) ax3.plot('t(s)', 'H2', color='r', data=msdot_df, marker='^', markersize=0.5, label="$H_2$") ax3.plot('t(s)', 'N2', color='g', data=msdot_df, marker='v', markersize=0.5, label="$N_2$") ax3.plot('t(s)', 'NH3', color='b', data=msdot_df, marker='*', markersize=0.5, label="$NH_3$") ax3.set_xlabel('Time (s)') ax3.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) ax3.set_ylabel('Surface Production Rate') #ax3.set_xlim([0,50]) ax3.set_xlim([0,0.001]) ax3.set_ylim([-1e-6,1e-6]) ax3.legend(loc="upper left", bbox_to_anchor=(1,1)) plt.tight_layout() plt.show() #plt.savefig('Ammonia_gas_species_production_rate.png', dpi=500) print(surf_cov_df.columns) ax1 = plt.subplot(1, 1, 1) ax1.plot('t(s)', 'RU(S1)', color='r', data=surf_cov_df, marker='^', markersize=0.5, label="$Ru*$") ax1.plot('t(s)', 'H(S1)', color='g', data=surf_cov_df, marker='v', markersize=0.5, label="$H*$") ax1.plot('t(s)', 'N(S1)', color='b', data=surf_cov_df, marker='*', markersize=0.5, label="$N*$") ax1.set_xlabel('Time (s)') ax1.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) ax1.set_ylabel('Surface Coverages') ax1.set_xlim([0,5]) #ax1.set_xlim([0,0.04]) ax1.legend(loc="upper left", bbox_to_anchor=(1,1)) plt.tight_layout() plt.show() #plt.savefig('Ammonia_surf_cov.png', dpi=500) Explanation: Surface Production Rates End of explanation mole_df_950 = pd.read_csv(os.path.join('T-950K','gas_mole_tr.csv')) msdot_df_950 = pd.read_csv(os.path.join('T-950K','gas_msdot_tr.csv')) surf_cov_df_950 = pd.read_csv(os.path.join('T-950K','surf_cov_tr.csv')) mole_df_900 = pd.read_csv(os.path.join('T-900K','gas_mole_tr.csv')) msdot_df_900 = pd.read_csv(os.path.join('T-900K','gas_msdot_tr.csv')) surf_cov_df_900 = pd.read_csv(os.path.join('T-900K','surf_cov_tr.csv')) ax = plt.subplot(1, 1, 1) ax.plot('t(s)', 'H2', '-', color='r', data=mole_df_950, marker='^', markersize=0.5, label="$H_2$ 950K") ax.plot('t(s)', 'H2', '--', color='r', data=mole_df_900, marker='^', markersize=0.5, label="$H_2$ 900K") ax.plot('t(s)', 'N2', '-', color='g', data=mole_df_950, marker='v', markersize=0.5, label="$N_2$ 950K") ax.plot('t(s)', 'N2', '--', color='g', data=mole_df_900, marker='v', markersize=0.5, label="$N_2$ 900K") ax.plot('t(s)', 'NH3', '-', color='b', data=mole_df_950, marker='*', markersize=0.5, label="$NH_3$ 950K") ax.plot('t(s)', 'NH3', '--', color='b', data=mole_df_900, marker='*', markersize=0.5, label="$NH_3$ 900K") ax.set_xlabel('Time (s)') ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) ax.set_ylabel('Mole Fraction') #ax.set_xlim([0,50]) # Change time limit to 1 ax.set_xlim([0,5]) ax.legend(loc="upper left", bbox_to_anchor=(1,1)) plt.tight_layout() plt.savefig('Ammonia_molefrac_Tcomp.png', dpi=500) ax = plt.subplot(1, 1, 1) ax.plot('t(s)', 'RU(S1)', '-', color='r', data=surf_cov_df_950, marker='^', markersize=0.5, label="$Ru*$ 950K") ax.plot('t(s)', 'RU(S1)', '--', color='r', data=surf_cov_df_900, marker='^', markersize=0.5, label="$Ru*$ 900K") ax.plot('t(s)', 'H(S1)', '-', color='g', data=surf_cov_df_950, marker='v', markersize=0.5, label="$H*$ 950K") ax.plot('t(s)', 'H(S1)', '--', color='g', data=surf_cov_df_900, marker='v', markersize=0.5, label="$H*$ 900K") ax.plot('t(s)', 'N(S1)', '-', color='b', data=surf_cov_df_950, marker='*', markersize=0.5, label="$N*$ 950K") ax.plot('t(s)', 'N(S1)', '--', color='b', data=surf_cov_df_900, marker='*', markersize=0.5, label="$N*$ 900K") ax.set_xlabel('Time (s)') ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) ax.set_ylabel('Surface Coverages') #ax.set_xlim([0,0.5]) ax.set_xlim([0,0.04]) ax.legend(loc="upper left", bbox_to_anchor=(1,1)) plt.tight_layout() plt.savefig('Ammonia_surf_cov_Tcomp.png', dpi=500) Explanation: Comparison between temperatures End of explanation mole_df_10 = pd.read_csv(os.path.join('AbyV-1000','gas_mole_tr.csv')) msdot_df_10 = pd.read_csv(os.path.join('AbyV-1000','gas_msdot_tr.csv')) surf_cov_df_10 = pd.read_csv(os.path.join('AbyV-1000','surf_cov_tr.csv')) mole_df_15 = pd.read_csv(os.path.join('AbyV-1500','gas_mole_tr.csv')) msdot_df_15 = pd.read_csv(os.path.join('AbyV-1500','gas_msdot_tr.csv')) surf_cov_df_15 = pd.read_csv(os.path.join('AbyV-1500','surf_cov_tr.csv')) ax = plt.subplot(1, 1, 1) ax.plot('t(s)', 'H2', '-', color='r', data=mole_df_15, marker='^', markersize=0.5, label="$H_2$ 1.5k") ax.plot('t(s)', 'H2', '--', color='r', data=mole_df_10, marker='^', markersize=0.5, label="$H_2$ 1.0K") ax.plot('t(s)', 'N2', '-', color='g', data=mole_df_15, marker='v', markersize=0.5, label="$N_2$ 1.5k") ax.plot('t(s)', 'N2', '--', color='g', data=mole_df_10, marker='v', markersize=0.5, label="$N_2$ 1.0k") ax.plot('t(s)', 'NH3', '-', color='b', data=mole_df_15, marker='*', markersize=0.5, label="$NH_3$ 1.5k") ax.plot('t(s)', 'NH3', '--', color='b', data=mole_df_10, marker='*', markersize=0.5, label="$NH_3$ 1.0k") ax.set_xlabel('Time (s)') ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) ax.set_ylabel('Mole Fraction') #ax.set_xlim([0,50]) # Change time limit to 1 ax.set_xlim([0,5]) ax.legend(loc="upper left", bbox_to_anchor=(1,1)) plt.tight_layout() plt.show() #plt.savefig('Ammonia_molefrac_catload_cmp.png', dpi=500) ax = plt.subplot(1, 1, 1) ax.plot('t(s)', 'RU(S1)', '-', color='r', data=surf_cov_df_15, marker='^', markersize=0.5, label="$Ru*$ 1.5k") ax.plot('t(s)', 'RU(S1)', '--', color='r', data=surf_cov_df_10, marker='^', markersize=0.5, label="$Ru*$ 1.0k") ax.plot('t(s)', 'H(S1)', '-', color='g', data=surf_cov_df_15, marker='v', markersize=0.5, label="$H*$ 1.5k") ax.plot('t(s)', 'H(S1)', '--', color='g', data=surf_cov_df_10, marker='v', markersize=0.5, label="$H*$ 1.0k") ax.plot('t(s)', 'N(S1)', '-', color='b', data=surf_cov_df_15, marker='*', markersize=0.5, label="$N*$ 1.5k") ax.plot('t(s)', 'N(S1)', '--', color='b', data=surf_cov_df_10, marker='*', markersize=0.5, label="$N*$ 1.0k") ax.set_xlabel('Time (s)') ax.ticklabel_format(axis='y', style='sci', scilimits=(0,0)) ax.set_ylabel('Surface Coverages') #ax.set_xlim([0,0.5]) ax.set_xlim([0,0.04]) ax.legend(loc="upper left", bbox_to_anchor=(1,1)) plt.tight_layout() plt.show() #plt.savefig('Ammonia_surf_cov_catload-comp.png', dpi=500) Explanation: Effect of catalyst loading Two different catalyst loadings 1500/cm A/V and 1000/cm A/V are evaluated. End of explanation
7,389
Given the following text description, write Python code to implement the functionality described below step by step Description: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Tuning-Spark-Partitions" data-toc-modified-id="Tuning-Spark-Partitions-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Tuning Spark Partitions</a></span><ul class="toc-item"><li><span><a href="#Custom-Partitions---PartitionBy" data-toc-modified-id="Custom-Partitions---PartitionBy-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Custom Partitions - PartitionBy</a></span></li><li><span><a href="#Working-With-DataFrames" data-toc-modified-id="Working-With-DataFrames-1.2"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Working With DataFrames</a></span><ul class="toc-item"><li><span><a href="#coalesce-vs-repartition" data-toc-modified-id="coalesce-vs-repartition-1.2.1"><span class="toc-item-num">1.2.1&nbsp;&nbsp;</span>coalesce vs repartition</a></span></li></ul></li><li><span><a href="#Best-Practices" data-toc-modified-id="Best-Practices-1.3"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>Best Practices</a></span></li></ul></li><li><span><a href="#Reference" data-toc-modified-id="Reference-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Reference</a></span></li></ul></div> Step1: Tuning Spark Partitions The main reason why we should care about partitions is performance. By having all relevant data in one place (node) we reduce the overhead of shuffling (need for serialization and network traffic). Understanding how Spark deals with partitions allow us to control the application parallelism (which leads to better cluster utilization - fewer costs). But keep in mind that partitioning will not be helpful in all applications. For example, if a given RDD is scanned only once, there is no point in partitioning it in advance. It's useful only when a dataset is reused multiple times and performing operations that involves a shuffle, e.g. reduceByKey(). We will use the following list of numbers to investigate the behavior of spark's partitioning. Step2: Let's look at what is happening under the hood. Spark uses different partitioning schemes for various types of RDD, in our case, our partitioner is None, If there is no partitioner, then the partitioning is not based upon characteristic of data but uniformly distributed across nodes. Looking at the partition structure, we can see that our RDD is in fact split into two partitions, and if we were to apply transformations on this RDD, then each partition's work will be executed in a separate thread. If you're confused about the glom method, it returns a RDD created by coalescing all elements within each partition into a list/array. An example usage of this method might be, say we wish to get the maximum value of a RDD, we could do Step3: As reduce introduces lot of shuffles between partitions for comparison, we could instead Step4: The next question is Step5: From the output above, we can see that Spark created the requested number of partitions, but some of them are empty. This is bad because we would need to spend time preparing these idle threads. Custom Partitions - PartitionBy partitionBy() transformation gives the end-user the flexibility to apply custom partitioning logic over the RDD. To use partitionBy(), our RDD must be comprised of tuple (pair) objects. And again, it's highly advised to persist it for more optimal later usage. Let's get into a more realistic example. Imagine that our data consist of various dummy transactions made across different countries. Step6: Say we know that our downstream analysis required analyzing records within the same country. To optimize network traffic it seems to be a good idea to put records from one country onto the same node/partition. Step7: It worked as expected, all records from the same country is within the same partition. We can perform some downstream work on them without worrying about large network shuffling. One caveat about this approach is that we should pay attention for potential data skews. Meaning if some keys are overrepresented in the dataset it can result in suboptimal resource usage and potential failure (e.g. in our case, say United Kingdom had a lot more data than Poland). After partitioning the data, the next common transformation is to use a mapPartitions(), which operates on each partition of the RDD. Working With DataFrames Nowadays we are all advised use structured DataFrames from Spark SQL module as oppose to RDDs as much as possible. When we are calling a DataFrame transformation, it actually becomes a set of RDD transformation underneath the hood. The main advantage is that when using the DataFrame API, spark understands the inner structure of our records much better and is capable of performing internal optimization to increase the processing speed. Step8: coalesce vs repartition The coalesce() and repartition() transformations are both used for changing the number of partitions in the RDD. The main difference is that
Python Code: # code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', 'notebook_format')) from formats import load_style load_style(plot_style=False) os.chdir(path) # 1. magic to print version # 2. magic so that the notebook will reload external python modules %load_ext watermark %load_ext autoreload %autoreload 2 from pyspark.conf import SparkConf from pyspark.sql import SparkSession, Row %watermark -a 'Ethen' -d -t -v -p pyspark spark = (SparkSession. builder. master('local[*]'). appName('implicit'). config(conf = SparkConf()). getOrCreate()) spark Explanation: <h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Tuning-Spark-Partitions" data-toc-modified-id="Tuning-Spark-Partitions-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Tuning Spark Partitions</a></span><ul class="toc-item"><li><span><a href="#Custom-Partitions---PartitionBy" data-toc-modified-id="Custom-Partitions---PartitionBy-1.1"><span class="toc-item-num">1.1&nbsp;&nbsp;</span>Custom Partitions - PartitionBy</a></span></li><li><span><a href="#Working-With-DataFrames" data-toc-modified-id="Working-With-DataFrames-1.2"><span class="toc-item-num">1.2&nbsp;&nbsp;</span>Working With DataFrames</a></span><ul class="toc-item"><li><span><a href="#coalesce-vs-repartition" data-toc-modified-id="coalesce-vs-repartition-1.2.1"><span class="toc-item-num">1.2.1&nbsp;&nbsp;</span>coalesce vs repartition</a></span></li></ul></li><li><span><a href="#Best-Practices" data-toc-modified-id="Best-Practices-1.3"><span class="toc-item-num">1.3&nbsp;&nbsp;</span>Best Practices</a></span></li></ul></li><li><span><a href="#Reference" data-toc-modified-id="Reference-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Reference</a></span></li></ul></div> End of explanation num_partitions = 2 rdd = spark.sparkContext.parallelize(range(10), num_partitions) print('Number of partitions: {}'.format(rdd.getNumPartitions())) print('Partitioner: {}'.format(rdd.partitioner)) print('Partitions structure: {}'.format(rdd.glom().collect())) Explanation: Tuning Spark Partitions The main reason why we should care about partitions is performance. By having all relevant data in one place (node) we reduce the overhead of shuffling (need for serialization and network traffic). Understanding how Spark deals with partitions allow us to control the application parallelism (which leads to better cluster utilization - fewer costs). But keep in mind that partitioning will not be helpful in all applications. For example, if a given RDD is scanned only once, there is no point in partitioning it in advance. It's useful only when a dataset is reused multiple times and performing operations that involves a shuffle, e.g. reduceByKey(). We will use the following list of numbers to investigate the behavior of spark's partitioning. End of explanation # or in Scala: rdd.reduce(_ max _) rdd.reduce(max) Explanation: Let's look at what is happening under the hood. Spark uses different partitioning schemes for various types of RDD, in our case, our partitioner is None, If there is no partitioner, then the partitioning is not based upon characteristic of data but uniformly distributed across nodes. Looking at the partition structure, we can see that our RDD is in fact split into two partitions, and if we were to apply transformations on this RDD, then each partition's work will be executed in a separate thread. If you're confused about the glom method, it returns a RDD created by coalescing all elements within each partition into a list/array. An example usage of this method might be, say we wish to get the maximum value of a RDD, we could do: End of explanation rdd.glom().map(lambda partition: max(partition)).reduce(max) Explanation: As reduce introduces lot of shuffles between partitions for comparison, we could instead: Find the maximum in each partition Compare maximum value between partitions to get the final max value. End of explanation num_partitions = 15 rdd = spark.sparkContext.parallelize(range(10), num_partitions) print('Number of partitions: {}'.format(rdd.getNumPartitions())) print('Partitioner: {}'.format(rdd.partitioner)) print('Partitions structure: {}'.format(rdd.glom().collect())) Explanation: The next question is: What will happen when the number of partitions exceeds the number of data records? End of explanation transactions = [ {'name': 'Bob', 'amount': 100, 'country': 'United Kingdom'}, {'name': 'James', 'amount': 15, 'country': 'United Kingdom'}, {'name': 'Marek', 'amount': 51, 'country': 'Poland'}, {'name': 'Paul', 'amount': 75, 'country': 'Poland'} ] Explanation: From the output above, we can see that Spark created the requested number of partitions, but some of them are empty. This is bad because we would need to spend time preparing these idle threads. Custom Partitions - PartitionBy partitionBy() transformation gives the end-user the flexibility to apply custom partitioning logic over the RDD. To use partitionBy(), our RDD must be comprised of tuple (pair) objects. And again, it's highly advised to persist it for more optimal later usage. Let's get into a more realistic example. Imagine that our data consist of various dummy transactions made across different countries. End of explanation def country_partitioner(country): return hash(country) # note that we technically don't need to pass in the custom # partitioner when using partitionBy, if we don't then spark # will use its own hash partitioner to carry out the partitioning rdd = (spark.sparkContext. parallelize(transactions). map(lambda record: (record['country'], record)). partitionBy(2, country_partitioner)) print("Number of partitions: {}".format(rdd.getNumPartitions())) print("Partitioner: {}".format(rdd.partitioner)) print("Partitions structure: {}".format(rdd.glom().collect())) Explanation: Say we know that our downstream analysis required analyzing records within the same country. To optimize network traffic it seems to be a good idea to put records from one country onto the same node/partition. End of explanation spark = (SparkSession. builder. master('local[*]'). config('spark.sql.shuffle.partitions', 2). getOrCreate()) # create a spark DataFrame from the dictionary rdd = (spark.sparkContext. parallelize(transactions, 2). map(lambda x: Row(**x))) # here, we are essentially creating a custom partitioner, # by specifying we are going to repartition using the 'country' column. # We can think of this operation as performing an indexing on the 'country' # column from a relational database standpoint. # When not specifying number of partitions, spark will use the value from the # config parameter 'spark.sql.shuffle.partitions', in this example, we # explicitly set it to 2, if we didn't specify this value, the default would # be 200. df = spark.createDataFrame(rdd).repartition(2, 'country') print('Number of partitions: {}'.format(df.rdd.getNumPartitions())) print('Partitioner: {}'.format(rdd.partitioner)) print('Partitions structure: {}'.format(df.rdd.glom().collect())) Explanation: It worked as expected, all records from the same country is within the same partition. We can perform some downstream work on them without worrying about large network shuffling. One caveat about this approach is that we should pay attention for potential data skews. Meaning if some keys are overrepresented in the dataset it can result in suboptimal resource usage and potential failure (e.g. in our case, say United Kingdom had a lot more data than Poland). After partitioning the data, the next common transformation is to use a mapPartitions(), which operates on each partition of the RDD. Working With DataFrames Nowadays we are all advised use structured DataFrames from Spark SQL module as oppose to RDDs as much as possible. When we are calling a DataFrame transformation, it actually becomes a set of RDD transformation underneath the hood. The main advantage is that when using the DataFrame API, spark understands the inner structure of our records much better and is capable of performing internal optimization to increase the processing speed. End of explanation # the coalesce algorithm merged the data from 1 partition to another # Partition to Partition A, thus it can't be used to increase the partition df_coalesce = df.coalesce(1) print('Number of partitions: {}'.format(df_coalesce.rdd.getNumPartitions())) print('Partitions structure: {}'.format(df_coalesce.rdd.glom().collect())) df_repartition = df.repartition(4) print('Number of partitions: {}'.format(df_repartition.rdd.getNumPartitions())) print('Partitions structure: {}'.format(df_repartition.rdd.glom().collect())) Explanation: coalesce vs repartition The coalesce() and repartition() transformations are both used for changing the number of partitions in the RDD. The main difference is that: If we are increasing the number of partitions use repartition(), this will perform a full shuffle. If we are decreasing the number of partitions use coalesce(), this operation ensures that we minimize shuffles. End of explanation
7,390
Given the following text description, write Python code to implement the functionality described below step by step Description: <img align="left" src="imgs/logo.jpg" width="50px" style="margin-right Step1: Loading the Corpus Next, we load and pre-process the corpus of documents. Configuring a DocPreprocessor We'll start by defining a TSVDocPreprocessor class to read in the documents, which are stored in a tab-seperated value format as pairs of document names and text. Step2: Running a CorpusParser We'll use Spacy, an NLP preprocessing tool, to split our documents into sentences and tokens, and provide named entity annotations. Step3: We can then use simple database queries (written in the syntax of SQLAlchemy, which Snorkel uses) to check how many documents and sentences were parsed Step4: Generating Candidates The next step is to extract candidates from our corpus. A Candidate in Snorkel is an object for which we want to make a prediction. In this case, the candidates are pairs of people mentioned in sentences, and our task is to predict which pairs are described as married in the associated text. Defining a Candidate schema We now define the schema of the relation mention we want to extract (which is also the schema of the candidates). This must be a subclass of Candidate, and we define it using a helper function. Here we'll define a binary spouse relation mention which connects two Span objects of text. Note that this function will create the table in the database backend if it does not exist Step5: Writing a basic CandidateExtractor Next, we'll write a basic function to extract candidate spouse relation mentions from the corpus. The Spacy parser we used performs named entity recognition for us. We will extract Candidate objects of the Spouse type by identifying, for each Sentence, all pairs of ngrams (up to trigrams) that were tagged as people. We do this with three objects Step6: Next, we'll split up the documents into train, development, and test splits; and collect the associated sentences. Note that we'll filter out a few sentences that mention more than five people. These lists are unlikely to contain spouses. Step7: Finally, we'll apply the candidate extractor to the three sets of sentences. The results will be persisted in the database backend. Step8: Loading Gold Labels Finally, we'll load gold labels for development and evaluation. Even though Snorkel is designed to create labels for data, we still use gold labels to evaluate the quality of our models. Fortunately, we need far less labeled data to evaluate a model than to train it.
Python Code: %load_ext autoreload %autoreload 2 %matplotlib inline import os # Connect to the database backend and initalize a Snorkel session from lib.init import * # Here, we just set how many documents we'll process for automatic testing- you can safely ignore this! n_docs = 1000 if 'CI' in os.environ else 2591 Explanation: <img align="left" src="imgs/logo.jpg" width="50px" style="margin-right:10px"> Snorkel Workshop: Extracting Spouse Relations <br> from the News Part 5: Preprocessing & Building the Snorkel Database In this tutorial, we will walk through the process of using Snorkel to identify mentions of spouses in a corpus of news articles. Part I: Preprocessing In this notebook, we preprocess several documents using Snorkel utilities, parsing them into a simple hierarchy of component parts of our input data, which we refer to as contexts. We'll also create candidates out of these contexts, which are the objects we want to classify, in this case, possible mentions of spouses. Finally, we'll load some gold labels for evaluation. All of this preprocessed input data is saved to a database. (Connection strings can be specified by setting the SNORKELDB environment variable. In Snorkel, if no database is specified, then a SQLite database at ./snorkel.db is created by default--so no setup is needed here! Initializing a SnorkelSession First, we initialize a SnorkelSession, which manages a connection to a database automatically for us, and will enable us to save intermediate results. If we don't specify any particular database (see commented-out code below), then it will automatically create a SQLite database in the background for us: End of explanation from snorkel.parser import TSVDocPreprocessor doc_preprocessor = TSVDocPreprocessor('data/articles.tsv', max_docs=n_docs) Explanation: Loading the Corpus Next, we load and pre-process the corpus of documents. Configuring a DocPreprocessor We'll start by defining a TSVDocPreprocessor class to read in the documents, which are stored in a tab-seperated value format as pairs of document names and text. End of explanation from snorkel.parser.spacy_parser import Spacy from snorkel.parser import CorpusParser corpus_parser = CorpusParser(parser=Spacy()) %time corpus_parser.apply(doc_preprocessor, count=n_docs, parallelism=1) Explanation: Running a CorpusParser We'll use Spacy, an NLP preprocessing tool, to split our documents into sentences and tokens, and provide named entity annotations. End of explanation from snorkel.models import Document, Sentence print("Documents:", session.query(Document).count()) print("Sentences:", session.query(Sentence).count()) Explanation: We can then use simple database queries (written in the syntax of SQLAlchemy, which Snorkel uses) to check how many documents and sentences were parsed: End of explanation from snorkel.models import candidate_subclass Spouse = candidate_subclass('Spouse', ['person1', 'person2']) Explanation: Generating Candidates The next step is to extract candidates from our corpus. A Candidate in Snorkel is an object for which we want to make a prediction. In this case, the candidates are pairs of people mentioned in sentences, and our task is to predict which pairs are described as married in the associated text. Defining a Candidate schema We now define the schema of the relation mention we want to extract (which is also the schema of the candidates). This must be a subclass of Candidate, and we define it using a helper function. Here we'll define a binary spouse relation mention which connects two Span objects of text. Note that this function will create the table in the database backend if it does not exist: End of explanation from snorkel.candidates import Ngrams, CandidateExtractor from snorkel.matchers import PersonMatcher ngrams = Ngrams(n_max=7) person_matcher = PersonMatcher(longest_match_only=True) cand_extractor = CandidateExtractor(Spouse, [ngrams, ngrams], [person_matcher, person_matcher], symmetric_relations=False) Explanation: Writing a basic CandidateExtractor Next, we'll write a basic function to extract candidate spouse relation mentions from the corpus. The Spacy parser we used performs named entity recognition for us. We will extract Candidate objects of the Spouse type by identifying, for each Sentence, all pairs of ngrams (up to trigrams) that were tagged as people. We do this with three objects: A ContextSpace defines the "space" of all candidates we even potentially consider; in this case we use the Ngrams subclass, and look for all n-grams up to 3 words long A Matcher heuristically filters the candidates we use. In this case, we just use a pre-defined matcher which looks for all n-grams tagged by CoreNLP as "PERSON" A CandidateExtractor combines this all together! End of explanation from snorkel.models import Document from lib.util import number_of_people docs = session.query(Document).order_by(Document.name).all() train_sents = set() dev_sents = set() test_sents = set() for i, doc in enumerate(docs): for s in doc.sentences: if number_of_people(s) <= 5: if i % 10 == 8: dev_sents.add(s) elif i % 10 == 9: test_sents.add(s) else: train_sents.add(s) Explanation: Next, we'll split up the documents into train, development, and test splits; and collect the associated sentences. Note that we'll filter out a few sentences that mention more than five people. These lists are unlikely to contain spouses. End of explanation %%time for i, sents in enumerate([train_sents, dev_sents, test_sents]): cand_extractor.apply(sents, split=i, parallelism=1) print("Number of candidates:", session.query(Spouse).filter(Spouse.split == i).count()) Explanation: Finally, we'll apply the candidate extractor to the three sets of sentences. The results will be persisted in the database backend. End of explanation from lib.util import load_external_labels %time load_external_labels(session, Spouse, annotator_name='gold') Explanation: Loading Gold Labels Finally, we'll load gold labels for development and evaluation. Even though Snorkel is designed to create labels for data, we still use gold labels to evaluate the quality of our models. Fortunately, we need far less labeled data to evaluate a model than to train it. End of explanation
7,391
Given the following text description, write Python code to implement the functionality described below step by step Description: healpy tutorial See the Jupyter Notebook version of this tutorial at https Step1: NSIDE and ordering Maps are simply numpy arrays, where each array element refers to a location in the sky as defined by the Healpix pixelization schemes (see the healpix website). Note Step2: The function healpy.pixelfunc.nside2npix gives the number of pixels NPIX of the map Step3: The same pixels in the map can be ordered in 2 ways, either RING, where they are numbered in the array in horizontal rings starting from the North pole Step4: The standard coordinates are the colatitude $\theta$, $0$ at the North Pole, $\pi/2$ at the equator and $\pi$ at the South Pole and the longitude $\phi$ between $0$ and $2\pi$ eastward, in a Mollview projection, $\phi=0$ is at the center and increases eastward toward the left of the map. We can also use vectors to represent coordinates, for example vec is the normalized vector that points to $\theta=\pi/2, \phi=3/4\pi$ Step5: We can find the indices of all the pixels within $10$ degrees of that point and then change the value of the map at those indices Step6: We can retrieve colatitude and longitude of each pixel using pix2ang, in this case we notice that the first 4 pixels cover the North Pole with pixel centers just ~$1.5$ degrees South of the Pole all at the same latitude. The fifth pixel is already part of another ring of pixels. Step7: The RING ordering is necessary for the Spherical Harmonics transforms, the other option is NESTED ordering which is very efficient for map domain operations because scaling up and down maps is achieved just multiplying and rounding pixel indices. See below how pixel are ordered in the NESTED scheme, notice the structure of the 12 HEALPix base pixels (NSIDE 1) Step8: All healpy routines assume RING ordering, in fact as soon as you read a map with read_map, even if it was stored as NESTED, it is transformed to RING. However, you can work in NESTED ordering passing the nest=True argument to most healpy routines. Reading and writing maps to file For the following section, it is required to download larger maps by executing from the terminal the bash script healpy_get_wmap_maps.sh which should be available in your path. This will download the higher resolution WMAP data into the current directory. Step9: By default, input maps are converted to RING ordering, if they are in NESTED ordering. You can otherwise specify nest=True to retrieve a map is NESTED ordering, or nest=None to keep the ordering unchanged. By default, read_map loads the first column, for reading other columns you can specify the field keyword. write_map writes a map to disk in FITS format, if the input map is a list of 3 maps, they are written to a single file as I,Q,U polarization components Step10: Visualization As shown above, mollweide projection with mollview is the most common visualization tool for HEALPIX maps. It also supports coordinate transformation, coord does Galactic to ecliptic coordinate transformation, norm='hist' sets a histogram equalized color scale and xsize increases the size of the image. graticule adds meridians and parallels. Step11: gnomview instead provides gnomonic projection around a position specified by rot, for example you can plot a projection of the galactic center, xsize and ysize change the dimension of the sky patch. Step12: mollzoom is a powerful tool for interactive inspection of a map, it provides a mollweide projection where you can click to set the center of the adjacent gnomview panel. Masked map, partial maps By convention, HEALPIX uses $-1.6375 * 10^{30}$ to mark invalid or unseen pixels. This is stored in healpy as the constant UNSEEN. All healpy functions automatically deal with maps with UNSEEN pixels, for example mollview marks in grey those sections of a map. There is an alternative way of dealing with UNSEEN pixel based on the numpyMaskedArray class, hp.ma loads a map as a masked array, by convention the mask is 0 where the data are masked, while numpy defines data masked when the mask is True, so it is necessary to flip the mask. Step13: Filling a masked array fills in the UNSEEN value and return a standard array that can be used by mollview. compressed() instead removes all the masked pixels and returns a standard array that can be used for examples by the matplotlib hist() function Step14: Spherical Harmonics transforms healpy provides bindings to the C++ HEALPIX library for performing spherical harmonic transforms. hp.anafast computes the angular power spectrum of a map Step15: therefore we can plot a normalized CMB spectrum and write it to disk Step16: Gaussian beam map smoothing is provided by hp.smoothing
Python Code: import matplotlib.pyplot as plt %matplotlib inline import numpy as np import healpy as hp Explanation: healpy tutorial See the Jupyter Notebook version of this tutorial at https://github.com/healpy/healpy/blob/master/doc/healpy_tutorial.ipynb See a executed version of the notebook with embedded plots at https://gist.github.com/zonca/9c114608e0903a3b8ea0bfe41c96f255 Choose the inline backend of maptlotlib to display the plots inside the Jupyter Notebook End of explanation NSIDE = 32 print( "Approximate resolution at NSIDE {} is {:.2} deg".format( NSIDE, hp.nside2resol(NSIDE, arcmin=True) / 60 ) ) Explanation: NSIDE and ordering Maps are simply numpy arrays, where each array element refers to a location in the sky as defined by the Healpix pixelization schemes (see the healpix website). Note: Running the code below in a regular Python session will not display the maps; it's recommended to use an IPython shell or a Jupyter notebook. The resolution of the map is defined by the NSIDE parameter, which is generally a power of 2. End of explanation NPIX = hp.nside2npix(NSIDE) print(NPIX) Explanation: The function healpy.pixelfunc.nside2npix gives the number of pixels NPIX of the map: End of explanation m = np.arange(NPIX) hp.mollview(m, title="Mollview image RING") hp.graticule() Explanation: The same pixels in the map can be ordered in 2 ways, either RING, where they are numbered in the array in horizontal rings starting from the North pole: End of explanation vec = hp.ang2vec(np.pi / 2, np.pi * 3 / 4) print(vec) Explanation: The standard coordinates are the colatitude $\theta$, $0$ at the North Pole, $\pi/2$ at the equator and $\pi$ at the South Pole and the longitude $\phi$ between $0$ and $2\pi$ eastward, in a Mollview projection, $\phi=0$ is at the center and increases eastward toward the left of the map. We can also use vectors to represent coordinates, for example vec is the normalized vector that points to $\theta=\pi/2, \phi=3/4\pi$: End of explanation ipix_disc = hp.query_disc(nside=32, vec=vec, radius=np.radians(10)) m = np.arange(NPIX) m[ipix_disc] = m.max() hp.mollview(m, title="Mollview image RING") Explanation: We can find the indices of all the pixels within $10$ degrees of that point and then change the value of the map at those indices: End of explanation theta, phi = np.degrees(hp.pix2ang(nside=32, ipix=[0, 1, 2, 3, 4])) theta phi Explanation: We can retrieve colatitude and longitude of each pixel using pix2ang, in this case we notice that the first 4 pixels cover the North Pole with pixel centers just ~$1.5$ degrees South of the Pole all at the same latitude. The fifth pixel is already part of another ring of pixels. End of explanation m = np.arange(NPIX) hp.mollview(m, nest=True, title="Mollview image NESTED") Explanation: The RING ordering is necessary for the Spherical Harmonics transforms, the other option is NESTED ordering which is very efficient for map domain operations because scaling up and down maps is achieved just multiplying and rounding pixel indices. See below how pixel are ordered in the NESTED scheme, notice the structure of the 12 HEALPix base pixels (NSIDE 1): End of explanation !healpy_get_wmap_maps.sh wmap_map_I = hp.read_map("wmap_band_iqumap_r9_7yr_W_v4.fits") Explanation: All healpy routines assume RING ordering, in fact as soon as you read a map with read_map, even if it was stored as NESTED, it is transformed to RING. However, you can work in NESTED ordering passing the nest=True argument to most healpy routines. Reading and writing maps to file For the following section, it is required to download larger maps by executing from the terminal the bash script healpy_get_wmap_maps.sh which should be available in your path. This will download the higher resolution WMAP data into the current directory. End of explanation hp.write_map("my_map.fits", wmap_map_I, overwrite=True) Explanation: By default, input maps are converted to RING ordering, if they are in NESTED ordering. You can otherwise specify nest=True to retrieve a map is NESTED ordering, or nest=None to keep the ordering unchanged. By default, read_map loads the first column, for reading other columns you can specify the field keyword. write_map writes a map to disk in FITS format, if the input map is a list of 3 maps, they are written to a single file as I,Q,U polarization components: End of explanation hp.mollview( wmap_map_I, coord=["G", "E"], title="Histogram equalized Ecliptic", unit="mK", norm="hist", min=-1, max=1, ) hp.graticule() Explanation: Visualization As shown above, mollweide projection with mollview is the most common visualization tool for HEALPIX maps. It also supports coordinate transformation, coord does Galactic to ecliptic coordinate transformation, norm='hist' sets a histogram equalized color scale and xsize increases the size of the image. graticule adds meridians and parallels. End of explanation hp.gnomview(wmap_map_I, rot=[0, 0.3], title="GnomView", unit="mK", format="%.2g") Explanation: gnomview instead provides gnomonic projection around a position specified by rot, for example you can plot a projection of the galactic center, xsize and ysize change the dimension of the sky patch. End of explanation mask = hp.read_map("wmap_temperature_analysis_mask_r9_7yr_v4.fits").astype(np.bool) wmap_map_I_masked = hp.ma(wmap_map_I) wmap_map_I_masked.mask = np.logical_not(mask) Explanation: mollzoom is a powerful tool for interactive inspection of a map, it provides a mollweide projection where you can click to set the center of the adjacent gnomview panel. Masked map, partial maps By convention, HEALPIX uses $-1.6375 * 10^{30}$ to mark invalid or unseen pixels. This is stored in healpy as the constant UNSEEN. All healpy functions automatically deal with maps with UNSEEN pixels, for example mollview marks in grey those sections of a map. There is an alternative way of dealing with UNSEEN pixel based on the numpyMaskedArray class, hp.ma loads a map as a masked array, by convention the mask is 0 where the data are masked, while numpy defines data masked when the mask is True, so it is necessary to flip the mask. End of explanation hp.mollview(wmap_map_I_masked.filled()) plt.hist(wmap_map_I_masked.compressed(), bins=1000); Explanation: Filling a masked array fills in the UNSEEN value and return a standard array that can be used by mollview. compressed() instead removes all the masked pixels and returns a standard array that can be used for examples by the matplotlib hist() function: End of explanation LMAX = 1024 cl = hp.anafast(wmap_map_I_masked.filled(), lmax=LMAX) ell = np.arange(len(cl)) Explanation: Spherical Harmonics transforms healpy provides bindings to the C++ HEALPIX library for performing spherical harmonic transforms. hp.anafast computes the angular power spectrum of a map: End of explanation plt.figure(figsize=(10, 5)) plt.plot(ell, ell * (ell + 1) * cl) plt.xlabel("$\ell$") plt.ylabel("$\ell(\ell+1)C_{\ell}$") plt.grid() hp.write_cl("cl.fits", cl, overwrite=True) Explanation: therefore we can plot a normalized CMB spectrum and write it to disk: End of explanation wmap_map_I_smoothed = hp.smoothing(wmap_map_I, fwhm=np.radians(1.)) hp.mollview(wmap_map_I_smoothed, min=-1, max=1, title="Map smoothed 1 deg") Explanation: Gaussian beam map smoothing is provided by hp.smoothing: End of explanation
7,392
Given the following text description, write Python code to implement the functionality described below step by step Description: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with Numpy, we'll be using TFLearn, a high-level library built on top of TensorFlow. TFLearn makes it simpler to build networks just by defining the layers. It takes care of most of the details for you. We'll start off by importing all the modules we'll need, then load and prepare the data. Step1: Preparing the data Following along with Andrew, our goal here is to convert our reviews into word vectors. The word vectors will have elements representing words in the total vocabulary. If the second position represents the word 'the', for each review we'll count up the number of times 'the' appears in the text and set the second position to that count. I'll show you examples as we build the input data from the reviews data. Check out Andrew's notebook and video for more about this. Read the data Use the pandas library to read the reviews and postive/negative labels from comma-separated files. The data we're using has already been preprocessed a bit and we know it uses only lower case characters. If we were working from raw data, where we didn't know it was all lower case, we would want to add a step here to convert it. That's so we treat different variations of the same word, like The, the, and THE, all the same way. Step2: Counting word frequency To start off we'll need to count how often each word appears in the data. We'll use this count to create a vocabulary we'll use to encode the review data. This resulting count is known as a bag of words. We'll use it to select our vocabulary and build the word vectors. You should have seen how to do this in Andrew's lesson. Try to implement it here using the Counter class. Exercise Step3: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in the vocabulary are rarely used so they will have little effect on our predictions. Below, we'll sort vocab by the count value and keep the 10000 most frequent words. Step4: What's the last word in our vocabulary? We can use this to judge if 10000 is too few. If the last word is pretty common, we probably need to keep more words. Step5: The last word in our vocabulary shows up in 30 reviews out of 25000. I think it's fair to say this is a tiny proportion of reviews. We are probably fine with this number of words. Note Step7: Text to vector function Now we can write a function that converts a some text to a word vector. The function will take a string of words as input and return a vector with the words counted up. Here's the general algorithm to do this Step8: If you do this right, the following code should return ``` text_to_vector('The tea is for a party to celebrate ' 'the movie so she has no time for a cake')[ Step9: Now, run through our entire review data set and convert each review to a word vector. Step10: Train, Validation, Test sets Now that we have the word_vectors, we're ready to split our data into train, validation, and test sets. Remember that we train on the train data, use the validation data to set the hyperparameters, and at the very end measure the network performance on the test data. Here we're using the function to_categorical from TFLearn to reshape the target data so that we'll have two output units and can classify with a softmax activation function. We actually won't be creating the validation set here, TFLearn will do that for us later. Step11: Building the network TFLearn lets you build the network by defining the layers. Input layer For the input layer, you just need to tell it how many units you have. For example, net = tflearn.input_data([None, 100]) would create a network with 100 input units. The first element in the list, None in this case, sets the batch size. Setting it to None here leaves it at the default batch size. The number of inputs to your network needs to match the size of your data. For this example, we're using 10000 element long vectors to encode our input data, so we need 10000 input units. Adding layers To add new hidden layers, you use net = tflearn.fully_connected(net, n_units, activation='ReLU') This adds a fully connected layer where every unit in the previous layer is connected to every unit in this layer. The first argument net is the network you created in the tflearn.input_data call. It's telling the network to use the output of the previous layer as the input to this layer. You can set the number of units in the layer with n_units, and set the activation function with the activation keyword. You can keep adding layers to your network by repeated calling net = tflearn.fully_connected(net, n_units). Output layer The last layer you add is used as the output layer. Therefore, you need to set the number of units to match the target data. In this case we are predicting two classes, positive or negative sentiment. You also need to set the activation function so it's appropriate for your model. Again, we're trying to predict if some input data belongs to one of two classes, so we should use softmax. net = tflearn.fully_connected(net, 2, activation='softmax') Training To set how you train the network, use net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy') Again, this is passing in the network you've been building. The keywords Step12: Intializing the model Next we need to call the build_model() function to actually build the model. In my solution I haven't included any arguments to the function, but you can add arguments so you can change parameters in the model if you want. Note Step13: Training the network Now that we've constructed the network, saved as the variable model, we can fit it to the data. Here we use the model.fit method. You pass in the training features trainX and the training targets trainY. Below I set validation_set=0.1 which reserves 10% of the data set as the validation set. You can also set the batch size and number of epochs with the batch_size and n_epoch keywords, respectively. Below is the code to fit our the network to our word vectors. You can rerun model.fit to train the network further if you think you can increase the validation accuracy. Remember, all hyperparameter adjustments must be done using the validation set. Only use the test set after you're completely done training the network. Step14: Testing After you're satisified with your hyperparameters, you can run the network on the test set to measure its performance. Remember, only do this after finalizing the hyperparameters. Step15: Try out your own text!
Python Code: import pandas as pd import numpy as np import tensorflow as tf import tflearn from tflearn.data_utils import to_categorical Explanation: Sentiment analysis with TFLearn In this notebook, we'll continue Andrew Trask's work by building a network for sentiment analysis on the movie review data. Instead of a network written with Numpy, we'll be using TFLearn, a high-level library built on top of TensorFlow. TFLearn makes it simpler to build networks just by defining the layers. It takes care of most of the details for you. We'll start off by importing all the modules we'll need, then load and prepare the data. End of explanation reviews = pd.read_csv('reviews.txt', header=None) labels = pd.read_csv('labels.txt', header=None) Explanation: Preparing the data Following along with Andrew, our goal here is to convert our reviews into word vectors. The word vectors will have elements representing words in the total vocabulary. If the second position represents the word 'the', for each review we'll count up the number of times 'the' appears in the text and set the second position to that count. I'll show you examples as we build the input data from the reviews data. Check out Andrew's notebook and video for more about this. Read the data Use the pandas library to read the reviews and postive/negative labels from comma-separated files. The data we're using has already been preprocessed a bit and we know it uses only lower case characters. If we were working from raw data, where we didn't know it was all lower case, we would want to add a step here to convert it. That's so we treat different variations of the same word, like The, the, and THE, all the same way. End of explanation from collections import Counter total_counts = Counter() for idx, review in reviews.to_records(): for word in review.split(' '): total_counts[word] += 1 print("Total words in data set: ", len(total_counts)) Explanation: Counting word frequency To start off we'll need to count how often each word appears in the data. We'll use this count to create a vocabulary we'll use to encode the review data. This resulting count is known as a bag of words. We'll use it to select our vocabulary and build the word vectors. You should have seen how to do this in Andrew's lesson. Try to implement it here using the Counter class. Exercise: Create the bag of words from the reviews data and assign it to total_counts. The reviews are stores in the reviews Pandas DataFrame. If you want the reviews as a Numpy array, use reviews.values. You can iterate through the rows in the DataFrame with for idx, row in reviews.iterrows(): (documentation). When you break up the reviews into words, use .split(' ') instead of .split() so your results match ours. End of explanation vocab = total_counts.most_common()[:10000] print(vocab[:60]) Explanation: Let's keep the first 10000 most frequent words. As Andrew noted, most of the words in the vocabulary are rarely used so they will have little effect on our predictions. Below, we'll sort vocab by the count value and keep the 10000 most frequent words. End of explanation print(vocab[-1]) Explanation: What's the last word in our vocabulary? We can use this to judge if 10000 is too few. If the last word is pretty common, we probably need to keep more words. End of explanation word2idx = {word: i for i, (word, freq) in enumerate(vocab)} Explanation: The last word in our vocabulary shows up in 30 reviews out of 25000. I think it's fair to say this is a tiny proportion of reviews. We are probably fine with this number of words. Note: When you run, you may see a different word from the one shown above, but it will also have the value 30. That's because there are many words tied for that number of counts, and the Counter class does not guarantee which one will be returned in the case of a tie. Now for each review in the data, we'll make a word vector. First we need to make a mapping of word to index, pretty easy to do with a dictionary comprehension. Exercise: Create a dictionary called word2idx that maps each word in the vocabulary to an index. The first word in vocab has index 0, the second word has index 1, and so on. End of explanation def text_to_vector(text): Converts text to feature vector based on the vocabulary ret = np.zeros(len(vocab), dtype=int) for word in text.split(' '): if word in word2idx: ret[word2idx[word]] += 1 return ret Explanation: Text to vector function Now we can write a function that converts a some text to a word vector. The function will take a string of words as input and return a vector with the words counted up. Here's the general algorithm to do this: Initialize the word vector with np.zeros, it should be the length of the vocabulary. Split the input string of text into a list of words with .split(' '). Again, if you call .split() instead, you'll get slightly different results than what we show here. For each word in that list, increment the element in the index associated with that word, which you get from word2idx. Note: Since all words aren't in the vocab dictionary, you'll get a key error if you run into one of those words. You can use the .get method of the word2idx dictionary to specify a default returned value when you make a key error. For example, word2idx.get(word, None) returns None if word doesn't exist in the dictionary. End of explanation text_to_vector('The tea is for a party to celebrate ' 'the movie so she has no time for a cake')[:65] Explanation: If you do this right, the following code should return ``` text_to_vector('The tea is for a party to celebrate ' 'the movie so she has no time for a cake')[:65] array([0, 1, 0, 0, 2, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0]) ``` End of explanation word_vectors = np.zeros((len(reviews), len(vocab)), dtype=np.int_) for ii, (_, text) in enumerate(reviews.to_records()): word_vectors[ii] = text_to_vector(text) # Printing out the first 5 word vectors word_vectors[:5, :23] Explanation: Now, run through our entire review data set and convert each review to a word vector. End of explanation Y = (labels=='positive').astype(np.int_) records = len(labels) shuffle = np.arange(records) np.random.shuffle(shuffle) test_fraction = 0.9 train_split, test_split = shuffle[:int(records*test_fraction)], shuffle[int(records*test_fraction):] trainX, trainY = word_vectors[train_split,:], to_categorical(Y.values.T[0][train_split], 2) testX, testY = word_vectors[test_split,:], to_categorical(Y.values.T[0][test_split], 2) trainX trainY Explanation: Train, Validation, Test sets Now that we have the word_vectors, we're ready to split our data into train, validation, and test sets. Remember that we train on the train data, use the validation data to set the hyperparameters, and at the very end measure the network performance on the test data. Here we're using the function to_categorical from TFLearn to reshape the target data so that we'll have two output units and can classify with a softmax activation function. We actually won't be creating the validation set here, TFLearn will do that for us later. End of explanation # Network building def build_model(input_size, hidden_units=[100, 30], lr=0.1): # This resets all parameters and variables, leave this here tf.reset_default_graph() # Input -- [batch_size, input_vector_dimension] print('Input features size: %s' % input_size) net = tflearn.input_data([None, input_size]) # Hidden -- for n in hidden_units: net = tflearn.fully_connected(net, n, activation='ReLU') # Output -- net = tflearn.fully_connected(net, 2, activation='softmax') # sgd: stochastic gradient descent net = tflearn.regression(net, optimizer='sgd', learning_rate=lr, loss='categorical_crossentropy') model = tflearn.DNN(net) return model Explanation: Building the network TFLearn lets you build the network by defining the layers. Input layer For the input layer, you just need to tell it how many units you have. For example, net = tflearn.input_data([None, 100]) would create a network with 100 input units. The first element in the list, None in this case, sets the batch size. Setting it to None here leaves it at the default batch size. The number of inputs to your network needs to match the size of your data. For this example, we're using 10000 element long vectors to encode our input data, so we need 10000 input units. Adding layers To add new hidden layers, you use net = tflearn.fully_connected(net, n_units, activation='ReLU') This adds a fully connected layer where every unit in the previous layer is connected to every unit in this layer. The first argument net is the network you created in the tflearn.input_data call. It's telling the network to use the output of the previous layer as the input to this layer. You can set the number of units in the layer with n_units, and set the activation function with the activation keyword. You can keep adding layers to your network by repeated calling net = tflearn.fully_connected(net, n_units). Output layer The last layer you add is used as the output layer. Therefore, you need to set the number of units to match the target data. In this case we are predicting two classes, positive or negative sentiment. You also need to set the activation function so it's appropriate for your model. Again, we're trying to predict if some input data belongs to one of two classes, so we should use softmax. net = tflearn.fully_connected(net, 2, activation='softmax') Training To set how you train the network, use net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy') Again, this is passing in the network you've been building. The keywords: optimizer sets the training method, here stochastic gradient descent learning_rate is the learning rate loss determines how the network error is calculated. In this example, with the categorical cross-entropy. Finally you put all this together to create the model with tflearn.DNN(net). So it ends up looking something like net = tflearn.input_data([None, 10]) # Input net = tflearn.fully_connected(net, 5, activation='ReLU') # Hidden net = tflearn.fully_connected(net, 2, activation='softmax') # Output net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy') model = tflearn.DNN(net) Exercise: Below in the build_model() function, you'll put together the network using TFLearn. You get to choose how many layers to use, how many hidden units, etc. End of explanation model = build_model(trainX.shape[1], [5000, 200, 25], 0.08) Explanation: Intializing the model Next we need to call the build_model() function to actually build the model. In my solution I haven't included any arguments to the function, but you can add arguments so you can change parameters in the model if you want. Note: You might get a bunch of warnings here. TFLearn uses a lot of deprecated code in TensorFlow. Hopefully it gets updated to the new TensorFlow version soon. End of explanation # Training model = build_model(trainX.shape[1], [2000, 200, 40], 0.05) model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=128, n_epoch=300) Explanation: Training the network Now that we've constructed the network, saved as the variable model, we can fit it to the data. Here we use the model.fit method. You pass in the training features trainX and the training targets trainY. Below I set validation_set=0.1 which reserves 10% of the data set as the validation set. You can also set the batch size and number of epochs with the batch_size and n_epoch keywords, respectively. Below is the code to fit our the network to our word vectors. You can rerun model.fit to train the network further if you think you can increase the validation accuracy. Remember, all hyperparameter adjustments must be done using the validation set. Only use the test set after you're completely done training the network. End of explanation predictions = (np.array(model.predict(testX))[:,0] >= 0.5).astype(np.int_) test_accuracy = np.mean(predictions == testY[:,0], axis=0) print("Test accuracy: ", test_accuracy) Explanation: Testing After you're satisified with your hyperparameters, you can run the network on the test set to measure its performance. Remember, only do this after finalizing the hyperparameters. End of explanation # Helper function that uses your model to predict sentiment def test_sentence(sentence): positive_prob = model.predict([text_to_vector(sentence.lower())])[0][1] print('Sentence: {}'.format(sentence)) print('P(positive) = {:.3f} :'.format(positive_prob), 'Positive' if positive_prob > 0.5 else 'Negative') sentence = "Moonlight is by far the best movie of 2016." test_sentence(sentence) sentence = "It's amazing anyone could be talented enough to make something this spectacularly awful" test_sentence(sentence) Explanation: Try out your own text! End of explanation
7,393
Given the following text description, write Python code to implement the functionality described below step by step Description: ES-DOC CMIP6 Model Properties - Atmos MIP Era Step1: Document Authors Set document authors Step2: Document Contributors Specify document contributors Step3: Document Publication Specify document publication status Step4: Document Table of Contents 1. Key Properties --&gt; Overview 2. Key Properties --&gt; Resolution 3. Key Properties --&gt; Timestepping 4. Key Properties --&gt; Orography 5. Grid --&gt; Discretisation 6. Grid --&gt; Discretisation --&gt; Horizontal 7. Grid --&gt; Discretisation --&gt; Vertical 8. Dynamical Core 9. Dynamical Core --&gt; Top Boundary 10. Dynamical Core --&gt; Lateral Boundary 11. Dynamical Core --&gt; Diffusion Horizontal 12. Dynamical Core --&gt; Advection Tracers 13. Dynamical Core --&gt; Advection Momentum 14. Radiation 15. Radiation --&gt; Shortwave Radiation 16. Radiation --&gt; Shortwave GHG 17. Radiation --&gt; Shortwave Cloud Ice 18. Radiation --&gt; Shortwave Cloud Liquid 19. Radiation --&gt; Shortwave Cloud Inhomogeneity 20. Radiation --&gt; Shortwave Aerosols 21. Radiation --&gt; Shortwave Gases 22. Radiation --&gt; Longwave Radiation 23. Radiation --&gt; Longwave GHG 24. Radiation --&gt; Longwave Cloud Ice 25. Radiation --&gt; Longwave Cloud Liquid 26. Radiation --&gt; Longwave Cloud Inhomogeneity 27. Radiation --&gt; Longwave Aerosols 28. Radiation --&gt; Longwave Gases 29. Turbulence Convection 30. Turbulence Convection --&gt; Boundary Layer Turbulence 31. Turbulence Convection --&gt; Deep Convection 32. Turbulence Convection --&gt; Shallow Convection 33. Microphysics Precipitation 34. Microphysics Precipitation --&gt; Large Scale Precipitation 35. Microphysics Precipitation --&gt; Large Scale Cloud Microphysics 36. Cloud Scheme 37. Cloud Scheme --&gt; Optical Cloud Properties 38. Cloud Scheme --&gt; Sub Grid Scale Water Distribution 39. Cloud Scheme --&gt; Sub Grid Scale Ice Distribution 40. Observation Simulation 41. Observation Simulation --&gt; Isscp Attributes 42. Observation Simulation --&gt; Cosp Attributes 43. Observation Simulation --&gt; Radar Inputs 44. Observation Simulation --&gt; Lidar Inputs 45. Gravity Waves 46. Gravity Waves --&gt; Orographic Gravity Waves 47. Gravity Waves --&gt; Non Orographic Gravity Waves 48. Solar 49. Solar --&gt; Solar Pathways 50. Solar --&gt; Solar Constant 51. Solar --&gt; Orbital Parameters 52. Solar --&gt; Insolation Ozone 53. Volcanos 54. Volcanos --&gt; Volcanoes Treatment 1. Key Properties --&gt; Overview Top level key properties 1.1. Model Overview Is Required Step5: 1.2. Model Name Is Required Step6: 1.3. Model Family Is Required Step7: 1.4. Basic Approximations Is Required Step8: 2. Key Properties --&gt; Resolution Characteristics of the model resolution 2.1. Horizontal Resolution Name Is Required Step9: 2.2. Canonical Horizontal Resolution Is Required Step10: 2.3. Range Horizontal Resolution Is Required Step11: 2.4. Number Of Vertical Levels Is Required Step12: 2.5. High Top Is Required Step13: 3. Key Properties --&gt; Timestepping Characteristics of the atmosphere model time stepping 3.1. Timestep Dynamics Is Required Step14: 3.2. Timestep Shortwave Radiative Transfer Is Required Step15: 3.3. Timestep Longwave Radiative Transfer Is Required Step16: 4. Key Properties --&gt; Orography Characteristics of the model orography 4.1. Type Is Required Step17: 4.2. Changes Is Required Step18: 5. Grid --&gt; Discretisation Atmosphere grid discretisation 5.1. Overview Is Required Step19: 6. Grid --&gt; Discretisation --&gt; Horizontal Atmosphere discretisation in the horizontal 6.1. Scheme Type Is Required Step20: 6.2. Scheme Method Is Required Step21: 6.3. Scheme Order Is Required Step22: 6.4. Horizontal Pole Is Required Step23: 6.5. Grid Type Is Required Step24: 7. Grid --&gt; Discretisation --&gt; Vertical Atmosphere discretisation in the vertical 7.1. Coordinate Type Is Required Step25: 8. Dynamical Core Characteristics of the dynamical core 8.1. Overview Is Required Step26: 8.2. Name Is Required Step27: 8.3. Timestepping Type Is Required Step28: 8.4. Prognostic Variables Is Required Step29: 9. Dynamical Core --&gt; Top Boundary Type of boundary layer at the top of the model 9.1. Top Boundary Condition Is Required Step30: 9.2. Top Heat Is Required Step31: 9.3. Top Wind Is Required Step32: 10. Dynamical Core --&gt; Lateral Boundary Type of lateral boundary condition (if the model is a regional model) 10.1. Condition Is Required Step33: 11. Dynamical Core --&gt; Diffusion Horizontal Horizontal diffusion scheme 11.1. Scheme Name Is Required Step34: 11.2. Scheme Method Is Required Step35: 12. Dynamical Core --&gt; Advection Tracers Tracer advection scheme 12.1. Scheme Name Is Required Step36: 12.2. Scheme Characteristics Is Required Step37: 12.3. Conserved Quantities Is Required Step38: 12.4. Conservation Method Is Required Step39: 13. Dynamical Core --&gt; Advection Momentum Momentum advection scheme 13.1. Scheme Name Is Required Step40: 13.2. Scheme Characteristics Is Required Step41: 13.3. Scheme Staggering Type Is Required Step42: 13.4. Conserved Quantities Is Required Step43: 13.5. Conservation Method Is Required Step44: 14. Radiation Characteristics of the atmosphere radiation process 14.1. Aerosols Is Required Step45: 15. Radiation --&gt; Shortwave Radiation Properties of the shortwave radiation scheme 15.1. Overview Is Required Step46: 15.2. Name Is Required Step47: 15.3. Spectral Integration Is Required Step48: 15.4. Transport Calculation Is Required Step49: 15.5. Spectral Intervals Is Required Step50: 16. Radiation --&gt; Shortwave GHG Representation of greenhouse gases in the shortwave radiation scheme 16.1. Greenhouse Gas Complexity Is Required Step51: 16.2. ODS Is Required Step52: 16.3. Other Flourinated Gases Is Required Step53: 17. Radiation --&gt; Shortwave Cloud Ice Shortwave radiative properties of ice crystals in clouds 17.1. General Interactions Is Required Step54: 17.2. Physical Representation Is Required Step55: 17.3. Optical Methods Is Required Step56: 18. Radiation --&gt; Shortwave Cloud Liquid Shortwave radiative properties of liquid droplets in clouds 18.1. General Interactions Is Required Step57: 18.2. Physical Representation Is Required Step58: 18.3. Optical Methods Is Required Step59: 19. Radiation --&gt; Shortwave Cloud Inhomogeneity Cloud inhomogeneity in the shortwave radiation scheme 19.1. Cloud Inhomogeneity Is Required Step60: 20. Radiation --&gt; Shortwave Aerosols Shortwave radiative properties of aerosols 20.1. General Interactions Is Required Step61: 20.2. Physical Representation Is Required Step62: 20.3. Optical Methods Is Required Step63: 21. Radiation --&gt; Shortwave Gases Shortwave radiative properties of gases 21.1. General Interactions Is Required Step64: 22. Radiation --&gt; Longwave Radiation Properties of the longwave radiation scheme 22.1. Overview Is Required Step65: 22.2. Name Is Required Step66: 22.3. Spectral Integration Is Required Step67: 22.4. Transport Calculation Is Required Step68: 22.5. Spectral Intervals Is Required Step69: 23. Radiation --&gt; Longwave GHG Representation of greenhouse gases in the longwave radiation scheme 23.1. Greenhouse Gas Complexity Is Required Step70: 23.2. ODS Is Required Step71: 23.3. Other Flourinated Gases Is Required Step72: 24. Radiation --&gt; Longwave Cloud Ice Longwave radiative properties of ice crystals in clouds 24.1. General Interactions Is Required Step73: 24.2. Physical Reprenstation Is Required Step74: 24.3. Optical Methods Is Required Step75: 25. Radiation --&gt; Longwave Cloud Liquid Longwave radiative properties of liquid droplets in clouds 25.1. General Interactions Is Required Step76: 25.2. Physical Representation Is Required Step77: 25.3. Optical Methods Is Required Step78: 26. Radiation --&gt; Longwave Cloud Inhomogeneity Cloud inhomogeneity in the longwave radiation scheme 26.1. Cloud Inhomogeneity Is Required Step79: 27. Radiation --&gt; Longwave Aerosols Longwave radiative properties of aerosols 27.1. General Interactions Is Required Step80: 27.2. Physical Representation Is Required Step81: 27.3. Optical Methods Is Required Step82: 28. Radiation --&gt; Longwave Gases Longwave radiative properties of gases 28.1. General Interactions Is Required Step83: 29. Turbulence Convection Atmosphere Convective Turbulence and Clouds 29.1. Overview Is Required Step84: 30. Turbulence Convection --&gt; Boundary Layer Turbulence Properties of the boundary layer turbulence scheme 30.1. Scheme Name Is Required Step85: 30.2. Scheme Type Is Required Step86: 30.3. Closure Order Is Required Step87: 30.4. Counter Gradient Is Required Step88: 31. Turbulence Convection --&gt; Deep Convection Properties of the deep convection scheme 31.1. Scheme Name Is Required Step89: 31.2. Scheme Type Is Required Step90: 31.3. Scheme Method Is Required Step91: 31.4. Processes Is Required Step92: 31.5. Microphysics Is Required Step93: 32. Turbulence Convection --&gt; Shallow Convection Properties of the shallow convection scheme 32.1. Scheme Name Is Required Step94: 32.2. Scheme Type Is Required Step95: 32.3. Scheme Method Is Required Step96: 32.4. Processes Is Required Step97: 32.5. Microphysics Is Required Step98: 33. Microphysics Precipitation Large Scale Cloud Microphysics and Precipitation 33.1. Overview Is Required Step99: 34. Microphysics Precipitation --&gt; Large Scale Precipitation Properties of the large scale precipitation scheme 34.1. Scheme Name Is Required Step100: 34.2. Hydrometeors Is Required Step101: 35. Microphysics Precipitation --&gt; Large Scale Cloud Microphysics Properties of the large scale cloud microphysics scheme 35.1. Scheme Name Is Required Step102: 35.2. Processes Is Required Step103: 36. Cloud Scheme Characteristics of the cloud scheme 36.1. Overview Is Required Step104: 36.2. Name Is Required Step105: 36.3. Atmos Coupling Is Required Step106: 36.4. Uses Separate Treatment Is Required Step107: 36.5. Processes Is Required Step108: 36.6. Prognostic Scheme Is Required Step109: 36.7. Diagnostic Scheme Is Required Step110: 36.8. Prognostic Variables Is Required Step111: 37. Cloud Scheme --&gt; Optical Cloud Properties Optical cloud properties 37.1. Cloud Overlap Method Is Required Step112: 37.2. Cloud Inhomogeneity Is Required Step113: 38. Cloud Scheme --&gt; Sub Grid Scale Water Distribution Sub-grid scale water distribution 38.1. Type Is Required Step114: 38.2. Function Name Is Required Step115: 38.3. Function Order Is Required Step116: 38.4. Convection Coupling Is Required Step117: 39. Cloud Scheme --&gt; Sub Grid Scale Ice Distribution Sub-grid scale ice distribution 39.1. Type Is Required Step118: 39.2. Function Name Is Required Step119: 39.3. Function Order Is Required Step120: 39.4. Convection Coupling Is Required Step121: 40. Observation Simulation Characteristics of observation simulation 40.1. Overview Is Required Step122: 41. Observation Simulation --&gt; Isscp Attributes ISSCP Characteristics 41.1. Top Height Estimation Method Is Required Step123: 41.2. Top Height Direction Is Required Step124: 42. Observation Simulation --&gt; Cosp Attributes CFMIP Observational Simulator Package attributes 42.1. Run Configuration Is Required Step125: 42.2. Number Of Grid Points Is Required Step126: 42.3. Number Of Sub Columns Is Required Step127: 42.4. Number Of Levels Is Required Step128: 43. Observation Simulation --&gt; Radar Inputs Characteristics of the cloud radar simulator 43.1. Frequency Is Required Step129: 43.2. Type Is Required Step130: 43.3. Gas Absorption Is Required Step131: 43.4. Effective Radius Is Required Step132: 44. Observation Simulation --&gt; Lidar Inputs Characteristics of the cloud lidar simulator 44.1. Ice Types Is Required Step133: 44.2. Overlap Is Required Step134: 45. Gravity Waves Characteristics of the parameterised gravity waves in the atmosphere, whether from orography or other sources. 45.1. Overview Is Required Step135: 45.2. Sponge Layer Is Required Step136: 45.3. Background Is Required Step137: 45.4. Subgrid Scale Orography Is Required Step138: 46. Gravity Waves --&gt; Orographic Gravity Waves Gravity waves generated due to the presence of orography 46.1. Name Is Required Step139: 46.2. Source Mechanisms Is Required Step140: 46.3. Calculation Method Is Required Step141: 46.4. Propagation Scheme Is Required Step142: 46.5. Dissipation Scheme Is Required Step143: 47. Gravity Waves --&gt; Non Orographic Gravity Waves Gravity waves generated by non-orographic processes. 47.1. Name Is Required Step144: 47.2. Source Mechanisms Is Required Step145: 47.3. Calculation Method Is Required Step146: 47.4. Propagation Scheme Is Required Step147: 47.5. Dissipation Scheme Is Required Step148: 48. Solar Top of atmosphere solar insolation characteristics 48.1. Overview Is Required Step149: 49. Solar --&gt; Solar Pathways Pathways for solar forcing of the atmosphere 49.1. Pathways Is Required Step150: 50. Solar --&gt; Solar Constant Solar constant and top of atmosphere insolation characteristics 50.1. Type Is Required Step151: 50.2. Fixed Value Is Required Step152: 50.3. Transient Characteristics Is Required Step153: 51. Solar --&gt; Orbital Parameters Orbital parameters and top of atmosphere insolation characteristics 51.1. Type Is Required Step154: 51.2. Fixed Reference Date Is Required Step155: 51.3. Transient Method Is Required Step156: 51.4. Computation Method Is Required Step157: 52. Solar --&gt; Insolation Ozone Impact of solar insolation on stratospheric ozone 52.1. Solar Ozone Impact Is Required Step158: 53. Volcanos Characteristics of the implementation of volcanoes 53.1. Overview Is Required Step159: 54. Volcanos --&gt; Volcanoes Treatment Treatment of volcanoes in the atmosphere 54.1. Volcanoes Implementation Is Required
Python Code: # DO NOT EDIT ! from pyesdoc.ipython.model_topic import NotebookOutput # DO NOT EDIT ! DOC = NotebookOutput('cmip6', 'ec-earth-consortium', 'ec-earth3-gris', 'atmos') Explanation: ES-DOC CMIP6 Model Properties - Atmos MIP Era: CMIP6 Institute: EC-EARTH-CONSORTIUM Source ID: EC-EARTH3-GRIS Topic: Atmos Sub-Topics: Dynamical Core, Radiation, Turbulence Convection, Microphysics Precipitation, Cloud Scheme, Observation Simulation, Gravity Waves, Solar, Volcanos. Properties: 156 (127 required) Model descriptions: Model description details Initialized From: -- Notebook Help: Goto notebook help page Notebook Initialised: 2018-02-15 16:53:59 Document Setup IMPORTANT: to be executed each time you run the notebook End of explanation # Set as follows: DOC.set_author("name", "email") # TODO - please enter value(s) Explanation: Document Authors Set document authors End of explanation # Set as follows: DOC.set_contributor("name", "email") # TODO - please enter value(s) Explanation: Document Contributors Specify document contributors End of explanation # Set publication status: # 0=do not publish, 1=publish. DOC.set_publication_status(0) Explanation: Document Publication Specify document publication status End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.model_overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: Document Table of Contents 1. Key Properties --&gt; Overview 2. Key Properties --&gt; Resolution 3. Key Properties --&gt; Timestepping 4. Key Properties --&gt; Orography 5. Grid --&gt; Discretisation 6. Grid --&gt; Discretisation --&gt; Horizontal 7. Grid --&gt; Discretisation --&gt; Vertical 8. Dynamical Core 9. Dynamical Core --&gt; Top Boundary 10. Dynamical Core --&gt; Lateral Boundary 11. Dynamical Core --&gt; Diffusion Horizontal 12. Dynamical Core --&gt; Advection Tracers 13. Dynamical Core --&gt; Advection Momentum 14. Radiation 15. Radiation --&gt; Shortwave Radiation 16. Radiation --&gt; Shortwave GHG 17. Radiation --&gt; Shortwave Cloud Ice 18. Radiation --&gt; Shortwave Cloud Liquid 19. Radiation --&gt; Shortwave Cloud Inhomogeneity 20. Radiation --&gt; Shortwave Aerosols 21. Radiation --&gt; Shortwave Gases 22. Radiation --&gt; Longwave Radiation 23. Radiation --&gt; Longwave GHG 24. Radiation --&gt; Longwave Cloud Ice 25. Radiation --&gt; Longwave Cloud Liquid 26. Radiation --&gt; Longwave Cloud Inhomogeneity 27. Radiation --&gt; Longwave Aerosols 28. Radiation --&gt; Longwave Gases 29. Turbulence Convection 30. Turbulence Convection --&gt; Boundary Layer Turbulence 31. Turbulence Convection --&gt; Deep Convection 32. Turbulence Convection --&gt; Shallow Convection 33. Microphysics Precipitation 34. Microphysics Precipitation --&gt; Large Scale Precipitation 35. Microphysics Precipitation --&gt; Large Scale Cloud Microphysics 36. Cloud Scheme 37. Cloud Scheme --&gt; Optical Cloud Properties 38. Cloud Scheme --&gt; Sub Grid Scale Water Distribution 39. Cloud Scheme --&gt; Sub Grid Scale Ice Distribution 40. Observation Simulation 41. Observation Simulation --&gt; Isscp Attributes 42. Observation Simulation --&gt; Cosp Attributes 43. Observation Simulation --&gt; Radar Inputs 44. Observation Simulation --&gt; Lidar Inputs 45. Gravity Waves 46. Gravity Waves --&gt; Orographic Gravity Waves 47. Gravity Waves --&gt; Non Orographic Gravity Waves 48. Solar 49. Solar --&gt; Solar Pathways 50. Solar --&gt; Solar Constant 51. Solar --&gt; Orbital Parameters 52. Solar --&gt; Insolation Ozone 53. Volcanos 54. Volcanos --&gt; Volcanoes Treatment 1. Key Properties --&gt; Overview Top level key properties 1.1. Model Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview of atmosphere model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.model_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 1.2. Model Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Name of atmosphere model code (CAM 4.0, ARPEGE 3.2,...) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.model_family') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "AGCM" # "ARCM" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 1.3. Model Family Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Type of atmospheric model. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.overview.basic_approximations') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "primitive equations" # "non-hydrostatic" # "anelastic" # "Boussinesq" # "hydrostatic" # "quasi-hydrostatic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 1.4. Basic Approximations Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Basic approximations made in the atmosphere. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.horizontal_resolution_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 2. Key Properties --&gt; Resolution Characteristics of the model resolution 2.1. Horizontal Resolution Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 This is a string usually used by the modelling group to describe the resolution of the model grid, e.g. T42, N48. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.canonical_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 2.2. Canonical Horizontal Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Expression quoted for gross comparisons of resolution, e.g. 2.5 x 3.75 degrees lat-lon. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.range_horizontal_resolution') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 2.3. Range Horizontal Resolution Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Range of horizontal resolution with spatial details, eg. 1 deg (Equator) - 0.5 deg End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.number_of_vertical_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 2.4. Number Of Vertical Levels Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Number of vertical levels resolved on the computational grid. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.resolution.high_top') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 2.5. High Top Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does the atmosphere have a high-top? High-Top atmospheres have a fully resolved stratosphere with a model top above the stratopause. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_dynamics') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 3. Key Properties --&gt; Timestepping Characteristics of the atmosphere model time stepping 3.1. Timestep Dynamics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestep for the dynamics, e.g. 30 min. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_shortwave_radiative_transfer') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 3.2. Timestep Shortwave Radiative Transfer Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for the shortwave radiative transfer, e.g. 1.5 hours. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.timestepping.timestep_longwave_radiative_transfer') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 3.3. Timestep Longwave Radiative Transfer Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Timestep for the longwave radiative transfer, e.g. 3 hours. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.orography.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "present day" # "modified" # TODO - please enter value(s) Explanation: 4. Key Properties --&gt; Orography Characteristics of the model orography 4.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time adaptation of the orography. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.key_properties.orography.changes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "related to ice sheets" # "related to tectonics" # "modified mean" # "modified variance if taken into account in model (cf gravity waves)" # TODO - please enter value(s) Explanation: 4.2. Changes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N If the orography type is modified describe the time adaptation changes. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 5. Grid --&gt; Discretisation Atmosphere grid discretisation 5.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of grid discretisation in the atmosphere End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "spectral" # "fixed grid" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 6. Grid --&gt; Discretisation --&gt; Horizontal Atmosphere discretisation in the horizontal 6.1. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal discretisation type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "finite elements" # "finite volumes" # "finite difference" # "centered finite difference" # TODO - please enter value(s) Explanation: 6.2. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal discretisation method End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.scheme_order') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "second" # "third" # "fourth" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 6.3. Scheme Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal discretisation function order End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.horizontal_pole') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "filter" # "pole rotation" # "artificial island" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 6.4. Horizontal Pole Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Horizontal discretisation pole singularity treatment End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.horizontal.grid_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Gaussian" # "Latitude-Longitude" # "Cubed-Sphere" # "Icosahedral" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 6.5. Grid Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal grid type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.grid.discretisation.vertical.coordinate_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "isobaric" # "sigma" # "hybrid sigma-pressure" # "hybrid pressure" # "vertically lagrangian" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 7. Grid --&gt; Discretisation --&gt; Vertical Atmosphere discretisation in the vertical 7.1. Coordinate Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Type of vertical coordinate system End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8. Dynamical Core Characteristics of the dynamical core 8.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of atmosphere dynamical core End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 8.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the dynamical core of the model. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.timestepping_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Adams-Bashforth" # "explicit" # "implicit" # "semi-implicit" # "leap frog" # "multi-step" # "Runge Kutta fifth order" # "Runge Kutta second order" # "Runge Kutta third order" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 8.3. Timestepping Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Timestepping framework type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "surface pressure" # "wind components" # "divergence/curl" # "temperature" # "potential temperature" # "total water" # "water vapour" # "water liquid" # "water ice" # "total water moments" # "clouds" # "radiation" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 8.4. Prognostic Variables Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N List of the model prognostic variables End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_boundary_condition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "sponge layer" # "radiation boundary condition" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 9. Dynamical Core --&gt; Top Boundary Type of boundary layer at the top of the model 9.1. Top Boundary Condition Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Top boundary condition End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_heat') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9.2. Top Heat Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Top boundary heat treatment End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.top_boundary.top_wind') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 9.3. Top Wind Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Top boundary wind treatment End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.lateral_boundary.condition') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "sponge layer" # "radiation boundary condition" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 10. Dynamical Core --&gt; Lateral Boundary Type of lateral boundary condition (if the model is a regional model) 10.1. Condition Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Type of lateral boundary condition End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.diffusion_horizontal.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 11. Dynamical Core --&gt; Diffusion Horizontal Horizontal diffusion scheme 11.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Horizontal diffusion scheme name End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.diffusion_horizontal.scheme_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "iterated Laplacian" # "bi-harmonic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 11.2. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Horizontal diffusion scheme method End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Heun" # "Roe and VanLeer" # "Roe and Superbee" # "Prather" # "UTOPIA" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 12. Dynamical Core --&gt; Advection Tracers Tracer advection scheme 12.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Tracer advection scheme name End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.scheme_characteristics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Eulerian" # "modified Euler" # "Lagrangian" # "semi-Lagrangian" # "cubic semi-Lagrangian" # "quintic semi-Lagrangian" # "mass-conserving" # "finite volume" # "flux-corrected" # "linear" # "quadratic" # "quartic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 12.2. Scheme Characteristics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Tracer advection scheme characteristics End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.conserved_quantities') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "dry mass" # "tracer mass" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 12.3. Conserved Quantities Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Tracer advection scheme conserved quantities End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_tracers.conservation_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "conservation fixer" # "Priestley algorithm" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 12.4. Conservation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Tracer advection scheme conservation method End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "VanLeer" # "Janjic" # "SUPG (Streamline Upwind Petrov-Galerkin)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13. Dynamical Core --&gt; Advection Momentum Momentum advection scheme 13.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Momentum advection schemes name End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_characteristics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "2nd order" # "4th order" # "cell-centred" # "staggered grid" # "semi-staggered grid" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13.2. Scheme Characteristics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Momentum advection scheme characteristics End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.scheme_staggering_type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Arakawa B-grid" # "Arakawa C-grid" # "Arakawa D-grid" # "Arakawa E-grid" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13.3. Scheme Staggering Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Momentum advection scheme staggering type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.conserved_quantities') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "Angular momentum" # "Horizontal momentum" # "Enstrophy" # "Mass" # "Total energy" # "Vorticity" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13.4. Conserved Quantities Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Momentum advection scheme conserved quantities End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.dynamical_core.advection_momentum.conservation_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "conservation fixer" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 13.5. Conservation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Momentum advection scheme conservation method End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.aerosols') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "sulphate" # "nitrate" # "sea salt" # "dust" # "ice" # "organic" # "BC (black carbon / soot)" # "SOA (secondary organic aerosols)" # "POM (particulate organic matter)" # "polar stratospheric ice" # "NAT (nitric acid trihydrate)" # "NAD (nitric acid dihydrate)" # "STS (supercooled ternary solution aerosol particle)" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 14. Radiation Characteristics of the atmosphere radiation process 14.1. Aerosols Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Aerosols whose radiative effect is taken into account in the atmosphere model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 15. Radiation --&gt; Shortwave Radiation Properties of the shortwave radiation scheme 15.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of shortwave radiation in the atmosphere End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 15.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the shortwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.spectral_integration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "wide-band model" # "correlated-k" # "exponential sum fitting" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 15.3. Spectral Integration Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Shortwave radiation scheme spectral integration End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.transport_calculation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "two-stream" # "layer interaction" # "bulk" # "adaptive" # "multi-stream" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 15.4. Transport Calculation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Shortwave radiation transport calculation methods End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_radiation.spectral_intervals') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 15.5. Spectral Intervals Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Shortwave radiation scheme number of spectral intervals End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.greenhouse_gas_complexity') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CO2" # "CH4" # "N2O" # "CFC-11 eq" # "CFC-12 eq" # "HFC-134a eq" # "Explicit ODSs" # "Explicit other fluorinated gases" # "O3" # "H2O" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 16. Radiation --&gt; Shortwave GHG Representation of greenhouse gases in the shortwave radiation scheme 16.1. Greenhouse Gas Complexity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Complexity of greenhouse gases whose shortwave radiative effects are taken into account in the atmosphere model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.ODS') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CFC-12" # "CFC-11" # "CFC-113" # "CFC-114" # "CFC-115" # "HCFC-22" # "HCFC-141b" # "HCFC-142b" # "Halon-1211" # "Halon-1301" # "Halon-2402" # "methyl chloroform" # "carbon tetrachloride" # "methyl chloride" # "methylene chloride" # "chloroform" # "methyl bromide" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 16.2. ODS Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Ozone depleting substances whose shortwave radiative effects are explicitly taken into account in the atmosphere model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_GHG.other_flourinated_gases') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "HFC-134a" # "HFC-23" # "HFC-32" # "HFC-125" # "HFC-143a" # "HFC-152a" # "HFC-227ea" # "HFC-236fa" # "HFC-245fa" # "HFC-365mfc" # "HFC-43-10mee" # "CF4" # "C2F6" # "C3F8" # "C4F10" # "C5F12" # "C6F14" # "C7F16" # "C8F18" # "c-C4F8" # "NF3" # "SF6" # "SO2F2" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 16.3. Other Flourinated Gases Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Other flourinated gases whose shortwave radiative effects are explicitly taken into account in the atmosphere model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17. Radiation --&gt; Shortwave Cloud Ice Shortwave radiative properties of ice crystals in clouds 17.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with cloud ice crystals End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "bi-modal size distribution" # "ensemble of ice crystals" # "mean projected area" # "ice water path" # "crystal asymmetry" # "crystal aspect ratio" # "effective crystal radius" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud ice crystals in the shortwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_ice.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 17.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud ice crystals in the shortwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 18. Radiation --&gt; Shortwave Cloud Liquid Shortwave radiative properties of liquid droplets in clouds 18.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with cloud liquid droplets End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "cloud droplet number concentration" # "effective cloud droplet radii" # "droplet size distribution" # "liquid water path" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 18.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud liquid droplets in the shortwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_liquid.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "geometric optics" # "Mie theory" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 18.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud liquid droplets in the shortwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_cloud_inhomogeneity.cloud_inhomogeneity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Monte Carlo Independent Column Approximation" # "Triplecloud" # "analytic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 19. Radiation --&gt; Shortwave Cloud Inhomogeneity Cloud inhomogeneity in the shortwave radiation scheme 19.1. Cloud Inhomogeneity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Method for taking into account horizontal cloud inhomogeneity End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 20. Radiation --&gt; Shortwave Aerosols Shortwave radiative properties of aerosols 20.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with aerosols End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "number concentration" # "effective radii" # "size distribution" # "asymmetry" # "aspect ratio" # "mixing state" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 20.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of aerosols in the shortwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_aerosols.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 20.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to aerosols in the shortwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.shortwave_gases.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 21. Radiation --&gt; Shortwave Gases Shortwave radiative properties of gases 21.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General shortwave radiative interactions with gases End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 22. Radiation --&gt; Longwave Radiation Properties of the longwave radiation scheme 22.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of longwave radiation in the atmosphere End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 22.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the longwave radiation scheme. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.spectral_integration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "wide-band model" # "correlated-k" # "exponential sum fitting" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 22.3. Spectral Integration Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Longwave radiation scheme spectral integration End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.transport_calculation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "two-stream" # "layer interaction" # "bulk" # "adaptive" # "multi-stream" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 22.4. Transport Calculation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Longwave radiation transport calculation methods End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_radiation.spectral_intervals') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 22.5. Spectral Intervals Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Longwave radiation scheme number of spectral intervals End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_GHG.greenhouse_gas_complexity') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CO2" # "CH4" # "N2O" # "CFC-11 eq" # "CFC-12 eq" # "HFC-134a eq" # "Explicit ODSs" # "Explicit other fluorinated gases" # "O3" # "H2O" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 23. Radiation --&gt; Longwave GHG Representation of greenhouse gases in the longwave radiation scheme 23.1. Greenhouse Gas Complexity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Complexity of greenhouse gases whose longwave radiative effects are taken into account in the atmosphere model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_GHG.ODS') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CFC-12" # "CFC-11" # "CFC-113" # "CFC-114" # "CFC-115" # "HCFC-22" # "HCFC-141b" # "HCFC-142b" # "Halon-1211" # "Halon-1301" # "Halon-2402" # "methyl chloroform" # "carbon tetrachloride" # "methyl chloride" # "methylene chloride" # "chloroform" # "methyl bromide" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 23.2. ODS Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Ozone depleting substances whose longwave radiative effects are explicitly taken into account in the atmosphere model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_GHG.other_flourinated_gases') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "HFC-134a" # "HFC-23" # "HFC-32" # "HFC-125" # "HFC-143a" # "HFC-152a" # "HFC-227ea" # "HFC-236fa" # "HFC-245fa" # "HFC-365mfc" # "HFC-43-10mee" # "CF4" # "C2F6" # "C3F8" # "C4F10" # "C5F12" # "C6F14" # "C7F16" # "C8F18" # "c-C4F8" # "NF3" # "SF6" # "SO2F2" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 23.3. Other Flourinated Gases Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Other flourinated gases whose longwave radiative effects are explicitly taken into account in the atmosphere model End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 24. Radiation --&gt; Longwave Cloud Ice Longwave radiative properties of ice crystals in clouds 24.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with cloud ice crystals End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.physical_reprenstation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "bi-modal size distribution" # "ensemble of ice crystals" # "mean projected area" # "ice water path" # "crystal asymmetry" # "crystal aspect ratio" # "effective crystal radius" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 24.2. Physical Reprenstation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud ice crystals in the longwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_ice.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 24.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud ice crystals in the longwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 25. Radiation --&gt; Longwave Cloud Liquid Longwave radiative properties of liquid droplets in clouds 25.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with cloud liquid droplets End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "cloud droplet number concentration" # "effective cloud droplet radii" # "droplet size distribution" # "liquid water path" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 25.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of cloud liquid droplets in the longwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_liquid.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "geometric optics" # "Mie theory" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 25.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to cloud liquid droplets in the longwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_cloud_inhomogeneity.cloud_inhomogeneity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Monte Carlo Independent Column Approximation" # "Triplecloud" # "analytic" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 26. Radiation --&gt; Longwave Cloud Inhomogeneity Cloud inhomogeneity in the longwave radiation scheme 26.1. Cloud Inhomogeneity Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Method for taking into account horizontal cloud inhomogeneity End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 27. Radiation --&gt; Longwave Aerosols Longwave radiative properties of aerosols 27.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with aerosols End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.physical_representation') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "number concentration" # "effective radii" # "size distribution" # "asymmetry" # "aspect ratio" # "mixing state" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 27.2. Physical Representation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical representation of aerosols in the longwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_aerosols.optical_methods') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "T-matrix" # "geometric optics" # "finite difference time domain (FDTD)" # "Mie theory" # "anomalous diffraction approximation" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 27.3. Optical Methods Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Optical methods applicable to aerosols in the longwave radiation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.radiation.longwave_gases.general_interactions') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "scattering" # "emission/absorption" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 28. Radiation --&gt; Longwave Gases Longwave radiative properties of gases 28.1. General Interactions Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N General longwave radiative interactions with gases End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 29. Turbulence Convection Atmosphere Convective Turbulence and Clouds 29.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of atmosphere convection and turbulence End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Mellor-Yamada" # "Holtslag-Boville" # "EDMF" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 30. Turbulence Convection --&gt; Boundary Layer Turbulence Properties of the boundary layer turbulence scheme 30.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Boundary layer turbulence scheme name End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.scheme_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "TKE prognostic" # "TKE diagnostic" # "TKE coupled with water" # "vertical profile of Kz" # "non-local diffusion" # "Monin-Obukhov similarity" # "Coastal Buddy Scheme" # "Coupled with convection" # "Coupled with gravity waves" # "Depth capped at cloud base" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 30.2. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Boundary layer turbulence scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.closure_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 30.3. Closure Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Boundary layer turbulence scheme closure order End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.boundary_layer_turbulence.counter_gradient') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 30.4. Counter Gradient Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Uses boundary layer turbulence scheme counter gradient End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 31. Turbulence Convection --&gt; Deep Convection Properties of the deep convection scheme 31.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Deep convection scheme name End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "mass-flux" # "adjustment" # "plume ensemble" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 31.2. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Deep convection scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.scheme_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "CAPE" # "bulk" # "ensemble" # "CAPE/WFN based" # "TKE/CIN based" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 31.3. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Deep convection scheme method End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "vertical momentum transport" # "convective momentum transport" # "entrainment" # "detrainment" # "penetrative convection" # "updrafts" # "downdrafts" # "radiative effect of anvils" # "re-evaporation of convective precipitation" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 31.4. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical processes taken into account in the parameterisation of deep convection End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.deep_convection.microphysics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "tuning parameter based" # "single moment" # "two moment" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 31.5. Microphysics Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Microphysics scheme for deep convection. Microphysical processes directly control the amount of detrainment of cloud hydrometeor and water vapor from updrafts End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 32. Turbulence Convection --&gt; Shallow Convection Properties of the shallow convection scheme 32.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Shallow convection scheme name End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_type') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "mass-flux" # "cumulus-capped boundary layer" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 32.2. Scheme Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N shallow convection scheme type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.scheme_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "same as deep (unified)" # "included in boundary layer turbulence" # "separate diagnosis" # TODO - please enter value(s) Explanation: 32.3. Scheme Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 shallow convection scheme method End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "convective momentum transport" # "entrainment" # "detrainment" # "penetrative convection" # "re-evaporation of convective precipitation" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 32.4. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Physical processes taken into account in the parameterisation of shallow convection End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.turbulence_convection.shallow_convection.microphysics') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "tuning parameter based" # "single moment" # "two moment" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 32.5. Microphysics Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Microphysics scheme for shallow convection End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 33. Microphysics Precipitation Large Scale Cloud Microphysics and Precipitation 33.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of large scale cloud microphysics and precipitation End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_precipitation.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 34. Microphysics Precipitation --&gt; Large Scale Precipitation Properties of the large scale precipitation scheme 34.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name of the large scale precipitation parameterisation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_precipitation.hydrometeors') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "liquid rain" # "snow" # "hail" # "graupel" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 34.2. Hydrometeors Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Precipitating hydrometeors taken into account in the large scale precipitation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_cloud_microphysics.scheme_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 35. Microphysics Precipitation --&gt; Large Scale Cloud Microphysics Properties of the large scale cloud microphysics scheme 35.1. Scheme Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name of the microphysics parameterisation scheme used for large scale clouds. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.microphysics_precipitation.large_scale_cloud_microphysics.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "mixed phase" # "cloud droplets" # "cloud ice" # "ice nucleation" # "water vapour deposition" # "effect of raindrops" # "effect of snow" # "effect of graupel" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 35.2. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Large scale cloud microphysics processes End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 36. Cloud Scheme Characteristics of the cloud scheme 36.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of the atmosphere cloud scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 36.2. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the cloud scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.atmos_coupling') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "atmosphere_radiation" # "atmosphere_microphysics_precipitation" # "atmosphere_turbulence_convection" # "atmosphere_gravity_waves" # "atmosphere_solar" # "atmosphere_volcano" # "atmosphere_cloud_simulator" # TODO - please enter value(s) Explanation: 36.3. Atmos Coupling Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N Atmosphere components that are linked to the cloud scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.uses_separate_treatment') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 36.4. Uses Separate Treatment Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Different cloud schemes for the different types of clouds (convective, stratiform and boundary layer) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.processes') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "entrainment" # "detrainment" # "bulk cloud" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 36.5. Processes Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Processes included in the cloud scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.prognostic_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 36.6. Prognostic Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the cloud scheme a prognostic scheme? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.diagnostic_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 36.7. Diagnostic Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Is the cloud scheme a diagnostic scheme? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.prognostic_variables') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "cloud amount" # "liquid" # "ice" # "rain" # "snow" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 36.8. Prognostic Variables Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.N List the prognostic variables used by the cloud scheme, if applicable. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.optical_cloud_properties.cloud_overlap_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "random" # "maximum" # "maximum-random" # "exponential" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 37. Cloud Scheme --&gt; Optical Cloud Properties Optical cloud properties 37.1. Cloud Overlap Method Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Method for taking into account overlapping of cloud layers End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.optical_cloud_properties.cloud_inhomogeneity') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 37.2. Cloud Inhomogeneity Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Method for taking into account cloud inhomogeneity End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # TODO - please enter value(s) Explanation: 38. Cloud Scheme --&gt; Sub Grid Scale Water Distribution Sub-grid scale water distribution 38.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale water distribution type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.function_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 38.2. Function Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale water distribution function name End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.function_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 38.3. Function Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale water distribution function type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_water_distribution.convection_coupling') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "coupled with deep" # "coupled with shallow" # "not coupled with convection" # TODO - please enter value(s) Explanation: 38.4. Convection Coupling Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Sub-grid scale water distribution coupling with convection End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "prognostic" # "diagnostic" # TODO - please enter value(s) Explanation: 39. Cloud Scheme --&gt; Sub Grid Scale Ice Distribution Sub-grid scale ice distribution 39.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale ice distribution type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.function_name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 39.2. Function Name Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale ice distribution function name End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.function_order') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 39.3. Function Order Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sub-grid scale ice distribution function type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.cloud_scheme.sub_grid_scale_ice_distribution.convection_coupling') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "coupled with deep" # "coupled with shallow" # "not coupled with convection" # TODO - please enter value(s) Explanation: 39.4. Convection Coupling Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Sub-grid scale ice distribution coupling with convection End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 40. Observation Simulation Characteristics of observation simulation 40.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of observation simulator characteristics End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.isscp_attributes.top_height_estimation_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "no adjustment" # "IR brightness" # "visible optical depth" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 41. Observation Simulation --&gt; Isscp Attributes ISSCP Characteristics 41.1. Top Height Estimation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Cloud simulator ISSCP top height estimation methodUo End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.isscp_attributes.top_height_direction') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "lowest altitude level" # "highest altitude level" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 41.2. Top Height Direction Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator ISSCP top height direction End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.run_configuration') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Inline" # "Offline" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 42. Observation Simulation --&gt; Cosp Attributes CFMIP Observational Simulator Package attributes 42.1. Run Configuration Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP run configuration End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_grid_points') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 42.2. Number Of Grid Points Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP number of grid points End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_sub_columns') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 42.3. Number Of Sub Columns Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP number of sub-cloumns used to simulate sub-grid variability End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.cosp_attributes.number_of_levels') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 42.4. Number Of Levels Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator COSP number of levels End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.frequency') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 43. Observation Simulation --&gt; Radar Inputs Characteristics of the cloud radar simulator 43.1. Frequency Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar frequency (Hz) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "surface" # "space borne" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 43.2. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.gas_absorption') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 43.3. Gas Absorption Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar uses gas absorption End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.radar_inputs.effective_radius') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 43.4. Effective Radius Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator radar uses effective radius End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.lidar_inputs.ice_types') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "ice spheres" # "ice non-spherical" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 44. Observation Simulation --&gt; Lidar Inputs Characteristics of the cloud lidar simulator 44.1. Ice Types Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Cloud simulator lidar ice type End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.observation_simulation.lidar_inputs.overlap') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "max" # "random" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 44.2. Overlap Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Cloud simulator lidar overlap End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 45. Gravity Waves Characteristics of the parameterised gravity waves in the atmosphere, whether from orography or other sources. 45.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of gravity wave parameterisation in the atmosphere End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.sponge_layer') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Rayleigh friction" # "Diffusive sponge layer" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 45.2. Sponge Layer Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Sponge layer in the upper levels in order to avoid gravity wave reflection at the top. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.background') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "continuous spectrum" # "discrete spectrum" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 45.3. Background Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Background wave distribution End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.subgrid_scale_orography') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "effect on drag" # "effect on lifting" # "enhanced topography" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 45.4. Subgrid Scale Orography Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Subgrid scale orography effects taken into account. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 46. Gravity Waves --&gt; Orographic Gravity Waves Gravity waves generated due to the presence of orography 46.1. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the orographic gravity wave scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.source_mechanisms') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "linear mountain waves" # "hydraulic jump" # "envelope orography" # "low level flow blocking" # "statistical sub-grid scale variance" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 46.2. Source Mechanisms Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Orographic gravity wave source mechanisms End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.calculation_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "non-linear calculation" # "more than two cardinal directions" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 46.3. Calculation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Orographic gravity wave calculation method End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.propagation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "linear theory" # "non-linear theory" # "includes boundary layer ducting" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 46.4. Propagation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Orographic gravity wave propogation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.orographic_gravity_waves.dissipation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "total wave" # "single wave" # "spectral" # "linear" # "wave saturation vs Richardson number" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 46.5. Dissipation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Orographic gravity wave dissipation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.name') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 47. Gravity Waves --&gt; Non Orographic Gravity Waves Gravity waves generated by non-orographic processes. 47.1. Name Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 Commonly used name for the non-orographic gravity wave scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.source_mechanisms') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "convection" # "precipitation" # "background spectrum" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 47.2. Source Mechanisms Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Non-orographic gravity wave source mechanisms End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.calculation_method') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "spatially dependent" # "temporally dependent" # TODO - please enter value(s) Explanation: 47.3. Calculation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Non-orographic gravity wave calculation method End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.propagation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "linear theory" # "non-linear theory" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 47.4. Propagation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Non-orographic gravity wave propogation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.gravity_waves.non_orographic_gravity_waves.dissipation_scheme') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "total wave" # "single wave" # "spectral" # "linear" # "wave saturation vs Richardson number" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 47.5. Dissipation Scheme Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Non-orographic gravity wave dissipation scheme End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 48. Solar Top of atmosphere solar insolation characteristics 48.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of solar insolation of the atmosphere End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_pathways.pathways') # PROPERTY VALUE(S): # Set as follows: DOC.set_value("value") # Valid Choices: # "SW radiation" # "precipitating energetic particles" # "cosmic rays" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 49. Solar --&gt; Solar Pathways Pathways for solar forcing of the atmosphere 49.1. Pathways Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.N Pathways for the solar forcing of the atmosphere model domain End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_constant.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "fixed" # "transient" # TODO - please enter value(s) Explanation: 50. Solar --&gt; Solar Constant Solar constant and top of atmosphere insolation characteristics 50.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time adaptation of the solar constant. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_constant.fixed_value') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 50.2. Fixed Value Is Required: FALSE&nbsp;&nbsp;&nbsp;&nbsp;Type: FLOAT&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 0.1 If the solar constant is fixed, enter the value of the solar constant (W m-2). End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.solar_constant.transient_characteristics') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 50.3. Transient Characteristics Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 solar constant transient characteristics (W m-2) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.type') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "fixed" # "transient" # TODO - please enter value(s) Explanation: 51. Solar --&gt; Orbital Parameters Orbital parameters and top of atmosphere insolation characteristics 51.1. Type Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Time adaptation of orbital parameters End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.fixed_reference_date') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # TODO - please enter value(s) Explanation: 51.2. Fixed Reference Date Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: INTEGER&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Reference date for fixed orbital parameters (yyyy) End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.transient_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 51.3. Transient Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Description of transient orbital parameters End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.orbital_parameters.computation_method') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "Berger 1978" # "Laskar 2004" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 51.4. Computation Method Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Method used for computing orbital parameters. End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.solar.insolation_ozone.solar_ozone_impact') # PROPERTY VALUE: # Set as follows: DOC.set_value(value) # Valid Choices: # True # False # TODO - please enter value(s) Explanation: 52. Solar --&gt; Insolation Ozone Impact of solar insolation on stratospheric ozone 52.1. Solar Ozone Impact Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: BOOLEAN&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Does top of atmosphere insolation impact on stratospheric ozone? End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.volcanos.overview') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # TODO - please enter value(s) Explanation: 53. Volcanos Characteristics of the implementation of volcanoes 53.1. Overview Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: STRING&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 Overview description of the implementation of volcanic effects in the atmosphere End of explanation # PROPERTY ID - DO NOT EDIT ! DOC.set_id('cmip6.atmos.volcanos.volcanoes_treatment.volcanoes_implementation') # PROPERTY VALUE: # Set as follows: DOC.set_value("value") # Valid Choices: # "high frequency solar constant anomaly" # "stratospheric aerosols optical thickness" # "Other: [Please specify]" # TODO - please enter value(s) Explanation: 54. Volcanos --&gt; Volcanoes Treatment Treatment of volcanoes in the atmosphere 54.1. Volcanoes Implementation Is Required: TRUE&nbsp;&nbsp;&nbsp;&nbsp;Type: ENUM&nbsp;&nbsp;&nbsp;&nbsp;Cardinality: 1.1 How volcanic effects are modeled in the atmosphere. End of explanation
7,394
Given the following text description, write Python code to implement the functionality described below step by step Description: Lecture 8 Step1: In this example, we switched the ordering of the arguments between the two function calls; consequently, the ordering of the arguments inside the function were also flipped. Hence, positional Step2: As you can see, we used the names of the arguments from the function header itself (go back to the previous slide to see the definition of pet_names if you don't remember), setting them equal to the variable we wanted to use for that argument. Consequently, order doesn't matter--Python can see that, in both function calls, we're setting name1 = pet1 and name2 = pet2. Keyword arguments are extremely useful when it comes to default arguments. Ordering of the keyword arguments doesn't matter; that's why we can specify some of the default parameters by keyword, leaving others at their defaults, and Python doesn't complain. Here's an important distinction, though Step3: Part 2 Step4: Inside the function, the arguments are basically treated as a list Step5: Instead of one star (*) in the function header, there are two (**). And yes, instead of a list when we get to the inside of the function, now we basically have a dictionary! Arbitrary arguments (either "lists" or "dictionaries") can be mixed with positional arguments, as well as with each other. Step6: That last example had pretty much everything. We have our positional or keyword arguments (they're used as positional arguments here) in the form of firstname and lastname *nicknames is an arbitrary list of arguments, so anything beyond the positional / keyword (or default!) arguments will be considered part of this aggregate **user_info is comprised of any key-value pairs that are not among the default arguments; in this case, those are department and university (Don't worry--we won't use these mechanisms too often in this class. They're also not used too often in practice, but it's still good to know how to read them when they do show up) Part 2 Step7: If we wrote another print statement, what would print out? 10? 20? Something else? Step8: It prints 10. Before explaining, let's take another example. Step9: What would a print statement now print out? [10, 10]? [20, 10]? Something else? Step10: It prints [20, 10]. To recap, what we've seen is that We tried to modify an integer function argument. It worked inside the function, but once the function completed, the old value returned. We modified a list element of a function argument. It worked inside the function, and the changes were still there after the function ended. Explaining these seemingly-divergent behaviors is the tricky part, but to give you the punchline Step11: Whenever you operate on some_list, you have to traverse the "arrow" to the object itself, which is separate. Again, think of the house analogy Step12: Now the function has finished; if we print out the list, what will we get? Step13: "But," you begin, "you said objects like lists are pass-by-reference, and therefore any changes made in functions are permanent!" And you'd be... mostly right. Because references are tricky little buggers. Here's the thing Step14: When it comes to more "complicated" data types--strings, lists, dictionaries, sets, tuples, generators--we have to deal with two parts Step15: Think of it this way Step16: Notice how we called append on the variable x, and yet when we print y, we see the 4 there as well! This is because x and y are both references that point to the same object. As such, if we reassign x to point to something else, y will still point to the first list.
Python Code: def pet_names(name1, name2): print("Pet 1: ", name1) print("Pet 2: ", name2) pet1 = "King" pet2 = "Reginald" pet_names(pet1, pet2) # pet1 variable, then pet2 variable pet_names(pet2, pet1) # notice we've switched the order in which they're passed to the function Explanation: Lecture 8: Functions II CSCI 1360E: Foundations for Informatics and Analytics Overview and Objectives In the previous lecture, we went over the basics of functions. Here, we'll expand a little bit on some of the finer points of function arguments that can both be useful but also be huge sources of confusion. By the end of the lecture, you should be able to: Differentiate positional arguments from keyword arguments Construct functions that take any number of arguments, in positional or key-value format Explain "pass by value" and contrast it with "pass by reference", and why certain Python types can be modified in functions while others can't Part 1: Keyword Arguments In the previous lecture we learned about positional arguments. As the name implies, position is key: End of explanation pet1 = "Rocco" pet2 = "Lucy" pet_names(name1 = pet1, name2 = pet2) pet_names(name2 = pet2, name1 = pet1) Explanation: In this example, we switched the ordering of the arguments between the two function calls; consequently, the ordering of the arguments inside the function were also flipped. Hence, positional: position matters. In contrast, Python also has keyword arguments, where order no longer matters as long as you specify the keyword. We can use the same pet_names function as before. Only this time, we'll use the names of the arguments themselves (aka, keywords): End of explanation # Here's our function with a default argument. # x comes first (required), y comes second (default) def pos_def(x, y = 10): return x + y # Here, we've specified both arguments, using the keyword format. z = pos_def(x = 10, y = 20) print(z) # We're still using the keyword format, which allows us to reverse their ordering. z = pos_def(y = 20, x = 10) print(z) # But *only* specifying the default argument is a no-no. z = pos_def(y = 20) print(z) Explanation: As you can see, we used the names of the arguments from the function header itself (go back to the previous slide to see the definition of pet_names if you don't remember), setting them equal to the variable we wanted to use for that argument. Consequently, order doesn't matter--Python can see that, in both function calls, we're setting name1 = pet1 and name2 = pet2. Keyword arguments are extremely useful when it comes to default arguments. Ordering of the keyword arguments doesn't matter; that's why we can specify some of the default parameters by keyword, leaving others at their defaults, and Python doesn't complain. Here's an important distinction, though: Default (optional) arguments are always keyword arguments, but... Positional (required) arguments MUST come before default arguments, both in the function header, and whenever you call it! In essence, you can't mix-and-match the ordering of positional and default arguments using keywords. Here's an example of this behavior in action: End of explanation def make_pizza(*toppings): print("Making a pizza with the following toppings:") for topping in toppings: print(" - ", topping) make_pizza("pepperoni") make_pizza("pepperoni", "banana peppers", "green peppers", "mushrooms") Explanation: Part 2: Passing an Arbitrary Number of Arguments There are instances where you'll want to pass in an arbitrary number of arguments to a function, a number which isn't known until the function is called and could change from call to call! On one hand, you could consider just passing in a single list, thereby obviating the need. That's more or less what actually happens here, but the syntax is a tiny bit different. Here's an example: a function which lists out pizza toppings. Note the format of the input argument(s): End of explanation def build_profile(**user_info): profile = {} for key, value in user_info.items(): # This is how you iterate through the key/value pairs of dictionaries. profile[key] = value return profile profile = build_profile(firstname = "Shannon", lastname = "Quinn", university = "UGA") print(profile) profile = build_profile(name = "Shannon Quinn", department = "Computer Science") print(profile) Explanation: Inside the function, the arguments are basically treated as a list: in fact, it is a list. So why not just make the input argument a single variable which is a list? Convenience. In some sense, it's more intuitive to the programmer calling the function to just list out a bunch of things, rather than putting them all in a list structure first. But that argument could go either way depending on the person and the circumstance, most likely. With variable-length arguments, you may very well ask: this is cool, but it doesn't seem like I can make keyword arguments work in this setting? And to that I would say, absolutely correct! So we have a slight variation to accommodate keyword arguments in the realm of including arbitrary numbers of arguments: End of explanation def build_better_profile(firstname, lastname, *nicknames, **user_info): profile = {'First Name': firstname, 'Last Name': lastname} for key, value in user_info.items(): profile[key] = value profile['Nicknames'] = nicknames return profile profile = build_better_profile("Shannon", "Quinn", "Professor", "Doctor", "Master of Science", department = "Computer Science", university = "UGA") for key, value in profile.items(): print(key, ": ", value) Explanation: Instead of one star (*) in the function header, there are two (**). And yes, instead of a list when we get to the inside of the function, now we basically have a dictionary! Arbitrary arguments (either "lists" or "dictionaries") can be mixed with positional arguments, as well as with each other. End of explanation def magic_function(x): x = 20 print("Inside function: ", x) x = 10 print("Before function: ", x) magic_function(x) Explanation: That last example had pretty much everything. We have our positional or keyword arguments (they're used as positional arguments here) in the form of firstname and lastname *nicknames is an arbitrary list of arguments, so anything beyond the positional / keyword (or default!) arguments will be considered part of this aggregate **user_info is comprised of any key-value pairs that are not among the default arguments; in this case, those are department and university (Don't worry--we won't use these mechanisms too often in this class. They're also not used too often in practice, but it's still good to know how to read them when they do show up) Part 2: Pass-by-value vs Pass-by-reference This is arguably one of the trickiest parts of programming, so please ask questions if you're having trouble. Let's start with an example to illustrate what's this is. Take the following code: End of explanation print("After function: ", x) Explanation: If we wrote another print statement, what would print out? 10? 20? Something else? End of explanation def magic_function2(x): x[0] = 20 print("Inside function: {}".format(x)) x = [10, 10] print("Before function: {}".format(x)) magic_function2(x) Explanation: It prints 10. Before explaining, let's take another example. End of explanation print("After function: ", x) Explanation: What would a print statement now print out? [10, 10]? [20, 10]? Something else? End of explanation some_list = [1, 2, 3] # some_list -> reference to my list # [1, 2, 3] -> the actual, physical list Explanation: It prints [20, 10]. To recap, what we've seen is that We tried to modify an integer function argument. It worked inside the function, but once the function completed, the old value returned. We modified a list element of a function argument. It worked inside the function, and the changes were still there after the function ended. Explaining these seemingly-divergent behaviors is the tricky part, but to give you the punchline: 1 (attempting to modify an integer argument) is an example of pass by value, in which the value of the argument is copied when the function is called, and then discarded when the function ends, hence the variable retaining its original value. 2 (attempting to modify a list argument) is an example of pass by reference, in which a reference to the list--not the list itself!--is passed to the function. This reference still points to the original list, so any changes made inside the function are also made to the original list, and therefore persist when the function is finished. StackOverflow has a great gif to represent this process in pictures. In pass by value (on the right), the cup (argument) is outright copied, so any changes made to it inside the function are made on the copy, not the original. So when the function ends and the copy vanishes, so do the edits you made on it. In pass by reference (on the left), only a reference to the cup is given to the function. This reference, however, "refers" to the original cup--as in, the original version is NOT copied!--so changes made to the reference are propagated back to the original, and therefore persist even when the function ends. What are "references"? So what are these mysterious references? Imagine you're throwing a party for some friends who have never visited your house before. They ask you for directions (or, given we live in the age of Google Maps, they ask for your home address). Rather than try to hand them your entire house, or put your physical house on Google Maps (I mean this quite literally), what do you do? You write down your home address on a piece of paper (or, realistically, send a text message). This is not your house, but it is a reference to your house. It's small, compact, and easy to give out--as opposed to your physical, literal home--while intrinsically providing a path to the real thing. So it is with references. They hearken back to ye olde computre ayge when fast memory was a precious commodity measured in kilobytes, which is not enough memory to store even the Facebook home page. It was, however, enough to store the address. These addresses, or references, would point to specific locations in the larger, much slower main memory hard disks where all the larger data objects would be saved. Scanning through larger, extremely slow hard disks looking for the object itself would be akin to driving through every neighborhood in the city of Atlanta looking for a specific house. Possible, sure, but not very efficient. Much faster to have the address in-hand and drive directly there whenever you need to. That doesn't explain the differing behavior of lists versus integers as function arguments Very astute. This has to do with a subtle but important difference in how Python passes variables of different types to functions. For the "primitive" variable types--int, float, string--they're passed by value. These are [typically] small enough to be passed directly to functions. However, in doing so, they are copied upon entering the function, and these copies vanish when the function ends, along with any changes you made to them inside the function. For the "object" variable types--lists, sets, dictionaries, NumPy arrays, generators, and pretty much anything else that builds on "primitive" types--they're passed by reference. This means you can modify the values inside these objects while you're still in the function, and those modifications will persist even after the function ends (because the original object was never copied--you were, in a sense, working directly on the original). Think of references as "arrows"--they refer to your actual objects, like lists or NumPy arrays. The name with which you refer to your object is the reference. End of explanation def set_to_none(some_list): some_list = None # sets the reference "some_list" to point at nothing print("In function: ", some_list) a_list = [1, 2, 3] print("Before function: {}".format(a_list)) set_to_none(a_list) Explanation: Whenever you operate on some_list, you have to traverse the "arrow" to the object itself, which is separate. Again, think of the house analogy: whenever you want to clean your house, you have to follow your reference to it first. This YouTube video isn't exactly the same thing, since C++ handles this much more explicitly than Python does. But if you substitute "references" for "pointers", and ignore the little code snippets, it's more or less describing precisely this concept. There's a slight wrinkle in this pass-by-value, pass-by-reference story... Using what you've learned so far, what do you think the output of this function will be? End of explanation print(a_list) Explanation: Now the function has finished; if we print out the list, what will we get? End of explanation def modify_int(x): x = 9238493 # Works as long as we're in this function...once we leave, it goes away. x = 10 modify_int(x) print(x) # Even though we set x to some other value in the function, that was only a copy Explanation: "But," you begin, "you said objects like lists are pass-by-reference, and therefore any changes made in functions are permanent!" And you'd be... mostly right. Because references are tricky little buggers. Here's the thing: everything in Python is pass-by-value. But references to non-"primitive" objects, like lists, still exist and have specific effects. Let's parse this out. We already know any "basic" data type in Python is passed by value, or copied. So any modifications we make inside a function go away outside the function (unless we return it, of course). This has not changed. End of explanation def modify_list(x): x[0] = 9238493 # Here, we're modifying a specific part of the object, so this will persist! a_list = [1, 2, 3] print(a_list) # Before modify_list(a_list) print(a_list) # After Explanation: When it comes to more "complicated" data types--strings, lists, dictionaries, sets, tuples, generators--we have to deal with two parts: the reference, and the object itself. When we pass one of the objects into a function, the reference is passed-by-value...meaning the reference is copied! But since it points to the same original object as the original reference, any modifications made to the object persist, even though the copied reference goes away after the function ends. It's like I sent out two text messages with my home address. I've copied the reference, though I clearly have not copied my house. And if a recipient deletes that text message, well--they only deleted the reference, not my house. Upshot being: to persist modifications made inside a function to an object, you have to modify the object itself, not the reference. Setting the reference to None is a modification of the reference, not the object. End of explanation x = [1, 2, 3] # Create a list, assign it to x. y = x # Assign a new variable y to x. x.append(4) # Append an element to the list x. print(y) # Print ** y ** Explanation: Think of it this way: x[0] modifies the list itself, of which there is only 1. x = None is modifying the reference to the list, of which we have only a COPY of in the function. This copy then goes away when the function ends, and we're left with the original reference, which still points to the original list! Clear as mud? Excellent! Here is one more example, which illustrates why it's better to think of Python variables as two parts: one part bucket of data (the actual object), and one part pointer to a bucket (the name). End of explanation x = 5 # reassign x print(x) print(y) # same as before! Explanation: Notice how we called append on the variable x, and yet when we print y, we see the 4 there as well! This is because x and y are both references that point to the same object. As such, if we reassign x to point to something else, y will still point to the first list. End of explanation
7,395
Given the following text description, write Python code to implement the functionality described below step by step Description: Assignment 5 This assignment has weighting $1.5$. Model tuning and evaluation Step1: Dataset We will use the Wisconsin breast cancer dataset for the following questions Step2: K-fold validation (20 points) Someone wrote the code below to conduct cross validation. Do you see anything wrong with it? And if so, correct the code and provide an explanation. Step3: Answer Problems with the original code Step4: Explanation Definition REC(recall) = TPR(true positive rate) = $\frac{TP}{TP+FN}$<br> PRE(precision) = $\frac{TP}{TP+FP}$<br> FPR(false positive rate) = $\frac{FP}{FP+TN}$<br> TP Step5: Number of classifiers (40 points) The function plot_base_error() above plots the ensemble error as a function of the base error given a fixed number of classifiers. Write another function to plot ensembe error versus different number of classifiers with a given base error. Does the ensemble error always go down with more classifiers? Why or why not? Can you improve the method ensemble_error() to produce a more reasonable plot? Answer The code for plotting is below Step6: Explanation Observations
Python Code: # Added version check for recent scikit-learn 0.18 checks from distutils.version import LooseVersion as Version from sklearn import __version__ as sklearn_version Explanation: Assignment 5 This assignment has weighting $1.5$. Model tuning and evaluation End of explanation import pandas as pd wdbc_source = 'https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data' #wdbc_source = '../datasets/wdbc/wdbc.data' df = pd.read_csv(wdbc_source, header=None) from sklearn.preprocessing import LabelEncoder X = df.loc[:, 2:].values y = df.loc[:, 1].values le = LabelEncoder() y = le.fit_transform(y) le.transform(['M', 'B']) if Version(sklearn_version) < '0.18': from sklearn.cross_validation import train_test_split else: from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = \ train_test_split(X, y, test_size=0.20, random_state=1) import matplotlib.pyplot as plt %matplotlib inline Explanation: Dataset We will use the Wisconsin breast cancer dataset for the following questions End of explanation import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.linear_model import Perceptron from sklearn.pipeline import Pipeline if Version(sklearn_version) < '0.18': from sklearn.cross_validation import StratifiedKFold else: from sklearn.model_selection import StratifiedKFold scl = StandardScaler() pca = PCA(n_components=2) # original: clf = Perceptron(random_state=1) # data preprocessing X_train_std = scl.fit_transform(X_train) X_test_std = scl.transform(X_test) X_train_pca = pca.fit_transform(X_train_std) X_test_pca = pca.transform(X_test_std) # compute the data indices for each fold if Version(sklearn_version) < '0.18': kfold = StratifiedKFold(y=y_train, n_folds=10, random_state=1) else: kfold = StratifiedKFold(n_splits=10, random_state=1).split(X_train, y_train) num_epochs = 2 scores = [[] for i in range(num_epochs)] enumerate_kfold = list(enumerate(kfold)) # new: clfs = [Perceptron(random_state=1) for i in range(len(enumerate_kfold))] for epoch in range(num_epochs): for k, (train, test) in enumerate_kfold: # original: # clf.partial_fit(X_train_std[train], y_train[train], classes=np.unique(y_train)) # score = clf.score(X_train_std[test], y_train[test]) # scores.append(score) # new: clfs[k].partial_fit(X_train_pca[train], y_train[train], classes=np.unique(y_train)) score = clfs[k].score(X_train_pca[test], y_train[test]) scores[epoch].append(score) print('Epoch: %s, Fold: %s, Class dist.: %s, Acc: %.3f' % (epoch, k, np.bincount(y_train[train]), score)) print('') # new: for epoch in range(num_epochs): print('Epoch: %s, CV accuracy: %.3f +/- %.3f' % (epoch, np.mean(scores[epoch]), np.std(scores[epoch]))) Explanation: K-fold validation (20 points) Someone wrote the code below to conduct cross validation. Do you see anything wrong with it? And if so, correct the code and provide an explanation. End of explanation from sklearn.metrics import roc_curve, precision_recall_curve, auc from scipy import interp from sklearn.linear_model import LogisticRegression pipe_lr = Pipeline([('scl', StandardScaler()), ('pca', PCA(n_components=2)), ('clf', LogisticRegression(penalty='l2', random_state=0, C=100.0))]) # intentionally use only 2 features to make the task harder and the curves more interesting X_train2 = X_train[:, [4, 14]] X_test2 = X_test[:, [4, 14]] if Version(sklearn_version) < '0.18': cv = StratifiedKFold(y_train, n_folds=3, random_state=1) else: cv = list(StratifiedKFold(n_splits=3, random_state=1).split(X_train, y_train)) fig = plt.figure(figsize=(7, 5)) # ************************************** # ROC - 2 Features # ************************************** print ("ROC Curve - 2 Features") mean_tpr = 0.0 mean_fpr = np.linspace(0, 1, 100) all_tpr = [] for i, (train, test) in enumerate(cv): probas = pipe_lr.fit(X_train2[train], y_train[train]).predict_proba(X_train2[test]) fpr, tpr, thresholds = roc_curve(y_train[test], probas[:, 1], pos_label=1) mean_tpr += interp(mean_fpr, fpr, tpr) #mean_tpr[0] = 0.0 roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i+1, roc_auc)) mean_tpr /= len(cv) mean_tpr[0] = 0.0 mean_tpr[-1] = 1.0 mean_auc = auc(mean_fpr, mean_tpr) plt.plot(mean_fpr, mean_tpr, 'k--', label='mean ROC (area = %0.2f)' % mean_auc, lw=2) plt.plot([0, 1], [0, 1], linestyle='--', color=(0.6, 0.6, 0.6), label='random guessing') plt.plot([0, 0, 1], [0, 1, 1], lw=2, linestyle=':', color='black', label='perfect performance') plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('false positive rate') plt.ylabel('true positive rate') plt.title('Receiver Operator Characteristic') plt.legend(loc='lower left', bbox_to_anchor=(1, 0)) plt.tight_layout() # plt.savefig('./figures/roc.png', dpi=300) plt.show() # ************************************** # ROC - All Features # ************************************** print ("ROC Curve - All Features") mean_tpr = 0.0 mean_fpr = np.linspace(0, 1, 100) all_tpr = [] for i, (train, test) in enumerate(cv): probas = pipe_lr.fit(X_train[train], y_train[train]).predict_proba(X_train[test]) fpr, tpr, thresholds = roc_curve(y_train[test], probas[:, 1], pos_label=1) mean_tpr += interp(mean_fpr, fpr, tpr) #mean_tpr[0] = 0.0 roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i+1, roc_auc)) mean_tpr /= len(cv) mean_tpr[0] = 0.0 mean_tpr[-1] = 1.0 mean_auc = auc(mean_fpr, mean_tpr) plt.plot(mean_fpr, mean_tpr, 'k--', label='mean ROC (area = %0.2f)' % mean_auc, lw=2) plt.plot([0, 1], [0, 1], linestyle='--', color=(0.6, 0.6, 0.6), label='random guessing') plt.plot([0, 0, 1], [0, 1, 1], lw=2, linestyle=':', color='black', label='perfect performance') plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('false positive rate') plt.ylabel('true positive rate') plt.title('Receiver Operator Characteristic') plt.legend(loc='lower left', bbox_to_anchor=(1, 0)) plt.tight_layout() # plt.savefig('./figures/roc.png', dpi=300) plt.show() # ************************************** # Precision-Recall - 2 Features # ************************************** print ("Precision Recall Curve - 2 Features") mean_pre = 0.0 mean_rec = np.linspace(0, 1, 100) all_pre = [] for i, (train, test) in enumerate(cv): probas = pipe_lr.fit(X_train2[train], y_train[train]).predict_proba(X_train2[test]) ## note that the return order is precision, recall pre, rec, thresholds = precision_recall_curve(y_train[test], probas[:, 1], pos_label=1) ## flip the recall and precison array mean_pre += interp(mean_rec, np.flipud(rec), np.flipud(pre)) pr_auc = auc(rec, pre) plt.plot(rec, pre, lw=1, label='PR fold %d (area = %0.2f)' % (i+1, pr_auc)) mean_pre /= len(cv) mean_auc = auc(mean_rec, mean_pre) plt.plot(mean_rec, mean_pre, 'k--', label='mean PR (area = %0.2f)' % mean_auc, lw=2) # random classifier: a line of Positive/(Positive+Negative) # here for simplicity, we set it to be Positive/(Positive+Negative) of fold 3 plt.plot(mean_rec, [pre[0] for i in range(len(mean_rec))], linestyle='--', label='random guessing of fold 3', color=(0.6, 0.6, 0.6)) # perfect performance: y = 1 for x in [0, 1]; when x = 1; down to the random guessing line plt.plot([0, 1, 1], [1, 1, pre[0]], lw=2, linestyle=':', color='black', label='perfect performance') plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('recall') plt.ylabel('precision') plt.title('Precision-Recall') plt.legend(loc='lower left', bbox_to_anchor=(1, 0)) plt.tight_layout() # plt.savefig('./figures/roc.png', dpi=300) plt.show() # ************************************** # Precision-Recall - All Features # ************************************** print ("Precision Recall Curve - All Features") mean_pre = 0.0 mean_rec = np.linspace(0, 1, 100) all_pre = [] for i, (train, test) in enumerate(cv): probas = pipe_lr.fit(X_train[train], y_train[train]).predict_proba(X_train[test]) ## note that the return order is precision, recall pre, rec, thresholds = precision_recall_curve(y_train[test], probas[:, 1], pos_label=1) ## flip the recall and precison array mean_pre += interp(mean_rec, np.flipud(rec), np.flipud(pre)) pr_auc = auc(rec, pre) plt.plot(rec, pre, lw=1, label='PR fold %d (area = %0.2f)' % (i+1, pr_auc)) mean_pre /= len(cv) mean_auc = auc(mean_rec, mean_pre) plt.plot(mean_rec, mean_pre, 'k--', label='mean PR (area = %0.2f)' % mean_auc, lw=2) # random classifier: a line of Positive/(Positive+Negative) # here for simplicity, we set it to be Positive/(Positive+Negative) of fold 3 plt.plot(mean_rec, [pre[0] for i in range(len(mean_rec))], linestyle='--', label='random guessing of fold 3', color=(0.6, 0.6, 0.6)) # perfect performance: y = 1 for x in [0, 1]; when x = 1; down to the random guessing line plt.plot([0, 1, 1], [1, 1, pre[0]], lw=2, linestyle=':', color='black', label='perfect performance') plt.xlim([-0.05, 1.05]) plt.ylim([-0.05, 1.05]) plt.xlabel('recall') plt.ylabel('precision') plt.title('Precision-Recall') plt.legend(loc='lower left', bbox_to_anchor=(1, 0)) plt.tight_layout() # plt.savefig('./figures/roc.png', dpi=300) plt.show() Explanation: Answer Problems with the original code: Use partial fit for all folds, which results in dependent training and thus cumulative learning.<br> Due to problem 1, we the CV accuracy is incorrect, and not able to show score for every epoch. <br> There are two major changes: We create a list of Perceptrons, each corresponds to one fold. Within each fold, we run partial fit for a given number of epochs. <br> Also, we create a list of accuracy scores, each corresponds to one epoch. Within each epoch, we append scores of all folds. <br> There is one minor change: To enable PCA, we change X_train_std into X_train_pca.<br> Precision-recall curve (40 points) We have plotted ROC (receiver operator characteristics) curve for the breast cancer dataset. Plot the precision-recall curve for the same data set using the same experimental setup. What similarities and differences you can find between ROC and precision-recall curves? You can find more information about precision-recall curve online such as: http://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_curve.html Answer End of explanation from scipy.misc import comb import math import numpy as np def ensemble_error(num_classifier, base_error): k_start = math.ceil(num_classifier/2) probs = [comb(num_classifier, k)*(base_error**k)*((1-base_error)**(num_classifier-k)) for k in range(k_start, num_classifier+1)] return sum(probs) import matplotlib.pyplot as plt %matplotlib inline def plot_base_error(ensemble_error_func, num_classifier, error_delta): error_range = np.arange(0.0, 1+error_delta, error_delta) ensemble_errors = [ensemble_error_func(num_classifier=num_classifier, base_error=error) for error in error_range] plt.plot(error_range, ensemble_errors, label = 'ensemble error', linewidth=2) plt.plot(error_range, error_range, label = 'base error', linestyle = '--', linewidth=2) plt.xlabel('base error') plt.ylabel('base/ensemble error') plt.legend(loc='best') plt.grid() plt.show() num_classifier = 11 error_delta = 0.01 base_error = 0.25 print(ensemble_error(num_classifier=num_classifier, base_error=base_error)) plot_base_error(ensemble_error, num_classifier=num_classifier, error_delta=error_delta) Explanation: Explanation Definition REC(recall) = TPR(true positive rate) = $\frac{TP}{TP+FN}$<br> PRE(precision) = $\frac{TP}{TP+FP}$<br> FPR(false positive rate) = $\frac{FP}{FP+TN}$<br> TP: Actual Class $A$, test result $A$<br> FP: Actual Class $B$, test result $A$<br> TN: Actual Class $B$, test result $B$<br> FN: Actual Class $A$, test result $B$<br> Similarities When number of features increases, in ROC curve, true positive rate is close to 1 regardless of false positive rate (not equals 0); in Precison-Recall curve, precision is close to 1 regardless of recall (not equals 1).<br> The training results are better than random guessing in this example.<br> Differences For monotonicity ROC curve: As false positive rate increase, the true positive rate generally increases, and the effect is huger when number of features is small.<br> This is because when avoid classifying class $B$ as class $A$, we actually increase the probability of successfully classifying class $A$ as class $A$, which increases the true positive rate.<br> Actually, the curve is almost concave. The image below illustrates the reason. <img src="https://github.com/irsisyphus/Pictures/raw/master/ML-Exercises/roc.png"><br> Please keep online to view the picture. Reference: https://upload.wikimedia.org/wikipedia/commons/5/5c/ROCfig.PNG<br><br> Precision-Recall curve: As recall increases, the precision generally decreases, especially when number of features is small.<br> This is because when we try to increase recall (reduce false negative), we avoid classifying samples with acutal class $A$ as class $B$, that is, we classify samples similar to class $A$ as class $A$. However, whis will also increase the probability of classifying samples with acutal class $B$ (but tested to be similar to class $A$) as class $A$, which is FP.<br> Notice that when FP increases, it is not necessary that precision decrease since TP also increases. Only when the ratio $\frac{TP}{TP+FP}$ drops, which is often the general case when number of features is small, precision drops. The image below illustrates the reason. <img width=50% src="https://github.com/irsisyphus/Pictures/raw/master/ML-Exercises/pre-rec.png"><br> Please keep online to view the picture. Reference: http://numerical.recipes/CS395T/lectures2008/17-ROCPrecisionRecall.pdf For random guessing ROC curve: true positive rate = false positive rate. This is because the propotion of TP in (TP+FN) equals the propotion of FP in (FP+TN), because declaring a result has no dependence on the actuall class label for random guessing. Precision-Recall curve: the random guessing is a horizontal line with y = P/(P+N) for given boundary of P and N, which varies with cases. (In this example, we choose P/(P+N) of fold 3 for simplicity). For perfect performance ROC curve: The perfect performance is (0, 0) -> (0, 1) -> (1, 1). We aim to have result in the "top-left" corner to obtain low false positive rate and high true positive rate. Precision-Recall curve: The perfect performance is (0, 1) -> (1, 1) -> (1, P/(P+N)). We aim to have result in the "top-right" corner to obtain high recall and high precision. Ensemble learning We have used the following code to compute and plot the ensemble error from individual classifiers for binary classification: End of explanation def plot_num_classifier(ensemble_error_func, max_num_classifier, base_error): num_classifiers = range(1, max_num_classifier+1) ensemble_errors = [ensemble_error_func(num_classifier = num_classifier, base_error=base_error) for num_classifier in num_classifiers] plt.plot(num_classifiers, ensemble_errors, label = 'ensemble error', linewidth = 2) plt.plot(range(max_num_classifier), [base_error]*max_num_classifier, label = 'base error', linestyle = '--', linewidth=2) plt.xlabel('num classifiers') plt.ylabel('ensemble error') plt.xlim([1, max_num_classifier]) plt.ylim([0, 1]) plt.title('base error %.2f' % base_error) plt.legend(loc='best') plt.grid() plt.show() max_num_classifiers = 20 base_error = 0.25 plot_num_classifier(ensemble_error, max_num_classifier=max_num_classifiers, base_error=base_error) Explanation: Number of classifiers (40 points) The function plot_base_error() above plots the ensemble error as a function of the base error given a fixed number of classifiers. Write another function to plot ensembe error versus different number of classifiers with a given base error. Does the ensemble error always go down with more classifiers? Why or why not? Can you improve the method ensemble_error() to produce a more reasonable plot? Answer The code for plotting is below: End of explanation def better_ensemble_error(num_classifier, base_error): k_start = math.ceil(num_classifier/2) probs = [comb(num_classifier, k)*(base_error**k)*((1-base_error)**(num_classifier-k)) for k in range(k_start, num_classifier+1)] if num_classifier % 2 == 0: probs.append(-0.5*comb(num_classifier, k_start)*(base_error**k_start)*((1-base_error)**(num_classifier-k_start))) return sum(probs) plot_num_classifier(better_ensemble_error, max_num_classifier=max_num_classifiers, base_error=base_error) Explanation: Explanation Observations: The ensemble error DOES NOT ALWAYS go down with more classifiers.<br> Overall, the ensemble error declines as the number of classifiers increases. However, when the number of calssifiers $N = 2k$, the error is much higher than $N = 2k-1$ and $2k+1$. Reason: This is because when a draw comes, i.e. $K$ subclassifiers are wrong and $K$ subclassifiers are correct, it is considered as "wrong prediction" by the original function. Describe a better algorithm for computing the ensemble error. End of explanation
7,396
Given the following text description, write Python code to implement the functionality described below step by step Description: This notebook will use a simple model to predict ratings for a user, anime pair Step1: Let's plot the objective and see how it decreases. Step2: So by 50 iterations, the model hits a bend and from there we see incremental improvement. We can see quite clearly that this model does not overfit. It's a very simple model (that likely underfits the data) and we use L2 regularization, so to that end it's not surprising at all. But it's good to confirm anyway. Let's test the model on our test data now.
Python Code: import matplotlib.pyplot as plt import matplotlib %matplotlib inline matplotlib.style.use('seaborn') from animerec.data import get_data users, anime = get_data() from sklearn.model_selection import train_test_split train, test = train_test_split(users, test_size = 0.1) #let's split up the dataset into a train and test set. train, valid = train_test_split(train, test_size = 0.2) #let's split up the dataset into a train and valid set. from animerec.data import remove_users train = remove_users(train, 10) #define validation set valid_users = valid['user_id'] valid_anime = valid['anime_id'] valid_ratings = valid['rating'] #initialize some local variables nUsers = len(train.user_id.unique()) nAnime = len(train.anime_id.unique()) # we'll need some data structures in order to vectorize computations from collections import defaultdict user_ids = train.user_id item_ids = train.anime_id user_index = defaultdict(lambda: -1) # maps a user_id to the index in the bias term. item_index = defaultdict(lambda: -1) # maps an anime_id to the index in the bias term. counter = 0 for user in user_ids: if user_index[user] == -1: user_index[user] = counter counter += 1 counter = 0 for item in item_ids: if item_index[item] == -1: item_index[item] = counter counter += 1 import tensorflow as tf y = tf.cast(tf.constant(train['rating'].as_matrix(), shape=[len(train),1]), tf.float32) def objective(alpha, Bi, Bu, y, lam): #construct the full items and user matrix. Bi_full = tf.gather(Bi, train.anime_id.map(lambda _id: item_index[_id]).as_matrix()) Bu_full = tf.gather(Bu, train.user_id.map(lambda _id: user_index[_id]).as_matrix()) alpha_full = tf.tile(alpha, (len(train), 1)) return tf.reduce_sum(abs(alpha_full+Bi_full+Bu_full-y)) + lam * (tf.reduce_sum(Bi**2) + tf.reduce_sum(Bu**2)) #initialize alpha, Bi, Bu alpha = tf.Variable(tf.constant([6.9], shape=[1, 1])) Bi = tf.Variable(tf.constant([0.0]*nAnime, shape=[nAnime, 1])) Bu = tf.Variable(tf.constant([0.0]*nUsers, shape=[nUsers, 1])) optimizer = tf.train.AdamOptimizer(0.01) obj = objective(alpha, Bi, Bu, y, 1) trainer = optimizer.minimize(obj) sess = tf.Session() sess.run(tf.global_variables_initializer()) tLoss = [] vLoss = [] prev = 10e10 for iteration in range(500): cvalues = sess.run([trainer, obj]) print("objective = " + str(cvalues[1])) tLoss.append(cvalues[1]) if not iteration % 5: cAlpha, cBi, cBu, cLoss = sess.run([alpha, Bi, Bu, obj]) indices = valid_users.map(lambda x: user_index[x]) bu = indices.map(lambda x: 0.0 if x == -1 else float(cBu[x])) indices = valid_anime.map(lambda x: item_index[x]) bi = indices.map(lambda x: 0.0 if x == -1 else float(cBi[x])) preds = bu + bi + float(cAlpha) MAE = 1.0/len(valid) * sum(abs(valid_ratings-preds)) vLoss.append(MAE) if MAE > prev: break else: prev = MAE cAlpha, cBi, cBu, cLoss = sess.run([alpha, Bi, Bu, obj]) print("\nFinal train loss is ", cLoss) Explanation: This notebook will use a simple model to predict ratings for a user, anime pair: rating(user, item) = offset + user_bias + item_bias Put simply, the predicted rating is the sum of three terms. The user_bias refers to whether a user is predisposed to rating higher or lower. For example, a user who gives all perfect scores will have a highly positive user_bias term. The item_bias is similar, except it refers to an anime. So a highly rated anime will have a highly positive anime_bias term. Finally, there's an offset to adjust for the general anime score. This will be initialized to 6.9 (the mean rating in the exploratory analysis) but since this is being run for only users with 10 or more ratings, that number is only a rough guess. Note that this entire program is optimized for users with 10 or more ratings, but the validation and test sets may include users with fewer ratings. The objective function will be mean absolute error (MAE) with L2 regularization. This model is implemented in tensorflow, just for the sake of practice. Broadly speaking, this code is organized into two parts. In the first part, I do some basic data prep: 1) Import some packages for plotting 2) Use my animerec package to get data 3) split the data into train, test, and validation sets 4) Define some data structures that'll be used to vectorize computations. In the second part, I use tensorflow to implement this simple model, using a validation set for early stopping. I then see the performance on the test set. End of explanation fig, ax1 = plt.subplots() plt.title('Linear model performance vs. iterations') ax1.plot(tLoss, 'b-') ax1.set_xlabel('Training Iterations') ax1.set_ylabel('Train Loss') ax2 = ax1.twinx() ax2.plot(range(0, len(vLoss)*5, 5), vLoss, 'r.') ax2.set_ylabel('Validation Classification MAE') fig.tight_layout() Explanation: Let's plot the objective and see how it decreases. End of explanation test_users = test['user_id'] test_anime = test['anime_id'] test_ratings = test['rating'] indices = test_users.map(lambda x: user_index[x]) bu = indices.map(lambda x: 0.0 if x == -1 else float(cBu[x])) indices = test_anime.map(lambda x: item_index[x]) bi = indices.map(lambda x: 0.0 if x == -1 else float(cBi[x])) preds = bu + bi + float(cAlpha) MAE = 1.0/len(test) * sum(abs(test_ratings-preds)) print ('MAE on test set is: ', float(MAE)) sess.close() Explanation: So by 50 iterations, the model hits a bend and from there we see incremental improvement. We can see quite clearly that this model does not overfit. It's a very simple model (that likely underfits the data) and we use L2 regularization, so to that end it's not surprising at all. But it's good to confirm anyway. Let's test the model on our test data now. End of explanation
7,397
Given the following text description, write Python code to implement the functionality described below step by step Description: <a id='top'> </a> Author Step1: Cosmic-ray composition clustering Table of contents Define analysis free parameters Data preprocessing Fitting random forest Fraction correctly identified Spectrum Unfolding Feature importance Step2: Define analysis free parameters [ back to top ] Whether or not to train on 'light' and 'heavy' composition classes, or the individual compositions Step3: Get composition classifier pipeline Step4: Define energy binning for this analysis Step5: Data preprocessing [ back to top ] 1. Load simulation/data dataframe and apply specified quality cuts 2. Extract desired features from dataframe 3. Get separate testing and training datasets 4. Feature transformation Step6: Run classifier over training and testing sets to get an idea of the degree of overfitting
Python Code: %load_ext watermark %watermark -u -d -v -p numpy,matplotlib,scipy,pandas,sklearn,mlxtend Explanation: <a id='top'> </a> Author: James Bourbeau End of explanation import sys sys.path.append('/home/jbourbeau/cr-composition') print('Added to PYTHONPATH') %matplotlib inline from __future__ import division, print_function from collections import defaultdict import itertools import numpy as np from scipy import interp import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.metrics import accuracy_score, confusion_matrix, roc_curve, auc from sklearn.model_selection import cross_val_score, ShuffleSplit, KFold, StratifiedKFold from sklearn.cluster import KMeans from mlxtend.feature_selection import SequentialFeatureSelector as SFS import composition as comp import composition.analysis.plotting as plotting color_dict = {'light': 'C0', 'heavy': 'C1', 'total': 'C2', 'P': 'C0', 'He': 'C1', 'O': 'C3', 'Fe':'C4'} Explanation: Cosmic-ray composition clustering Table of contents Define analysis free parameters Data preprocessing Fitting random forest Fraction correctly identified Spectrum Unfolding Feature importance End of explanation comp_class = True comp_list = ['light', 'heavy'] if comp_class else ['P', 'He', 'O', 'Fe'] Explanation: Define analysis free parameters [ back to top ] Whether or not to train on 'light' and 'heavy' composition classes, or the individual compositions End of explanation pipeline_str = 'xgboost' pipeline = comp.get_pipeline(pipeline_str) Explanation: Get composition classifier pipeline End of explanation energybins = comp.analysis.get_energybins() Explanation: Define energy binning for this analysis End of explanation sim_train, sim_test = comp.preprocess_sim(comp_class=comp_class, return_energy=True) data = comp.preprocess_data(comp_class=comp_class, return_energy=True) Explanation: Data preprocessing [ back to top ] 1. Load simulation/data dataframe and apply specified quality cuts 2. Extract desired features from dataframe 3. Get separate testing and training datasets 4. Feature transformation End of explanation clf_name = pipeline.named_steps['classifier'].__class__.__name__ print('=' * 30) print(clf_name) pipeline.fit(sim_train.X, sim_train.y) train_pred = pipeline.predict(sim_train.X) train_acc = accuracy_score(sim_train.y, train_pred) print('Training accuracy = {:.2%}'.format(train_acc)) test_pred = pipeline.predict(sim_test.X) test_acc = accuracy_score(sim_test.y, test_pred) print('Testing accuracy = {:.2%}'.format(test_acc)) # scores = cross_val_score( # estimator=pipeline, X=sim_train.X, y=sim_train.y, cv=3, n_jobs=10) # print('CV score: {:.2%} (+/- {:.2%})'.format(scores.mean(), scores.std())) print('=' * 30) splitter = ShuffleSplit(n_splits=1, test_size=.5, random_state=2) for set1_index, set2_index in splitter.split(sim_train.X): sim_train1 = sim_train[set1_index] sim_train2 = sim_train[set2_index] kmeans = KMeans(n_clusters=4) pred = kmeans.fit_predict(sim_train.X) MC_comp_mask = {} for composition in comp_list: MC_comp_mask[composition] = sim_train.le.inverse_transform(sim_train.y) == composition MC_comp_mask light_0 = np.sum(pred[MC_comp_mask['light']] == 0)/np.sum(MC_comp_mask['light']) light_1 = np.sum(pred[MC_comp_mask['light']] == 1)/np.sum(MC_comp_mask['light']) print('percent light cluster in 0 = {}'.format(light_0)) print('percent light cluster in 1 = {}'.format(light_1)) heavy_0 = np.sum(pred[MC_comp_mask['heavy']] == 0)/np.sum(MC_comp_mask['heavy']) heavy_1 = np.sum(pred[MC_comp_mask['heavy']] == 1)/np.sum(MC_comp_mask['heavy']) print('percent heavy cluster in 0 = {}'.format(heavy_0)) print('percent heavy cluster in 1 = {}'.format(heavy_1)) Explanation: Run classifier over training and testing sets to get an idea of the degree of overfitting End of explanation
7,398
Given the following text description, write Python code to implement the functionality described below step by step Description: Drive LEDs with the Raspberry Pi GPIO pins This notebook will walk you through using the Raspberry Pi General Purpose Input/Output (GPIO) pins to make a LED light burn. The GPIO pins are the 40 (numbered) pins that electronic components can be connected to. Before actually using them, we have to agree with our Raspberry Pi how to address the pins and we do that with the setmode function. IPython Instructions Step1: BCM is the numbering that is engraved on the Raspberry Pi case we use and that you can also find back on the printed Pinout schema (BCM stands for Broadcom, the company that produces the Raspberry Pi chip). Watch out 1 Step2: With all GPIO settings done, we can put pin GPIO18 to work. To do this, we import the time library, so we can use its time related functionality Step3: Note
Python Code: #load GPIO library import RPi.GPIO as GPIO #Set BCM (Broadcom) mode for the pin numbering GPIO.setmode(GPIO.BCM) Explanation: Drive LEDs with the Raspberry Pi GPIO pins This notebook will walk you through using the Raspberry Pi General Purpose Input/Output (GPIO) pins to make a LED light burn. The GPIO pins are the 40 (numbered) pins that electronic components can be connected to. Before actually using them, we have to agree with our Raspberry Pi how to address the pins and we do that with the setmode function. IPython Instructions: Place your cursor in the cell below and press Shift+Enter or click the Play button in the toolbar above to execute the code in the cell. Shift + Enter: Execute the cell and jump to the next one Ctrl + Enter: Execute the cell, but stay in the current one Alt + Enter: Execute the cell and create a new one below the current one As long as a [*] appears to the left os the cell, it is still running. As soon as the code ends, a number appears and any output generated by the code is printed under the cell. End of explanation # If we assign the name 'PIN' to the pin number we intend to use, we can reuse it later # yet still change easily in one place PIN = 18 # set pin as output GPIO.setup(PIN, GPIO.OUT) Explanation: BCM is the numbering that is engraved on the Raspberry Pi case we use and that you can also find back on the printed Pinout schema (BCM stands for Broadcom, the company that produces the Raspberry Pi chip). Watch out 1: a LED is a diode, which means it is important to send current through in the correct direction. So the difference between the long and short end of the LED connectors is important. Watch out 2: if left to their own devices, LEDs will consume more current than is good for them and will subsequently burn out. If it's a bad day, the Raspberry Pi might get damaged because of it... To prevent this, we need to add a resistor (in series!) Connect the long end of the LED with GPIO18 on the Pi. Place a low value resistor (220-360 Ohm) in series with the LED. Illustration: <img src="LED01.png" height="300"/> Then all that is left in our setup is to tell the Raspberry Pi that we intend to use GPIO18 as output, so we can change the voltage on that pin. This way we can send current on the pin to turn on the LED. End of explanation import time # Repeat forever while True: # turn off pin 18 GPIO.output(PIN, 0) # wait for half a second time.sleep(.5) # turn on pin 18 GPIO.output(PIN, 1) # wait for half a second time.sleep(.5) #... and again ... Explanation: With all GPIO settings done, we can put pin GPIO18 to work. To do this, we import the time library, so we can use its time related functionality: time.sleep(x) is a function that tells the computer to wait for a number of seconds before continuing with the next instruction. End of explanation #reset the GPIO PIN = 18 GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(PIN, GPIO.OUT) # Create PWM object and set its frequency in Hz (cycles per second) led = GPIO.PWM(PIN, 60) # Start PWM signal led.start(0) try: while True: # increase duty cycle by 1% for dc in range(0, 101, 1): led.ChangeDutyCycle(dc) time.sleep(0.05) # and down again ... for dc in range(100, -1, -1): led.ChangeDutyCycle(dc) time.sleep(0.05) except KeyboardInterrupt: pass led.stop() GPIO.cleanup() Explanation: Note: To stop the running code, you can: click the stop button in the toolbar above choose Kernel > Interrupt from the dropdown menu use a keyboard shortcut: type i twice (only while the cell is in "command mode" (indicated by a grey border). Pulse Width Modulation So we can now send binary commands ("on" and "off"), but the GPIO library also allows us to simulate an analog signal, also called PWM (Pulse Width Modulation). A PWM signal consists of a quick succession of on and off signals where the ratio between the total on and the total off time indicates the pseudo-analog level between 0 and 1. E.g. 75% of the time "on" == a duty cycle of 75% == an analog signal of 0.75 (or 75% of the max amplitude) In the case of a LED, this will manifest itself as a stronger or weaker light being emitted from the LED. In different motors this can be the rotating speed or the angle to which the axis moves (or is held). End of explanation
7,399
Given the following text description, write Python code to implement the functionality described below step by step Description: Использование глубокого обучения в NLP Смотрите в этой серии Step1: Познакомимся с данными Бывший kaggle-конкурс про выявление нежелательного контента. Описание конкурса есть тут - https Step2: Step3: Сбалансируем выборку Выборка смещена в сторону незаблокированных объявлений 4 миллиона объявлений и только 250 тысяч заблокированы. Давайте просто выберем случайные 250 тысяч незаблокированных объявлений и сократим выборку до полумилиона. В последствии можно испоьзовать более умные способы сбалансировать выборку Если у вас слабый ПК и вы видите OutOfMemory, попробуйте уменьшить размер выборки до 100 000 примеров Алсо если вы не хотите ждать чтения всех данных каждый раз - сохраните уменьшенную выборку и читайте её Step4: Токенизируем примеры Сначала соберём словарь всех возможных слов. Поставим каждому слову в соответствие целое число - его id Step5: Вырежем редкие токены Step6: Заменим слова на их id Для каждого описания установим максимальную длину. * Если описание больше длины - обрежем, если меньше - дополним нулями. * Таким образом, у нас получится матрица размера (число объявлений)x(максимальная длина) * Элемент под индексами i,j - номер j-того слова i-того объявления Step7: Пример формата данных Step8: Как вы видите, всё довольно грязно. Посмотрим, сожрёт ли это нейронка Нетекстовые признаки Часть признаков не являются строками текста Step9: Поделим данные на обучение и тест Step10: Сохраним данные [опционально] В этот момент вы можете сохранить все НУЖНЫЕ данные на диск и перезапусатить тетрадку, после чего считать их - чтобы выкинуть всё ненужное. рекомендуется, если у вас мало памяти Для этого нужно один раз выполнить эту клетку с save_prepared_data=True. После этого можно начинать тетрадку с ЭТОЙ табы в режиме read_prepared_data=True Step11: Поучим нейронку Поскольку у нас есть несколько источников данных, наша нейронная сеть будет немного отличаться от тех, что вы тренировали раньше. Отдельный вход для заголовка свёртка + global max pool или RNN Отдельный вход для описания свёртка + global max pool или RNN Отдельный вход для категориальных признаков обычные полносвязные слои или какие-нибудь трюки Всё это нужно как-то смешать - например, сконкатенировать Выход - обычный двухклассовый выход 1 сигмоидальный нейрон и binary_crossentropy 2 нейрона с softmax и categorical_crossentropy - то же самое, что 1 сигмоидальный 1 нейрон без нелинейности (lambda x Step12: Архитектура нейронной сети Step13: Целевая функция и обновления весов Делаем всё стандартно Step14: Чтобы оценивать качество сети, в которой есть элемент случайности Dropout, например, Нужно отдельно вычислить ошибку для случая, когда dropout выключен (deterministic = True) К слову, неплохо бы убедиться, что droput нам вообще нужен Step15: Скомпилируем функции обучения и оценки качества Step16: Главный цикл обучения Всё как обычно - в цикле по минибатчам запускаем функцию обновления весов. Поскольку выборка огромна, а чашки чая хватает в среднем на 100к примеров, будем на каждой эпохе пробегать только часть примеров. Step17: Что можно покрутить? batch_size - сколько примеров обрабатывается за 1 раз Чем больше, тем оптимизация стабильнее, но тем и медленнее на начальном этапе Возможно имеет смысл увеличивать этот параметр на поздних этапах обучения minibatches_per_epoch - количество минибатчей, после которых эпоха принудительно завершается Не влияет на обучение - при малых значениях просто будет чаще печататься отчёт Ставить 10 или меньше имеет смысл только для того, чтобы убедиться, что ваша сеть не упала с ошибкой n_epochs - сколько всего эпох сеть будет учиться Никто не отменял n_epochs = 10**10 и остановку процесса вручную по возвращению с дачи/из похода. Tips Step18: Final evaluation Оценим качество модели по всей тестовой выборке.
Python Code: low_RAM_mode = True very_low_RAM = False #если у вас меньше 3GB оперативки, включите оба флага import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline Explanation: Использование глубокого обучения в NLP Смотрите в этой серии: * Простые способы работать с текстом, bag of words * Word embedding и... нет, это не word2vec * Как сделать лучше? Текстовые свёрточные сети * Совмещение нескольких различных источников данных * Решение +- реальной задачи нейронками За помощь в организации свёрточной части спасибо Ирине Гольцман NLTK Для работы этого семинара вам потреюуется nltk v3.2 Важно, что именно v3.2, чтобы правильно работал токенизатор Устаовить/обновиться до неё можно командой * sudo pip install --upgrade nltk==3.2 * Если у вас старый pip, предварительно нужно сделать sudo pip install --upgrade pip Если у вас нет доступа к этой версии - просто убедитесь, что токены в token_counts включают русские слова. Для людей со слабым ПК Этот семинар можно выполнить, имея относительно скромную машину (<= 4Gb RAM) Для этого существует специальный флаг "low_RAM_mode" - если он True, семинар работает в режиме экономии вашей памяти Если у вас 8GB и больше - проблем с памятью возникнуть не должно Если включить режим very_low_ram, расход мамяти будет ещё меньше, но вам может быть более трудно научить нейронку. End of explanation if not low_RAM_mode: # Если у вас много оперативки df = pd.read_csv("avito_train.tsv",sep='\t') else: #Если у вас меньше 4gb оперативки df = pd.read_csv("avito_train_1kk.tsv",sep='\t') print df.shape, df.is_blocked.mean() df[:5] Explanation: Познакомимся с данными Бывший kaggle-конкурс про выявление нежелательного контента. Описание конкурса есть тут - https://www.kaggle.com/c/avito-prohibited-content Скачать Если много RAM, * Из данных конкурса (вкладка Data) нужно скачать avito_train.tsv и распаковать в папку с тетрадкой Если мало RAM, * Cкачайте прореженную выборку отсюда * Пожатая https://yadi.sk/d/l0p4lameqw3W8 * Непожатая https://yadi.sk/d/I1v7mZ6Sqw2WK Много разных признаков: * 2 вида текста - заголовок и описание * Много специальных фичей - цена, количество телефонов/ссылок/e-mail адресов * Категория и субкатегория - как ни странно, категориальные фичи * Аттрибуты - много категориальных признаков Нужно предсказать всего 1 бинарный признак - есть ли в рекламе нежелательный контент. * Под нежелательным контентом понимается криминал, прон, афера, треска и прочие любимые нами темы. * Да, если присмотреться к заблокированным объявлениям, можно потерять аппетит и сон на пару дней. * Однако профессия аналитика данных обязывает вас смотреть на данные. * А кто сказал, что будет легко? Data Science - опасная профессия. End of explanation print "Доля заблокированных объявлений",df.is_blocked.mean() print "Всего объявлений:",len(df) Explanation: End of explanation #downsample < выдели подвыборку, в которой отрицательных примеров примерно столько же, сколько положительных> df = <уменьшенная подвыборка> print "Доля заблокированных объявлений:",df.is_blocked.mean() print "Всего объявлений:",len(df) assert df.is_blocked.mean() < 0.51 assert df.is_blocked.mean() > 0.49 assert len(df) <= 560000 print "All tests passed" #прореживаем данные ещё в 2 раза, если памяти не хватает if very_low_ram: data = data[::2] Explanation: Сбалансируем выборку Выборка смещена в сторону незаблокированных объявлений 4 миллиона объявлений и только 250 тысяч заблокированы. Давайте просто выберем случайные 250 тысяч незаблокированных объявлений и сократим выборку до полумилиона. В последствии можно испоьзовать более умные способы сбалансировать выборку Если у вас слабый ПК и вы видите OutOfMemory, попробуйте уменьшить размер выборки до 100 000 примеров Алсо если вы не хотите ждать чтения всех данных каждый раз - сохраните уменьшенную выборку и читайте её End of explanation from nltk.tokenize import RegexpTokenizer from collections import Counter,defaultdict tokenizer = RegexpTokenizer(r"\w+") #словарь для всех токенов token_counts = Counter() #все заголовки и описания all_texts = np.hstack([df.description.values,df.title.values]) #считаем частоты слов for s in all_texts: if type(s) is not str: continue s = s.decode('utf8').lower() tokens = tokenizer.tokenize(s) for token in tokens: token_counts[token] +=1 Explanation: Токенизируем примеры Сначала соберём словарь всех возможных слов. Поставим каждому слову в соответствие целое число - его id End of explanation #распределение частот слов - большинство слов встречаются очень редко - для нас это мусор _=plt.hist(token_counts.values(),range=[0,50],bins=50) #возьмём только те токены, которые встретились хотя бы 10 раз в обучающей выборке #информацию о том, сколько раз встретился каждый токен, можно найти в словаре token_counts min_count = 10 tokens = <список слов(ключей) из token_counts, которые встретились в выборке не менее min_count раз> token_to_id = {t:i+1 for i,t in enumerate(tokens)} null_token = "NULL" token_to_id[null_token] = 0 print "Всего токенов:",len(token_to_id) if len(token_to_id) < 30000: print "Алярм! Мало токенов. Проверьте, есть ли в token_to_id юникодные символы, если нет - обновите nltk или возьмите другой токенизатор" if len(token_to_id) > 1000000: print "Алярм! Много токенов. Если вы знаете, что делаете - всё ок, если нет - возможно, вы слишком слабо обрезали токены по количеству" Explanation: Вырежем редкие токены End of explanation def vectorize(strings, token_to_id, max_len=150): token_matrix = [] for s in strings: if type(s) is not str: token_matrix.append([0]*max_len) continue s = s.decode('utf8').lower() tokens = tokenizer.tokenize(s) token_ids = map(lambda token: token_to_id.get(token,0), tokens)[:max_len] token_ids += [0]*(max_len - len(token_ids)) token_matrix.append(token_ids) return np.array(token_matrix) desc_tokens = vectorize(df.description.values,token_to_id,max_len = 150) title_tokens = vectorize(df.title.values,token_to_id,max_len = 15) Explanation: Заменим слова на их id Для каждого описания установим максимальную длину. * Если описание больше длины - обрежем, если меньше - дополним нулями. * Таким образом, у нас получится матрица размера (число объявлений)x(максимальная длина) * Элемент под индексами i,j - номер j-того слова i-того объявления End of explanation print "Размер матрицы:",title_tokens.shape for title, tokens in zip(df.title.values[:3],title_tokens[:3]): print title,'->', tokens[:10],'...' Explanation: Пример формата данных End of explanation #Возьмём числовые признаки df_numerical_features = df[["phones_cnt","emails_cnt","urls_cnt","price"]] #Возьмём one-hot encoding категорий товара. #Для этого можно использовать DictVectorizer (или другой ваш любимый препроцессор) from sklearn.feature_extraction import DictVectorizer categories = [] for cat_str, subcat_str in df[["category","subcategory"]].values: cat_dict = {"category":cat_str,"subcategory":subcat_str} categories.append(cat_dict) vectorizer = DictVectorizer(sparse=False) cat_one_hot = vectorizer.fit_transform(categories) cat_one_hot = pd.DataFrame(cat_one_hot,columns=vectorizer.feature_names_) df_non_text = pd.merge( df_numerical_features,cat_one_hot,on = np.arange(len(cat_one_hot)) ) del df_non_text["key_0"] Explanation: Как вы видите, всё довольно грязно. Посмотрим, сожрёт ли это нейронка Нетекстовые признаки Часть признаков не являются строками текста: цена, количество телефонов, категория товара. Их можно обработать отдельно. End of explanation #целевая переменная - есть заблокирован ли контент target = df.is_blocked.values.astype('int32') #закодированное название title_tokens = title_tokens.astype('int32') #закодированное описание desc_tokens = desc_tokens.astype('int32') #все нетекстовые признаки df_non_text = df_non_text.astype('float32') #поделим всё это на обучение и тест from sklearn.cross_validation import train_test_split data_tuple = train_test_split(title_tokens,desc_tokens,df_non_text.values,target) title_tr,title_ts,desc_tr,desc_ts,nontext_tr,nontext_ts,target_tr,target_ts = data_tuple Explanation: Поделим данные на обучение и тест End of explanation save_prepared_data = True #сохранить read_prepared_data = False #cчитать #за 1 раз данные можно либо записать, либо прочитать, но не и то и другое вместе assert not (save_prepared_data and read_prepared_data) if save_prepared_data: print "Сохраняем подготовленные данные... (может занять до 3 минут)" import pickle with open("preprocessed_data.pcl",'w') as fout: pickle.dump(data_tuple,fout) with open("token_to_id.pcl",'w') as fout: pickle.dump(token_to_id,fout) print "готово" elif read_prepared_data: print "Читаем сохранённые данные..." import pickle with open("preprocessed_data.pcl",'r') as fin: data_tuple = pickle.load(fin) title_tr,title_ts,desc_tr,desc_ts,nontext_tr,nontext_ts,target_tr,target_ts = data_tuple with open("token_to_id.pcl",'r') as fin: token_to_id = pickle.load(fin) #повторно импортируем библиотеки, чтобы было удобно перезапускать тетрадку с этой клетки import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline print "готово" Explanation: Сохраним данные [опционально] В этот момент вы можете сохранить все НУЖНЫЕ данные на диск и перезапусатить тетрадку, после чего считать их - чтобы выкинуть всё ненужное. рекомендуется, если у вас мало памяти Для этого нужно один раз выполнить эту клетку с save_prepared_data=True. После этого можно начинать тетрадку с ЭТОЙ табы в режиме read_prepared_data=True End of explanation #загрузим библиотеки import lasagne from theano import tensor as T import theano #3 входа и 1 выход title_token_ids = T.matrix("title_token_ids",dtype='int32') desc_token_ids = T.matrix("desc_token_ids",dtype='int32') categories = T.matrix("categories",dtype='float32') target_y = T.ivector("is_blocked") Explanation: Поучим нейронку Поскольку у нас есть несколько источников данных, наша нейронная сеть будет немного отличаться от тех, что вы тренировали раньше. Отдельный вход для заголовка свёртка + global max pool или RNN Отдельный вход для описания свёртка + global max pool или RNN Отдельный вход для категориальных признаков обычные полносвязные слои или какие-нибудь трюки Всё это нужно как-то смешать - например, сконкатенировать Выход - обычный двухклассовый выход 1 сигмоидальный нейрон и binary_crossentropy 2 нейрона с softmax и categorical_crossentropy - то же самое, что 1 сигмоидальный 1 нейрон без нелинейности (lambda x: x) и hinge loss End of explanation title_inp = lasagne.layers.InputLayer((None,title_tr.shape[1]),input_var=title_token_ids) descr_inp = lasagne.layers.InputLayer((None,desc_tr.shape[1]),input_var=desc_token_ids) cat_inp = lasagne.layers.InputLayer((None,nontext_tr.shape[1]), input_var=categories) # Описание descr_nn = lasagne.layers.EmbeddingLayer(descr_inp,input_size=len(token_to_id)+1,output_size=128) #поменять порядок осей с [batch, time, unit] на [batch,unit,time], чтобы свёртки шли по оси времени, а не по нейронам descr_nn = lasagne.layers.DimshuffleLayer(descr_nn, [0,2,1]) # 1D свёртка на ваш вкус descr_nn = lasagne.layers.Conv1DLayer(descr_nn,num_filters=?,filter_size=?) # максимум по времени для каждого нейрона descr_nn = lasagne.layers.GlobalPoolLayer(descr_nn,pool_function=T.max) #А ещё можно делать несколько параллельных свёрток разного размера или стандартный пайплайн #1dconv -> 1d max pool ->1dconv и в конце global pool # Заголовок title_nn = <текстовая свёрточная сеть для заголовков (title_inp)> # Нетекстовые признаки cat_nn = <простая полносвязная сеть для нетекстовых признаков (cat_inp)> nn = <объединение всех 3 сетей в одну (например lasagne.layers.concat) > nn = lasagne.layers.DenseLayer(nn,1024) nn = lasagne.layers.DropoutLayer(nn,p=0.05) nn = lasagne.layers.DenseLayer(nn,1,nonlinearity=lasagne.nonlinearities.linear) Explanation: Архитектура нейронной сети End of explanation #Все обучаемые параметры сети weights = lasagne.layers.get_all_params(nn,trainable=True) #Обычное предсказание нейронки prediction = lasagne.layers.get_output(nn)[:,0] #функция потерь для prediction loss = lasagne.objectives.binary_hinge_loss(prediction,target_y,delta = 1.0).mean() #Шаг оптимизации весов updates = <Ваш любимый метод оптимизации весов> Explanation: Целевая функция и обновления весов Делаем всё стандартно: получаем предсказание считаем функцию потерь вычисляем обновления весов компилируем итерацию обучения и оценки весов Hinge loss $ L_i = \max(0, \delta - t_i p_i) $ Важный параметр - delta - насколько глубоко пример должен быть в правильном классе, чтобы перестать нас волновать В описании функции в документации может быть что-то про ограничения на +-1 - не верьте этому - главное, чтобы в функции по умолчанию стоял флаг binary = True End of explanation #Предсказание нейронки без учёта dropout и прочего шума - если он есть det_prediction = lasagne.layers.get_output(nn,deterministic=True)[:,0] #функция потерь для det_prediction det_loss = lasagne.objectives.binary_hinge_loss(det_prediction,target_y,delta = 1.0).mean() Explanation: Чтобы оценивать качество сети, в которой есть элемент случайности Dropout, например, Нужно отдельно вычислить ошибку для случая, когда dropout выключен (deterministic = True) К слову, неплохо бы убедиться, что droput нам вообще нужен End of explanation train_fun = theano.function([desc_token_ids,title_token_ids,categories,target_y],[loss,prediction],updates = updates) eval_fun = theano.function([desc_token_ids,title_token_ids,categories,target_y],[det_loss,det_prediction]) Explanation: Скомпилируем функции обучения и оценки качества End of explanation #average precision at K from oracle import APatK, score # наш старый знакомый - итератор по корзинкам - теперь умеет работать с произвольным числом каналов (название, описание, категории, таргет) def iterate_minibatches(*arrays,**kwargs): batchsize=kwargs.get("batchsize",100) shuffle = kwargs.get("shuffle",True) if shuffle: indices = np.arange(len(arrays[0])) np.random.shuffle(indices) for start_idx in range(0, len(arrays[0]) - batchsize + 1, batchsize): if shuffle: excerpt = indices[start_idx:start_idx + batchsize] else: excerpt = slice(start_idx, start_idx + batchsize) yield [arr[excerpt] for arr in arrays] Explanation: Главный цикл обучения Всё как обычно - в цикле по минибатчам запускаем функцию обновления весов. Поскольку выборка огромна, а чашки чая хватает в среднем на 100к примеров, будем на каждой эпохе пробегать только часть примеров. End of explanation from sklearn.metrics import roc_auc_score, accuracy_score n_epochs = 100 batch_size = 100 minibatches_per_epoch = 100 for i in range(n_epochs): #training epoch_y_true = [] epoch_y_pred = [] b_c = b_loss = 0 for j, (b_desc,b_title,b_cat, b_y) in enumerate( iterate_minibatches(desc_tr,title_tr,nontext_tr,target_tr,batchsize=batch_size,shuffle=True)): if j > minibatches_per_epoch:break loss,pred_probas = train_fun(b_desc,b_title,b_cat,b_y) b_loss += loss b_c +=1 epoch_y_true.append(b_y) epoch_y_pred.append(pred_probas) epoch_y_true = np.concatenate(epoch_y_true) epoch_y_pred = np.concatenate(epoch_y_pred) print "Train:" print '\tloss:',b_loss/b_c print '\tacc:',accuracy_score(epoch_y_true,epoch_y_pred>0.) print '\tauc:',roc_auc_score(epoch_y_true,epoch_y_pred) print '\tap@k:',APatK(epoch_y_true,epoch_y_pred,K = int(len(epoch_y_pred)*0.025)+1) #evaluation epoch_y_true = [] epoch_y_pred = [] b_c = b_loss = 0 for j, (b_desc,b_title,b_cat, b_y) in enumerate( iterate_minibatches(desc_ts,title_ts,nontext_ts,target_ts,batchsize=batch_size,shuffle=True)): if j > minibatches_per_epoch: break loss,pred_probas = eval_fun(b_desc,b_title,b_cat,b_y) b_loss += loss b_c +=1 epoch_y_true.append(b_y) epoch_y_pred.append(pred_probas) epoch_y_true = np.concatenate(epoch_y_true) epoch_y_pred = np.concatenate(epoch_y_pred) print "Val:" print '\tloss:',b_loss/b_c print '\tacc:',accuracy_score(epoch_y_true,epoch_y_pred>0.) print '\tauc:',roc_auc_score(epoch_y_true,epoch_y_pred) print '\tap@k:',APatK(epoch_y_true,epoch_y_pred,K = int(len(epoch_y_pred)*0.025)+1) print "Если ты видишь это сообщение, самое время сделать резервную копию ноутбука. \nНет, честно, здесь очень легко всё сломать" Explanation: Что можно покрутить? batch_size - сколько примеров обрабатывается за 1 раз Чем больше, тем оптимизация стабильнее, но тем и медленнее на начальном этапе Возможно имеет смысл увеличивать этот параметр на поздних этапах обучения minibatches_per_epoch - количество минибатчей, после которых эпоха принудительно завершается Не влияет на обучение - при малых значениях просто будет чаще печататься отчёт Ставить 10 или меньше имеет смысл только для того, чтобы убедиться, что ваша сеть не упала с ошибкой n_epochs - сколько всего эпох сеть будет учиться Никто не отменял n_epochs = 10**10 и остановку процесса вручную по возвращению с дачи/из похода. Tips: Если вы выставили небольшой minibatches_per_epoch, качество сети может сильно скакать возле 0.5 на первых итерациях, пока сеть почти ничему не научилась. На первых этапах попытки стоит сравнивать в первую очередь по AUC, как по самой стабильной метрике. Метрика Average Precision at top 2.5% (APatK) - сама по себе очень нестабильная на маленьких выборках, поэтому её имеет смысл оценивать на на всех примерах (см. код ниже). Для менее, чем 10000 примеров она вовсе неинформативна. Для сравнения методов оптимизации и регуляризаторов будет очень полезно собирать метрики качества после каждой итерации и строить график по ним после обучения Как только вы убедились, что сеть не упала - имеет смысл дать ей покрутиться - на стандартном ноутбуке хотя бы пару часов. End of explanation #evaluation epoch_y_true = [] epoch_y_pred = [] b_c = b_loss = 0 for j, (b_desc,b_title,b_cat, b_y) in enumerate( iterate_minibatches(desc_ts,title_ts,nontext_ts,target_ts,batchsize=batch_size,shuffle=True)): loss,pred_probas = eval_fun(b_desc,b_title,b_cat,b_y) b_loss += loss b_c +=1 epoch_y_true.append(b_y) epoch_y_pred.append(pred_probas) epoch_y_true = np.concatenate(epoch_y_true) epoch_y_pred = np.concatenate(epoch_y_pred) final_accuracy = accuracy_score(epoch_y_true,epoch_y_pred>0) final_auc = roc_auc_score(epoch_y_true,epoch_y_pred) final_apatk = APatK(epoch_y_true,epoch_y_pred,K = int(len(epoch_y_pred)*0.025)+1) print "Scores:" print '\tloss:',b_loss/b_c print '\tacc:',final_accuracy print '\tauc:',final_auc print '\tap@k:',final_apatk score(final_accuracy,final_auc,final_apatk) Explanation: Final evaluation Оценим качество модели по всей тестовой выборке. End of explanation