markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
As well as accessing positions in lists using indexing, you can use *slices* on lists. This uses the colon character, `:`, to stand in for 'from the beginning' or 'until the end' (when only appearing once). For instance, to print just the last two entries, we would use the index `-2:` to mean from the second-to-last on... | print(list_example[:3])
print(list_example[-3:]) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Slicing can be even more elaborate than that because we can jump entries using a second colon. Here's a full example that begins at the second entry (remember the index starts at 0), runs up until the second-to-last entry (exclusive), and jumps every other entry inbetween (range just produces a list of integers from th... | list_of_numbers = list(range(1, 11))
start = 1
stop = -1
step = 2
print(list_of_numbers[start:stop:step]) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
A handy trick is that you can print a reversed list entirely using double colons: | print(list_of_numbers[::-1]) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
What's amazing about lists is that they can hold any type, including other lists! Here's a valid example of a list that's got a lot going on: | wacky_list = [
3.1415,
16,
["five", 4, 3],
"Hello World!",
True,
None,
{"key": "value", "key2": "value2"},
]
wacky_list | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Can you identify the types of each of the entries (and entries of entries)? OperatorsAll of the basic operators you see in mathematics are available to use: `+` for addition, `-` for subtraction, `*` for multiplication, `**` for powers, `/` for division, and `%` for modulo. These work as you'd expect on numbers. But th... | string_one = "This is an example "
string_two = "of string concatenation"
string_full = string_one + string_two
print(string_full) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
It works for lists too: | list_one = ["apples", "oranges"]
list_two = ["pears", "satsumas"]
list_full = list_one + list_two
print(list_full) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Perhaps more surprisingly, you can multiply strings! | string = "apples, "
print(string * 3) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Below is a table of the basic arithmetic operations.| Operator | Description || :------: | :--------------: || `+` | addition || `-` | subtraction || `*` | multiplication || `/` | division || `**` | exponentiation || `//` | integer division / floor division || ... | string = "cheesecake"
print(string[-4:]) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Both lists and strings will also allow you to use the `len` command to get their length: | string = "cheesecake"
print("String has length:")
print(len(string))
list_of_numbers = range(1, 20)
print("List of numbers has length:")
print(len(list_of_numbers)) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Strings have type `string` and can be defined by single or double quotes, eg `string = "cheesecake"` would have been equally valid above.There are various functions built into Python to help you work with strings that are particularly useful for cleaning messy data. For example, imagine you have a variable name like 'T... | string = "This Is /A Variable "
string = string.replace("/", "").rstrip().lower()
print(string) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
The steps above replace the character '/', strip out whitespace on the right hand-side of the string, and put everything in lower case. The brackets after the words signify that a function has been applied; we'll see more of functions later.You'll often want to output one type of data as another, and Python generally k... | value = 20
sqrt_val = 20 ** 0.5
print(f"The square root of {value:d} is {sqrt_val:.2f}") | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
The formatting command `:d` is an instruction to treat `value` like an integer, while `:.2f` is an instruction to print it like a float with 2 decimal places.```{note}f-strings are only available in Python 3.6+``` Booleans and conditionsSome of the most important operations you will perform are with `True` and `False` ... | not True | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
as you would expect.Conditions are expressions that evaluate as booleans. A simple example is `10 == 20`. The `==` is an operator that compares the objects on either side and returns `True` if they have the same *values*--though be careful using it with different data types.Here's a table of conditions that return bool... | boolean_condition = 10 == 20
print(boolean_condition) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
The real power of conditions comes when we start to use them in more complex examples. Some of the keywords that evaluate conditions are `if`, `else`, `and`, `or`, `in`, `not`, and `is`. Here's an example showing how some of these conditional keywords work: | name = "Ada"
score = 99
if name == "Ada" and score > 90:
print("Ada, you achieved a high score.")
if name == "Smith" or score > 90:
print("You could be called Smith or have a high score")
if name != "Smith" and score > 90:
print("You are not called Smith and you have a high score") | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
All three of these conditions evaluate as True, and so all three messages get printed. Given that `==` and `!=` test for equality and not equal, respectively, you may be wondering what the keywords `is` and `not` are for. Remember that everything in Python is an object, and that values can be assigned to objects. `==` ... | name_list = ["Ada", "Adam"]
name_list_two = ["Ada", "Adam"]
# Compare values
print(name_list == name_list_two)
# Compare objects
print(name_list is name_list_two) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
One of the most useful conditional keywords is `in`. I must use this one ten times a day to pick out a variable or make sure something is where it's supposed to be. | name_list = ["Lovelace", "Smith", "Hopper", "Babbage"]
print("Lovelace" in name_list)
print("Bob" in name_list) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
The opposite is `not in`.Finally, one conditional construct you're bound to use at *some* point, is the `if`...`else` structure: | score = 98
if score == 100:
print("Top marks!")
elif score > 90 and score < 100:
print("High score!")
elif score > 10 and score <= 90:
pass
else:
print("Better luck next time.") | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Note that this does nothing if the score is between 11 and 90, and prints a message otherwise.One nice feature of Python is that you can make multiple boolean comparisons in a single line. | a, b = 3, 6
1 < a < b < 20 | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Casting variablesSometimes we need to explicitly cast a value from one type to another. We can do this using functions like `str()`, `int()`, and `float()`. If you try these, Python will do its best to interpret the input and convert it to the output type you'd like and, if they can't, the code will throw a great big ... | orig_number = 4.39898498
type(orig_number) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Now we cast it to an int: | mod_number = int(orig_number)
mod_number | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
which looks like it became an integer, but we can double check that: | type(mod_number) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Tuples and (im)mutabilityA tuple is an object that is defined by parentheses and entries that are separated by commas, for example `(15, 20, 32)`. (They are of type `tuple`.) As such, they have a lot in common with lists-but there's a big and important difference.Tuples are immutable, while lists are mutable. This mea... | x = 10
if x > 2:
print("x is greater than 2") | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
When functions, conditional clauses, or loops are combined together, they each cause an *increase* in the level of indentation. Here's a double indent. | if x > 2:
print("outer conditional cause")
for i in range(4):
print("inner loop") | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
The standard practice for indentation is that each sub-statement should be indented by 4 spaces. It can be hard to keep track of these but, as usual, Visual Studio Code has you covered. Go to Settings (the cog in the bottom left-hand corner, then click Settings) and type 'Whitespace' into the search bar. Under 'Editor:... | name_list = ["Lovelace", "Smith", "Pigou", "Babbage"]
for name in name_list:
print(name) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
prints out a name until all names have been printed out. A useful trick with for loops is the `enumerate` keyword, which runs through an index that keeps track of the items in a list: | name_list = ["Lovelace", "Smith", "Hopper", "Babbage"]
for i, name in enumerate(name_list):
print(f"The name in position {i} is {name}") | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Remember, Python indexes from 0 so the first entry of `i` will be zero. But, if you'd like to index from a different number, you can: | for i, name in enumerate(name_list, start=1):
print(f"The name in position {i} is {name}") | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
High-level languages like Python and R do not get *compiled* into highly performant machine code ahead of being run, unlike C++ and FORTRAN. What this means is that although they are much less unwieldy to use, some types of operation can be very slow--and `for` loops are particularly cumbersome. (Although you may not n... | number_list = range(1, 40)
divide_list = [x for x in number_list if x % 3 == 0]
print(divide_list) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Or if we only wanted to pick out names that end in 'Smith': | names_list = ["Joe Bloggs", "Adam Smith", "Sandra Noone", "leonara smith"]
smith_list = [x for x in names_list if "smith" in x.lower()]
print(smith_list) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Note how we used 'smith' rather than 'Smith' and then used `lower()` to ensure we matched names regardless of the case they are written in. We can even do a whole `if` ... `else` construct *inside* a list comprehension: | names_list = ["Joe Bloggs", "Adam Smith", "Sandra Noone", "leonara smith"]
smith_list = [x if "smith" in x.lower() else "Not Smith!" for x in names_list]
print(smith_list) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Many of the constructs we've seen can be combined. For instance, there is no reason why we can't have a nested or repeated list comprehension, and, perhaps more surprisingly, sometimes these are useful! | first_names = ["Ada", "Adam", "Grace", "Charles"]
last_names = ["Lovelace", "Smith", "Hopper", "Babbage"]
names_list = [x + " " + y for x, y in zip(first_names, last_names)]
print(names_list) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
The `zip` keyword is doing this magic; think of it like a zipper, bringing an element of each list together in turn. It can also be used directly in a for loop: | for first_nm, last_nm in zip(first_names, last_names):
print(first_nm, last_nm) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Finally, an even more extreme use of list comprehensions can deliver nested structures: | first_names = ["Ada", "Adam"]
last_names = ["Lovelace", "Smith"]
names_list = [[x + " " + y for x in first_names] for y in last_names]
print(names_list) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
This gives a nested structure that (in this case) iterates over `first_names` first, and then `last_names`. If you'd like to learn more about list comprehensions, check out these [short video tutorials](https://calmcode.io/comprehensions/introduction.html). While loops`while` loops continue to execute code until their ... | n = 10
while n > 0:
print(n)
n -= 1
print("execution complete") | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
NB: in case you're wondering what `-=` does, it's a compound assignment that sets the left-hand side equal to the left-hand side minus the right-hand side.You can use the keyword `break` to break out of a while loop, for example if it's reached a certain number of iterations without converging. DictionariesAnother buil... | fruit_dict = {
"Jazz": "Apple",
"Owari": "Satsuma",
"Seto": "Satsuma",
"Pink Lady": "Apple",
}
# Add an entry
fruit_dict.update({"Cox": "Apple"})
variety_list = ["Jazz", "Jazz", "Seto", "Cox"]
fruit_list = [fruit_dict[x] for x in variety_list]
print(fruit_list) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
From an input list of varieties, we get an output list of their associated fruits. Another good trick to know with dictionaries is that you can iterate through their keys and values: | for key, value in fruit_dict.items():
print(key + " maps into " + value) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Running on emptyBeing able to create empty containers is sometimes useful. The commands to create empty lists, tuples, dictionaries, and sets are `lst = []`, `tup=()`, `dic={}`, and `st = set()` respectively. FunctionsIf you're an economist, I hardly need to tell you what a function is. In coding, it's much the same a... | def welcome_message(name):
return f"Hello {name}, and welcome!"
# Without indentation, this code is not part of function
name = "Ada"
output_string = welcome_message(name)
print(output_string) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
One powerful feature of functions is that we can define defaults for the input arguments. Let's see that in action by defining a default value for `name`, along with multiple outputs--a hello message and a score. | def score_message(score, name="student"):
"""This is a doc-string, a string describing a function.
Args:
score (float): Raw score
name (str): Name of student
Returns:
str: A hello message.
float: A normalised score.
"""
norm_score = (score - 50) / 10
return f"Hell... | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
In that last example, you'll notice that I added some text to the function. This is a doc-string. It's there to help users (and, most likely, future you) to understand what the function does. Let's see how this works in action by calling `help` on the `score_message` function: | help(score_message) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
ScopeScope refers to what parts of your code can see what other parts. If you define a variable inside a function, the rest of your code won't be able to 'see' it or use it. For example, here's a function that creates a variable and then an example of calling that variable:```pythondef var_func(): str_variable = 'H... | def var_func():
str_variable = "Hello World!"
return str_variable
returned_var = var_func()
print(returned_var) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Or, if you only want to modify a variable, you can declare the variable before the function is run, pass it into the function, and then return it. Using packages and modulesWe already saw how to install packages in the previous chapter: using `pip install packagename` or `conda install packagename` on the command line.... | import numpy as np
from numpy.linalg import inv
matrix = np.array([[4.0, 2.0, 4.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]])
print("Matrix:")
print(matrix)
inv_mat = inv(matrix)
print("Inverse:")
print(inv_mat) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
We could have imported all of **numpy** using `from numpy import *` but this is considered bad practice as it fills our 'namespace' with function names that might clash with other packages and it's less easy to parse which package's function is doing what. R also relies heavily on imported libraries but uses a differen... | import networkx as nx
import matplotlib.pyplot as plt
graph = nx.DiGraph()
graph.add_edges_from(
[
("Utility script", "code file a"),
("Utility script", "code file b"),
("code file a", "code file c"),
("code file b", "code file c"),
("Utility script", "code file c"),
]
)... | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
How would this work in practice? We would define a file 'utilities.py' that had the following:```python Contents of utilities.py filedef really_useful_func(number): return number*10```Then, in 'code_script_a.py': | import utilities as utils
print(utils.really_useful_func(20)) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
An alternative is to *just* import the function we want, with the name we want: | from utilities import really_useful_func as ru_fn
print(ru_fn(30)) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Another important example is the case where you want to run 'utilities.py' as a script, but still want to borrow functions from it to run in other scripts. There's a way to do this. Let's change utilities.py to```python Contents of utilities.py filedef really_useful_func(number): return number*10def default_func(): ... | plus_one = lambda x: x + 1
plus_one(3) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
For a one-liner function that has a name it's actually better practice here to use `def plus_one(x): return x + 1`, so you shouldn't see this form of lambda function too much in the wild. However, you are likely to see lambda functions being used with dataframes and other objects. For example, if you had a dataframe wi... | import pandas as pd
df = pd.DataFrame(
data=[["hello my blah is Ada"], ["hElLo mY blah IS Adam"]],
columns=["strings"],
dtype="string",
)
df["strings"].apply(lambda x: x.title().replace("Blah", "Name")) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
More complex lambda functions can be constructed, eg `lambda x, y, z: x + y + z`. One of the best use cases of lambdas is when you *don't* want to go to the trouble of declaring a function. For example, let's say you want to compose a series of functions and you want to specify those functions in a list, one after the ... | number = 1
for func in [lambda x: x + 1, lambda x: x * 2, lambda x: x ** 2]:
number = func(number)
print(number) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Note that people often use `x` by convention, but there's nothing to stop you writing `lambda horses: horses**2` (except the looks your co-authors will give you). If you want to learn more about lambda functions, check out these [short video tutorials](https://calmcode.io/lambda/introduction.html). Splat and splatty-sp... | def add(a, b):
return a + b
print(add(5, 10))
func_args = (6, 11)
print(add(*func_args)) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
The splat operator, `*`, unpacks the variable `func_args` into two different function arguments. Splatty-splat unpacks dictionaries into keyword arguments (aka kwargs): | def function_with_kwargs(a, x=0, y=0, z=0):
return a + x + y + z
print(function_with_kwargs(5))
kwargs = {"x": 3, "y": 4, "z": 5}
print(function_with_kwargs(5, **kwargs)) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Perhaps most surprisingly of all, we can use the splat operator *in the definition of a function*. For example: | def sum_elements(*elements):
return sum(*elements)
nums = (1, 2, 3)
print(sum_elements(nums))
more_nums = (1, 2, 3, 4, 5)
print(sum_elements(more_nums)) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
To learn more about args and kwargs, check out these [short video tutorials](https://calmcode.io/args-kwargs/introduction.html). TimeLet's do a quick dive into how to deal with dates and times. This is only going to scratch the surface, but should give a sense of what's possible.The built-in library that deals with dat... | from datetime import datetime
now = datetime.now()
print(now) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
You can pick out bits of the datetime that you need: | day = now.day
month = now.month
year = now.year
hour = now.hour
minute = now.minute
print(f"{year}/{month}/{day}, {hour}:{minute}") | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
To add or subtract time to a datetime, use `timedelta`: | from datetime import timedelta
new_time = now + timedelta(days=365, hours=5)
print(new_time) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
To take the difference of two dates: | from datetime import date
new_year = date(year=2022, month=1, day=1)
time_till_ny = new_year - date.today()
print(f"{time_till_ny.days} days until New Year") | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Note that date and datetime are two different types of objects-a datetime includes information on the date and time, whereas a date does not. Reading and writing filesAlthough most applications in economics will probably use the **pandas** package to read and write tabular data, it's sometimes useful to know how to rea... | α = 15
β = 30
print(α / β) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
You can swap variables in a single assignment: | a = 10
b = "This is a string"
a, b = b, a
print(a) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
**iterools** offers counting, repeating, cycling, chaining, and slicing. Here's a cycling example that uses the `next` keyword to get the next iteraction: | from itertools import cycle
lorrys = ["red lorry", "yellow lorry"]
lorry_iter = cycle(lorrys)
print(next(lorry_iter))
print(next(lorry_iter))
print(next(lorry_iter)) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
**iterools** also offers products, combinations, combinations with replacement, and permutations. Here are the combinations of 'abc' of length 2: | from itertools import combinations
print(list(combinations("abc", 2))) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Find out what the date is! (Can pass a timezone as an argument.) | from datetime import date
print(date.today()) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Because functions are just objects, you can iterate over them just like any other object: | functions = [str.isdigit, str.islower, str.isupper]
raw_str = "asdfaa3fa"
for str_func in functions:
print(f"Function name: {str_func.__name__}, value is:")
print(str_func(raw_str)) | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Functions can be defined recursively. For instance, the Fibonacci sequence is defined such that $ a_n = a_{n-1} + a_{n-2} $ for $ n>1 $. | def fibonacci(n):
if n < 0:
print("Please enter n>0")
return 0
elif n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
[fibonacci(i) for i in range(10)] | _____no_output_____ | MIT | code-basics.ipynb | lukestein/coding-for-economists |
Animate samples from a Gaussian distributionThis notebook demonstrates how to use the functionality in `ProbNum-Evaluation` to animate samples from a Gaussian distribution. | from probnumeval import visual
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42) | _____no_output_____ | MIT | docs/source/tutorials/animate_gaussian_distributions.ipynb | anukaal/probnum-evaluation |
As a toy example, let us consider animate a sample from a Gaussian process on 15 grid points with `N =5` frames. The number of grid points determines the dimension of the underlying Normal distribution, therefore this variable is called `dim` in `ProbNum-Evaluation`. | dim = 15
num_frames = 5 | _____no_output_____ | MIT | docs/source/tutorials/animate_gaussian_distributions.ipynb | anukaal/probnum-evaluation |
For didactic reasons, let us set `endpoint` to `True`, which means that the final sample is the first sample. | states_gp = visual.animate_with_periodic_gp(dim, num_frames, endpoint=True)
states_sphere = visual.animate_with_great_circle_of_unitsphere(dim, num_frames, endpoint=True) | _____no_output_____ | MIT | docs/source/tutorials/animate_gaussian_distributions.ipynb | anukaal/probnum-evaluation |
The output of the `animate_with*` function is a sequence of (pseudo-) samples from a standard Normal distribution. | fig, axes = plt.subplots(dpi=150, ncols=num_frames, nrows=2, sharey=True, sharex=True, figsize=(num_frames*2, 2), constrained_layout=True)
for ax in axes.flatten():
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
for state_sphere, state_gp, ax in zip(states_sphere, states_gp, axe... | _____no_output_____ | MIT | docs/source/tutorials/animate_gaussian_distributions.ipynb | anukaal/probnum-evaluation |
These can be turned into samples from a multivariate Normal distribution $N(m, K)$ via the formula $u \mapsto m + \sqrt{K} u$ | def k(s, t):
return np.exp(-(s - t)**2/0.1)
locations = np.linspace(0, 1, dim)
cov = k(locations[:, None], locations[None, :])
cov_cholesky = np.linalg.cholesky(cov + 1e-12 * np.eye(dim))
# From the "right", because the states have shape (N, d).
samples_sphere = states_sphere @ cov_cholesky.T
samples_gp = states_... | _____no_output_____ | MIT | docs/source/tutorials/animate_gaussian_distributions.ipynb | anukaal/probnum-evaluation |
The resulting (pseudo-)samples "move through the sample space" in a continuous way for both, the periodic GP and the sphere. | fig, axes = plt.subplots(dpi=150, ncols=num_frames, nrows=2, sharey=True, sharex=True, figsize=(num_frames*2, 2), constrained_layout=True)
for ax in axes.flatten():
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
for sample_sphere, sample_gp, ax in zip(samples_sphere, samples_gp,... | _____no_output_____ | MIT | docs/source/tutorials/animate_gaussian_distributions.ipynb | anukaal/probnum-evaluation |
URL text boxhttps://vuetifyjs.com/en/components/text-fields | v.Col(cols=6, children=[
v.TextField(outlined=True, class_='ma-2', label='URL', placeholder='https://')
])
# home listing
# https://www.rightmove.co.uk/property-for-sale/property-72921928.html
# all listing data: property of Rightmove.co.uk
from download_listing import get_listing
from pprint import pprint
... | _____no_output_____ | BSD-3-Clause | 3 Custom components.ipynb | MichaMucha/odsc2019-voila-jupyter-web-app |
Cardhttps://vuetifyjs.com/en/components/cards | from download_listing import get_listing
class URLTextField(v.VuetifyTemplate):
url = Unicode('').tag(sync=True, allow_null=True)
loading = Bool(False).tag(sync=True)
props = List(get_listing('')).tag(sync=True)
show = Bool(False).tag(sync=True)
price_string = Unicode('£1,000,000').tag(sync=True)
... | _____no_output_____ | BSD-3-Clause | 3 Custom components.ipynb | MichaMucha/odsc2019-voila-jupyter-web-app |
Sparklinehttps://vuetifyjs.com/en/components/sparklines | %matplotlib inline
import numpy as np
import pandas as pd
strange_walk = np.random.beta(2, 3, 10) * 100 * np.random.normal(size=10)
strange_walk = pd.Series(strange_walk, name='Strange Walk').cumsum().round(2)
strange_walk.plot()
class SeriesSparkline(v.VuetifyTemplate):
name = Unicode('').tag(sync=True)
valu... | _____no_output_____ | BSD-3-Clause | 3 Custom components.ipynb | MichaMucha/odsc2019-voila-jupyter-web-app |
Fix the Seed for Reproducible Results | import random
seed = 23
#torch.manual_seed(seed)
#torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
import re
def my_preprocess_text(in_text):
username_re = re.compile(r'(^|[^@\w])@(\w{1,15})\b') # @username
url_re = re.compile(r'http\S+') # urls
in_text = re.sub('RT', '', in_text.rst... | _____no_output_____ | MIT | Germeval2019-Task2.ipynb | rother/germeval2019 |
Fine grained task | # Transform from the format text, binary, fine to
# text, 'other', 'offense', 'abuse', 'insult', 'profanity' for finegrained classification
# 1) Copy
#df_tweets_tsh_fine = pd.read_csv(file_head, delimiter='\t', header=None)
df_tweets_tsh_fine = pd.concat([pd.read_csv(f, delimiter='\t', header=None) for f in file_list ]... | _____no_output_____ | MIT | Germeval2019-Task2.ipynb | rother/germeval2019 |
Concepts in Spatial Linear Modelling Data Borrowing in Supervised Learning | import numpy as np
import libpysal.weights as lp
import geopandas as gpd
import pandas as pd
import shapely.geometry as shp
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
listings = pd.read_csv('./data/berlin-listings.csv.gz')
listings['geometry'] = listings[['longitude','latitude']].apply(shp... | _____no_output_____ | MIT | AdvancedDataAnalysis/Session12 Geospatial/Notebook-4-Data-Borrowing.ipynb | robretoarenal/BTS2 |
Kernel Regressions Kernel regressions are one exceptionally common way to allow observations to "borrow strength" from nearby observations. However, when working with spatial data, there are *two simultaneous senses of what is near:* - things that similar in attribute (classical kernel regression)- things that are sim... | model_data = listings[['accommodates', 'review_scores_rating',
'bedrooms', 'bathrooms', 'beds',
'price', 'geometry']].dropna()
Xnames = ['accommodates', 'review_scores_rating',
'bedrooms', 'bathrooms', 'beds' ]
X = model_data[Xnames].values
X = X.astype(fl... | _____no_output_____ | MIT | AdvancedDataAnalysis/Session12 Geospatial/Notebook-4-Data-Borrowing.ipynb | robretoarenal/BTS2 |
Further, since each listing has a location, I'll extract the set of spatial coordinates coordinates for each listing. | coordinates = np.vstack(model_data.geometry.apply(lambda p: np.hstack(p.xy)).values) | _____no_output_____ | MIT | AdvancedDataAnalysis/Session12 Geospatial/Notebook-4-Data-Borrowing.ipynb | robretoarenal/BTS2 |
scikit neighbor regressions are contained in the `sklearn.neighbors` module, and there are two main types:- `KNeighborsRegressor`, which uses a k-nearest neighborhood of observations around each focal site- `RadiusNeighborsRegressor`, which considers all observations within a fixed radius around each focal site.Further... | import sklearn.neighbors as skn
import sklearn.metrics as skm
shuffle = np.random.permutation(len(y))
train,test = shuffle[:14000],shuffle[14000:] | _____no_output_____ | MIT | AdvancedDataAnalysis/Session12 Geospatial/Notebook-4-Data-Borrowing.ipynb | robretoarenal/BTS2 |
So, let's fit three models:- `spatial`: using inverse distance weighting on the nearest 500 neighbors geograpical space- `attribute`: using inverse distance weighting on the nearest 500 neighbors in attribute space- `both`: using inverse distance weighting in both geographical and attribute space. | KNNR = skn.KNeighborsRegressor(weights='distance', n_neighbors=500)
spatial = KNNR.fit(coordinates[train,:],
y[train,:])
KNNR = skn.KNeighborsRegressor(weights='distance', n_neighbors=500)
attribute = KNNR.fit(X[train,:],
y[train,])
KNNR = skn.KNeighborsRegressor(weights='distance'... | _____no_output_____ | MIT | AdvancedDataAnalysis/Session12 Geospatial/Notebook-4-Data-Borrowing.ipynb | robretoarenal/BTS2 |
To score them, I'm going to grab their out of sample prediction accuracy and get their % explained variance: | sp_ypred = spatial.predict(coordinates[test,:])
att_ypred = attribute.predict(X[test,:])
both_ypred = both.predict(np.hstack((X,coordinates))[test,:])
(skm.explained_variance_score(y[test,], sp_ypred),
skm.explained_variance_score(y[test,], att_ypred),
skm.explained_variance_score(y[test,], both_ypred)) | _____no_output_____ | MIT | AdvancedDataAnalysis/Session12 Geospatial/Notebook-4-Data-Borrowing.ipynb | robretoarenal/BTS2 |
If you don't know $X$, using $Wy$ would be better than nothing, but it works nowhere near as well... less than half of the variance that is explained by nearness in feature/attribute space is explained by nearness in geographical space. Making things even worse, simply glomming on the geographical information to the fe... | from libpysal.weights.util import fill_diagonal
kW = lp.Kernel.from_dataframe(model_data, fixed=False, function='gaussian', k=100)
kW = fill_diagonal(kW, 0)
WX = lp.lag_spatial(kW, X)
WX
kW.to_adjlist()[kW.to_adjlist()["focal"]== 1] | _____no_output_____ | MIT | AdvancedDataAnalysis/Session12 Geospatial/Notebook-4-Data-Borrowing.ipynb | robretoarenal/BTS2 |
I like `statsmodels` regression summary tables, so I'll pop it up here. Below are the results for the model with only the covariates used above:- accommodates: the number of people the airbnb can accommodate- review_scores_rating: the aggregate rating of the listing- bedrooms: the number of bedrooms the airbnb has- ba... | import statsmodels.api as sm
Xtable = pd.DataFrame(X, columns=Xnames)
onlyX = sm.OLS(y,sm.add_constant(Xtable)).fit()
onlyX.summary() | _____no_output_____ | MIT | AdvancedDataAnalysis/Session12 Geospatial/Notebook-4-Data-Borrowing.ipynb | robretoarenal/BTS2 |
Then, we could fit a model using the neighbourhood average synthetic features as well: | WXtable = pd.DataFrame(WX, columns=['lag_{}'.format(name) for name in Xnames])
WXtable.head()
XWXtable = pd.concat((Xtable,WXtable),axis=1)
XWXtable.head()
withWX = sm.OLS(y,sm.add_constant(XWXtable)).fit()
withWX.summary() | _____no_output_____ | MIT | AdvancedDataAnalysis/Session12 Geospatial/Notebook-4-Data-Borrowing.ipynb | robretoarenal/BTS2 |
AlignmentThis notebook covers [*alignment*](https://pandas.pydata.org/docs/user_guide/dsintro.htmldsintro-alignment), a feature of pandas that's crucial to using it well. It relies on the pandas' handling of *labels*. | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
Goal: Compute Real GDPLet's learn through an example: Gross Domestic Product (the total output of a country) is measured in dollars. This means we we can't just compare the GDP from 1950 to the GDP from 2000, since the value of a dollar changed over that time (inflation).In the US, the Bureau of Economic Analysis alre... | gdp_bad = pd.read_csv("data/GDP.csv.gz", parse_dates=["DATE"])
cpi_bad = pd.read_csv("data/CPIAUCSL.csv.gz", parse_dates=["DATE"]) | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
Our formula says `real_gdp = gdp / cpi`, so, let's try it! | %xmode plain
gdp_bad / cpi_bad | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
Whoops, what happened? We should probably look at our data: | gdp_bad
gdp_bad.dtypes
gdp_bad['DATE'][0] | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
So, we've tried to divide a datetime by a datetime, and pandas has correctly raised a type error. That raises another issue though. These two timeseries have different frequencies. | cpi_bad.head() | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
CPI is measured monthly, while GDP is quarterly. What we'd really need to do is *join* the two timeseries on the `DATE` variable, and then do the operation. We could do that, but let's do things the pandorable way first.A DataFrame is a 2-D data structure composed of three components:1. The *values*, the actual data2. ... | # Notice that we select the GDP column to convert the
# 1-column DataFrame to a 1D Series
gdp = pd.read_csv('data/GDP.csv.gz', index_col='DATE',
parse_dates=['DATE'])["GDP"]
gdp.head() | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
Notice that we selected the single column `"GDP"` using `[]`. This returns a `pandas.Series` object, a 1-D array *with row labels*. | type(gdp)
gdp.index | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
The actual values are a NumPy array of floats. | gdp.to_numpy()[:10] | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
Let's read in CPI as well. | cpi = pd.read_csv('data/CPIAUCSL.csv.gz', index_col='DATE',
parse_dates=['DATE'])["CPIAUCSL"]
cpi.head() | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
And let's try the formula again. | rgdp = gdp / cpi
rgdp | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
**What happened?**We've gotten our answer, but is there anything in the output that's surprising? What are these `NaN`s?In pandas, any time you do an operation involving multiple pandas objects (dataframes, series), pandas will *align* the inputs. Alignment is a two-step process:1. Take the union of the labels2. Reinde... | # manual alignment, just for demonstration:
all_dates = gdp.index.union(cpi.index)
all_dates
gdp2 = gdp.reindex(all_dates)
gdp2
cpi2 = cpi.reindex(all_dates)
cpi2
rgdp2 = gdp2 / cpi2
rgdp2 | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
So when we wrote```pythonrgdp = gdp / cpi```pandas performs```pythonall_dates = gdp.index.union(cpi.index)rgdp = gdp.reindex(all_dates) / cpi.reindex(all_dates)```This behavior is somewhat peculiar to pandas. But once you're used to it it's hard to go back. pandas handling the labels / alignment elimiates a class of er... | rgdp.isna()
rgdp.dropna()
rgdp.fillna(method='ffill') # or fill with a scalar. | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
Exercise:Normalize real GDP to year **2000** dollars.Right now, the unit on the `CPI` variable is "Index 1982-1984=100". This means that "index value" for the Consumer Price *Index* show year is the average of 1982 - 1984. | # use `.loc[start:end]` or `.loc["<year>"]` to slice a subset of *rows*
cpi.loc['1982':'1984'].mean() # close enough to 100 | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
To *renormalize* an index like CPI, divide the series by the average of a different timespan (say the year 2000) and multiply by 100. | # Get the mean CPI for the year 2000
cpi_2000_average = cpi.loc[...]...
# *renormalize* the entire `cpi` series to "Index 2000" units.
cpi_2000 = 100 * (... / ...)
# Compute real GDP again, this time in "year 2000 dollars".
rgdp_2000 = ...
rgdp_2000
%load solutions/alignment-cpi2000.py | _____no_output_____ | CC-BY-4.0 | Alignment.ipynb | TomAugspurger/pandorable-pandas |
Predictions callbacks> Various callbacks to customize get_preds behaviors MCDropoutCallback> Turns on dropout during inference, allowing you to call Learner.get_preds multiple times to approximate your model uncertainty using [Monte Carlo Dropout](https://arxiv.org/pdf/1506.02142.pdf). | #|export
class MCDropoutCallback(Callback):
def before_validate(self):
for m in [m for m in flatten_model(self.model) if 'dropout' in m.__class__.__name__.lower()]:
m.train()
def after_validate(self):
for m in [m for m in flatten_model(self.model) if 'dropout' in m.__class__.__n... | _____no_output_____ | Apache-2.0 | nbs/18b_callback.preds.ipynb | EmbraceLife/fastai |
Export - | #|hide
from nbdev.export import notebook2script
notebook2script() | Converted 00_torch_core.ipynb.
Converted 01_layers.ipynb.
Converted 02_data.load.ipynb.
Converted 03_data.core.ipynb.
Converted 04_data.external.ipynb.
Converted 05_data.transforms.ipynb.
Converted 06_data.block.ipynb.
Converted 07_vision.core.ipynb.
Converted 08_vision.data.ipynb.
Converted 09_vision.augment.ipynb.
Co... | Apache-2.0 | nbs/18b_callback.preds.ipynb | EmbraceLife/fastai |
Exercises 5. Fiddle with the activation functions. Try applying a ReLu to the first hidden layer and tanh to the second one. The tanh activation is given by the method: tf.nn.tanh()**Solution** Analogically to the previous lecture, we can change the activation functions. This time though, we will use different activat... | import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# TensorFLow includes a data provider for MNIST that we'll use.
# This function automatically downloads the MNIST dataset to the chosen directory.
# The dataset is already split into training, validation, and test su... | _____no_output_____ | MIT | course_2/course_material/Part_7_Deep_Learning/S54_L390/5. TensorFlow_MNIST_Activation_functions_Part_2_Solution.ipynb | Alexander-Meldrum/learning-data-science |
Outline the modelThe whole code is in one cell, so you can simply rerun this cell (instead of the whole notebook) and train a new model.The tf.reset_default_graph() function takes care of clearing the old parameters. From there on, a completely new training starts. | input_size = 784
output_size = 10
# Use same hidden layer size for both hidden layers. Not a necessity.
hidden_layer_size = 50
# Reset any variables left in memory from previous runs.
tf.reset_default_graph()
# As in the previous example - declare placeholders where the data will be fed into.
inputs = tf.placeholder(... | _____no_output_____ | MIT | course_2/course_material/Part_7_Deep_Learning/S54_L390/5. TensorFlow_MNIST_Activation_functions_Part_2_Solution.ipynb | Alexander-Meldrum/learning-data-science |
Test the modelAs we discussed in the lectures, after training on the training and validation sets, we test the final prediction power of our model by running it on the test dataset that the algorithm has not seen before.It is very important to realize that fiddling with the hyperparameters overfits the validation data... | input_batch, target_batch = mnist.test.next_batch(mnist.test._num_examples)
test_accuracy = sess.run([accuracy],
feed_dict={inputs: input_batch, targets: target_batch})
# Test accuracy is a list with 1 value, so we want to extract the value from it, using x[0]
# Uncomment the print to see how it looks before the ... | _____no_output_____ | MIT | course_2/course_material/Part_7_Deep_Learning/S54_L390/5. TensorFlow_MNIST_Activation_functions_Part_2_Solution.ipynb | Alexander-Meldrum/learning-data-science |
Modeling Theta: Muti-population recurrent network (with BMTK BioNet) Here we will create a heterogenous yet relatively small network consisting of hundreds of cells recurrently connected. All cells will belong to one of four "cell-types". Two of these cell types will be biophysically detailed cells, i.e. containing a ... | import numpy as np
from bmtk.builder.networks import NetworkBuilder
from bmtk.builder.auxi.node_params import positions_list
def pos_CA3e():
# Create the possible x,y,z coordinates for CA3e cells
x_start, x_end, x_stride = 0.5,15,2.3
y_start, y_end, y_stride = 0.5,3,1
z_start, z_end, z_stride = 1,4,1
... | _____no_output_____ | MIT | theta.ipynb | cyneuro/theta |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.