markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Calculate a boolean array whether the images in the validation-set are classified correctly. | def validation_correct():
return correct_prediction(images = data.validation.images,
labels = data.validation.labels,
cls_true = data.validation.cls) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-functions for calculating the classification accuracy
This function calculates the classification accuracy given a boolean array whether each image was correctly classified. E.g. classification_accuracy([True, True, False, False, False]) = 2/5 = 0.4 | def classification_accuracy(correct):
# When averaging a boolean array, False means 0 and True means 1.
# So we are calculating: number of True / len(correct) which is
# the same as the classification accuracy.
return correct.mean() | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Calculate the classification accuracy on the test-set. | def test_accuracy():
# Get the array of booleans whether the classifications are correct
# for the test-set.
correct = test_correct()
# Calculate the classification accuracy and return it.
return classification_accuracy(correct) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Calculate the classification accuracy on the original validation-set. | def validation_accuracy():
# Get the array of booleans whether the classifications are correct
# for the validation-set.
correct = validation_correct()
# Calculate the classification accuracy and return it.
return classification_accuracy(correct) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Results and analysis
Function for calculating the predicted labels for all the neural networks in the ensemble. The labels are combined further below. | def ensemble_predictions():
# Empty list of predicted labels for each of the neural networks.
pred_labels = []
# Classification accuracy on the test-set for each network.
test_accuracies = []
# Classification accuracy on the validation-set for each network.
val_accuracies = []
# For each ... | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Summarize the classification accuracies on the test-set for the neural networks in the ensemble. | print("Mean test-set accuracy: {0:.4f}".format(np.mean(test_accuracies)))
print("Min test-set accuracy: {0:.4f}".format(np.min(test_accuracies)))
print("Max test-set accuracy: {0:.4f}".format(np.max(test_accuracies))) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The predicted labels of the ensemble is a 3-dim array, the first dim is the network-number, the second dim is the image-number, the third dim is the classification vector. | pred_labels.shape | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Ensemble predictions
There are different ways to calculate the predicted labels for the ensemble. One way is to calculate the predicted class-number for each neural network, and then select the class-number with most votes. But this requires a large number of neural networks relative to the number of classes.
The metho... | ensemble_pred_labels = np.mean(pred_labels, axis=0)
ensemble_pred_labels.shape | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The ensemble's predicted class number is then the index of the highest number in the label, which is calculated using argmax as usual. | ensemble_cls_pred = np.argmax(ensemble_pred_labels, axis=1)
ensemble_cls_pred.shape | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Boolean array whether each of the images in the test-set was correctly classified by the ensemble of neural networks. | ensemble_correct = (ensemble_cls_pred == data.test.cls) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Negate the boolean array so we can use it to lookup incorrectly classified images. | ensemble_incorrect = np.logical_not(ensemble_correct) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Best neural network
Now we find the single neural network that performed best on the test-set.
First list the classification accuracies on the test-set for all the neural networks in the ensemble. | test_accuracies | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The index of the neural network with the highest classification accuracy. | best_net = np.argmax(test_accuracies)
best_net | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The best neural network's classification accuracy on the test-set. | test_accuracies[best_net] | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Predicted labels of the best neural network. | best_net_pred_labels = pred_labels[best_net, :, :] | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The predicted class-number. | best_net_cls_pred = np.argmax(best_net_pred_labels, axis=1) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Boolean array whether the best neural network classified each image in the test-set correctly. | best_net_correct = (best_net_cls_pred == data.test.cls) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Boolean array whether each image is incorrectly classified. | best_net_incorrect = np.logical_not(best_net_correct) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Comparison of ensemble vs. the best single network
The number of images in the test-set that were correctly classified by the ensemble. | np.sum(ensemble_correct) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The number of images in the test-set that were correctly classified by the best neural network. | np.sum(best_net_correct) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Boolean array whether each image in the test-set was correctly classified by the ensemble and incorrectly classified by the best neural network. | ensemble_better = np.logical_and(best_net_incorrect,
ensemble_correct) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Number of images in the test-set where the ensemble was better than the best single network: | ensemble_better.sum() | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Boolean array whether each image in the test-set was correctly classified by the best single network and incorrectly classified by the ensemble. | best_net_better = np.logical_and(best_net_correct,
ensemble_incorrect) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Number of images in the test-set where the best single network was better than the ensemble. | best_net_better.sum() | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Helper-functions for plotting and printing comparisons
Function for plotting images from the test-set and their true and predicted class-numbers. | def plot_images_comparison(idx):
plot_images(images=data.test.images[idx, :],
cls_true=data.test.cls[idx],
ensemble_cls_pred=ensemble_cls_pred[idx],
best_cls_pred=best_net_cls_pred[idx]) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Function for printing the predicted labels. | def print_labels(labels, idx, num=1):
# Select the relevant labels based on idx.
labels = labels[idx, :]
# Select the first num labels.
labels = labels[0:num, :]
# Round numbers to 2 decimal points so they are easier to read.
labels_rounded = np.round(labels, 2)
# Print the rounded la... | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Function for printing the predicted labels for the ensemble of neural networks. | def print_labels_ensemble(idx, **kwargs):
print_labels(labels=ensemble_pred_labels, idx=idx, **kwargs) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Function for printing the predicted labels for the best single network. | def print_labels_best_net(idx, **kwargs):
print_labels(labels=best_net_pred_labels, idx=idx, **kwargs) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Function for printing the predicted labels of all the neural networks in the ensemble. This only prints the labels for the first image. | def print_labels_all_nets(idx):
for i in range(num_networks):
print_labels(labels=pred_labels[i, :, :], idx=idx, num=1) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Examples: Ensemble is better than the best network
Plot examples of images that were correctly classified by the ensemble and incorrectly classified by the best single network. | plot_images_comparison(idx=ensemble_better) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The ensemble's predicted labels for the first of these images (top left image): | print_labels_ensemble(idx=ensemble_better, num=1) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The best network's predicted labels for the first of these images: | print_labels_best_net(idx=ensemble_better, num=1) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The predicted labels of all the networks in the ensemble, for the first of these images: | print_labels_all_nets(idx=ensemble_better) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Examples: Best network is better than ensemble
Now plot examples of images that were incorrectly classified by the ensemble but correctly classified by the best single network. | plot_images_comparison(idx=best_net_better) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The ensemble's predicted labels for the first of these images (top left image): | print_labels_ensemble(idx=best_net_better, num=1) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The best single network's predicted labels for the first of these images: | print_labels_best_net(idx=best_net_better, num=1) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
The predicted labels of all the networks in the ensemble, for the first of these images: | print_labels_all_nets(idx=best_net_better) | 05_Ensemble_Learning.ipynb | Hvass-Labs/TensorFlow-Tutorials | mit |
Plotting 1d histograms
We can now run the MCMC routine and plot the histograms of the inferred parameters. | print('Running...')
chains = mcmc.run()
print('Done!')
# Select chain 0 and discard warm-up
chain = chains[0]
chain = chain[3000:]
import pints.plot
# Plot the 1d histogram of each parameter
pints.plot.histogram([chain], parameter_names=['growth rate', 'carrying capacity', 'noise'])
plt.show() | examples/plotting/mcmc-pairwise-scatterplots.ipynb | martinjrobins/hobo | bsd-3-clause |
Plotting 2d histograms and a matrix of parameter distribution plots
Plotting the histograms of two variables (showing their correlation) can be performed using pints.plot.pairwise with the parameter heatmap set to True. Additionally, by supplying the known real parameters, we see the locations of the true values appear... | pints.plot.pairwise(chain, heatmap=True, parameter_names=['growth rate', 'carrying capacity', 'noise'], ref_parameters=real_parameters)
plt.show() | examples/plotting/mcmc-pairwise-scatterplots.ipynb | martinjrobins/hobo | bsd-3-clause |
Matrix of parameter distribution plots with KDE
It is also possible to use kernel density estimation (KDE) to visualize the probability distributions of each parameter. Using the pints.plot.pairwise function, this time with the parameter kde set to True, we can create a matrix of scatterplots with KDE. | pints.plot.pairwise(chain, kde=True, parameter_names=['growth rate', 'carrying capacity', 'noise'], ref_parameters=real_parameters)
plt.show() | examples/plotting/mcmc-pairwise-scatterplots.ipynb | martinjrobins/hobo | bsd-3-clause |
Python dictionaries are structures built for data that have a key-value structure. The keys are like indices. But instead of numerical indices (0,1,2,etc.), the keys can be any numbers or strings (technically, any hashable type)! Each key in the dictionary references a value, in the same way that each index of a lis... | nemo = {'species':'clownfish', 'color':'orange', 'age':6}
nemo['color'] # The key 'color' references the value 'orange'.
nemo['age'] # Predict the result. Notice the quotes are necessary. The *string* 'age' is the key.
nemo[1] # This yields a KeyError, since 1 is not a key in the dictionary. | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Dictionaries can have values of any type, and their keys can be numbers or strings. In this case, the keys are all strings, while the values include strings and integers. In this way, dictionaries are useful for storing properties of different kinds -- they can be used to store [records](https://en.wikipedia.org/wiki... | id(L)
id(nemo)
id(L[0]) | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
It is sometimes useful to check the ID numbers of objects, to look "under the hood" a bit. For example, consider the following. | x = 3
y = 3
print(x == y) # This should be true!
id(x)
id(y) | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
What happened? You probably noticed that both variables x and y have the same id number. That means that Python is being efficient, and not filling up two different slots of memory with the same number (3). Instead, it puts the number in one memory slot, and uses x and y as alternative names for this slot.
But what ... | x = 5
id(x)
id(y) | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Python won't be confused by this. When we assigned x = 5, Python opened up a new memory slot for the number 5, and assigned x to refer to the number in this new slot. Note that y still "points" at the old slot. Python tries to be smart about memory, remembering where numbers are stored, and putting numbers into slot... | id(3) # Does Python remember where it put 3?
id(5) # Does Python remember where it put 5?
id(4) # 4 was probably not in memory before. But now it is!
y = 5
id(y) # Did Python change the number in a slot? Or did it point `y` at another slot?
id(L[2]) # Python doesn't like to waste space. | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
This sort of memory management can be helpful to avoid repetetion. For example, consider a list with repetition. | R = [19,19,19]
id(R) # The list itself is an object.
id(R[0]) # The 0th item in the list is an object.
id(R[1]) # The 1st item in the list is an object.
id(R[2]) # The 2nd item in the list is an object. | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
By having each list entry point to the same location in memory, Python avoids having to fill three blocks of memory with the same number 19.
Python objects can have methods attached to them. Methods are functions which can utilize and change the data within an object. The basic syntax for using methods is <obje... | nemo.keys() # What are the keys of nemo?
nemo.values() # What are the values of nemo? | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
The output of the keys() and values() methods are list-like. As such, they are convenient for iteration and membership-testing. | 'color' in nemo.keys()
'taste' in nemo.keys()
'orange' in nemo.keys() # Is 'orange' a key in the dictionary?
for k in nemo.keys(): # Iterates through the keys.
print('Nemo\'s {} is {}.'.format(k,nemo[k])) # \' is used to get a single-quote in a string. | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
In fact, Python provides a simpler syntax for iterating over keys or testing membership in keys. The syntax for k in <dictionary>: iterates the variable k through the keys of the <dictionary>. Similarly the syntax k in <dictionary> is shorthand for k in <dictionary>.keys(). | for k in nemo: # This will iterate through the *keys* of the dictionary nemo.
print('Nemo\'s {} is {}.'.format(k,nemo[k])) | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Sometimes we'll want to change a dictionary. Perhaps we learn that nemo has gotten lost. | nemo['status'] = 'lost'
id(nemo)
id('status')
print(nemo) | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
The command nemo['status'] = 'lost' creates a new key in the dictionary called 'status' and assigns the value 'lost' to the key. If we find nemo, then we can change the value. | nemo['status'] = 'found'
print(nemo) | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Since 'status' is already among the keys of nemo, the command nemo['status'] = 'found' does not create a new key this time. It just changes the associated value from 'lost' to 'found'. | nemo.keys() # What are the keys of nemo now?
nemo.values() # What are the values of nemo now? | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
We mentioned earlier that keys() and values() are methods attached to the object nemo, and methods are functions which are attached to Python objects.
Python objects often (and often by default!) have methods attached to them. Every dictionary and every list in Python comes with attached methods. Methods can be used... | L = [2,3,5,7]
print(L) # Let's remember what the list L is.
L[0] # What is this?
id(L[0]) # What is the ID number of the 0th item in the list?
L.reverse() # The reverse() method changes L!
print(L)
L[0] # We have definitely changed L.
L[3] # The last item in the list L.
id(L[3]) # The ID number of the last item... | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Observe that Python changed the order of the items in the list. But it didn't move them around in memory! The object 2 maintains the same ID number, and stays in the same place in memory. But the list item L[0] points at 2 before reversing while L[3] points at 2 after reversing. This kind of thing is confusing at f... | L.append(11) # Let's add another term to the list with the append(*) method.
print(L)
L.sort() # Let's get this list back in order.
print(L) | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Some more useful list methods can be found at the official Python tutorial.
Prime decomposition dictionaries
If $N$ is a positive integer, then $N$ can be uniquely decomposed into a product of primes. Here "uniquely" means that $N$ has a unique expression of the form
$$N = 2^{e_2} 3^{e_3} 5^{e_5} \cdots$$
in which t... | from math import sqrt # We'll want to use the square root.
def smallest_factor(n):
'''
Gives the smallest prime factor of n.
'''
if n < 2:
return None # No prime factors!
test_factor = 2 # The smallest possible prime factor.
max_factor = sqrt(n) # we don't have to search past sqrt... | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Now that we have a function to compute the prime decomposition of a positive integer, we write a function to recover a positive integer from such a prime decomposition. The function is deceptively simple, since Python makes it easy to iterate through the keys of a dictionary. Make sure that you understand every line. | def recompose(D):
'''
If D is a dictionary with prime keys and natural values,
this function outputs the product of terms of the form
key^value. In this way, it recovers a single number from a
prime decomposition.
'''
N = 1
for p in D.keys(): # iterate p through all the keys of D.
... | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Exercises
Create the list [1,100,2,99,3,98,4,97,...,50,51] with as few list commands as you can.
If you try the commands x = 7, y = 11, then x,y = y,x, what do you expect happens with id(x) and id(y) along the way?
How might you adapt the decompose function to work with all integers (positive and negative)? Note... | # Use this space for the exercises.
| P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
<a id='multfunc'></a>
Multiplicative functions
A multiplicative function is a function $f(n)$ which takes positive integer input $n$, and which satisfies $f(1) = 1$ and $f(ab) = f(a) f(b)$ whenever $a$ and $b$ are coprime. A good example is the divisor-sum function, implemented below. | def divisor_sum(n):
S = 0 # Start the sum at zero.
for d in range(1,n+1): # potential divisors between 1 and n.
if n%d == 0:
S = S + d
return S
divisor_sum(100) # The sum 1 + 2 + 4 + 5 + 10 + 20 + 25 + 50 + 100
%timeit divisor_sum(730) # Let's see how quickly this runs. | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
A perfect number is a positive integer which equals the sum of its proper factors (its positive factors, not including itself). Thus a number $n$ is perfect if its divisor sum equals $2n$. This can be implemented in a very short function. | def is_perfect(n):
return divisor_sum(n) == 2*n
is_perfect(10)
is_perfect(28) | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Let's find the perfect numbers up to 10000. It might take a few seconds. | for j in range(1,10000):
if is_perfect(j):
print("{} is perfect!".format(j)) | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Multiplicative functions like the divisor sum function can be computed via prime decomposition. Indeed, if $f$ is a multiplicative function, and $$n = 2^{e_2} 3^{e_3} 5^{e_5} \cdots,$$ then the value $f(n)$ satisfies
$$f(n) = f(2^{e_2}) \cdot f(3^{e_3}) \cdot f(5^{e_5}) \cdots.$$
So if we can compute the values of $f$... | def divisor_sum_pp(p,e): # pp stands for prime power
'''
Computes the divisor sum of the prime power p**e,
when p is prime and e is a positive integer.
This is just 1 + p^2 + p^3 + ... + p^e,
simplified using a geometric series formula.
'''
return (p**(e+1) - 1) // (p - 1)
divisor_sum_pp(2... | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Now let's re-implement the divisor sum function, using prime decomposition and the divisor_sum_pp function for prime powers. | def divisor_sum(n):
'''
Computes the sum of the positive divisors of a
positive integer n.
'''
D = decompose(n) # We require the decompose function from before!
result = 1
for p in D.keys():
result = result * divisor_sum_pp(p,D[p])
return result
divisor_sum(15)
% timeit(... | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
There are a lot of interesting multiplicative functions. We could implement each one by a two-step process as above: implementing the function for prime powers, then defining a version for positive integers by using the decompose function. But there's a shortcut for the second step, which brings in a very cool aspec... | type(divisor_sum_pp) # Every object has a type.
id(divisor_sum_pp) # Yes, every object gets an ID number. | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Since functions are Python objects, it is possible to define a function which takes a function as input and outputs a function too! You can pass a function as an input parameter to another function, just as if it were any other variable. You can output a function with the return keyword, just as if it were another va... | def addone(x): # Let's make a simple function.
return x + 1 # It's not a very interesting function, is it.
addone(10) # Predict the result.
def do_twice(f):
'''
If a function f is input, then the output is the function
"f composed with f."
'''
def ff(x): # Defines a new function ff!
... | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Now we exploit this function-as-object approach to create a Python function called mult_function. Given a function f_pp(p,e), the function mult_function outputs the multiplicative function which coincides with f_pp on prime powers. In other words, if f = mult_function(f_pp), then f(p**e) will equal f_pp(p,e). | def mult_function(f_pp):
'''
When a function f_pp(p,e) of two arguments is input,
this outputs a multiplicative function obtained from f_pp
via prime decomposition.
'''
def f(n):
D = decompose(n)
result = 1
for p in D:
result = result * f_pp(p, D[p])
r... | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Let's see how this works for the divisor-counting function. This is the function $\sigma_0(n)$ whose value is the number of positive divisors of $n$. For prime powers, it is easy to count divisors, $$\sigma_0(p^e) = e + 1.$$ | def sigma0_pp(p,e):
return e+1 | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Since the divisor-counting function is multiplicative, we can implement it by applying mult_function to sigma0_pp. | sigma0 = mult_function(sigma0_pp)
sigma0(100) # How many divisors does 100 have? | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
Exercises
A positive integer $n$ is called deficient/perfect/abundant according to whether the sum of its proper divisors is less than/equal to/greater than $n$ itself. Among the numbers up to 10000, how many are deficient, perfect, and abundant?
If $f(n)$ is a function with natural number input and real output, d... | # Use this space to work on the exercises. | P3wNT Notebook 4.ipynb | MartyWeissman/Python-for-number-theory | gpl-3.0 |
In order to also showcase some other network generation options we first start with a small 2D network with StickAndBall geometry. | spacing=2.5e-5
net = op.network.Cubic([20, 20, 1], spacing=spacing)
geo = op.geometry.StickAndBall(network=net, pores=net.Ps, throats=net.Ts) | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
We then trim all the surface pores to obtain disctint sets of boundary edge pores. | net.labels()
net.num_throats('surface')
trim(network=net, throats=net.throats('surface'))
h = net.check_network_health()
trim(network=net, pores=h['trim_pores']) | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
Then we use a function from our porespy package to generate a tomography style image of the abstract network providing the number of pixels in each dimension. | #NBVAL_IGNORE_OUTPUT
im = ps.io.openpnm_to_im(net, max_dim=1000)
im.shape | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
This creates a 3D image but we can crop it to get the central slice in 2D for visualization. | #NBVAL_IGNORE_OUTPUT
fig, ax = plt.subplots(figsize=(5, 5))
plt.imshow(im[25:-25, 25:-25, 25].T)
crop = im[25:-25, 25:-25, :] | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
Next the snow algorithm is used to do network extraction on the tomography style image. Of course if you have your own tomogrpahy image this can be used instead. | #NBVAL_IGNORE_OUTPUT
snow_out = ps.networks.snow(crop > 0, voxel_size=4e-7)
snow_out.regions.shape | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
The SNOW algorithm provides a labelled region image containing the pore index. As zero is used for the background it is actually the pore index + 1 because python references arrays with first element as zero and we do not explicitly store the pore index. | #NBVAL_IGNORE_OUTPUT
fig, ax = plt.subplots(figsize=(5, 5))
reg = snow_out.regions.astype(float) - 1
reg[reg == -1] = np.nan
region_slice = snow_out.regions[:, :, 28] - 1
mask = region_slice >= 0
plt.imshow(region_slice.T); | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
Now our new network is extracted we can fill a network object with all the properties and begin simulation. | wrk = op.Workspace()
wrk.clear()
net = op.network.GenericNetwork()
net.update(snow_out)
geo = op.geometry.GenericGeometry(network=net, pores=net.Ps, throats=net.Ts) | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
A helper function is defined for plotting a particular data set. | def update_image(data):
data = data.astype(float)
out_im = np.ones(region_slice.shape, dtype=float)*-1
out_im[mask] = data[region_slice[mask]]
out_im[~mask] = np.nan
return out_im
#NBVAL_IGNORE_OUTPUT
fig, ax = plt.subplots(figsize=(5, 5))
out = update_image(net['pore.diameter'])
plt.imshow(out.T); | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
Again, stadard physics is used to define the capillary entry pressures. And these are shown as a histogram for all the throats in the network. | water = op.phases.Water(network=net)
phys = op.physics.Standard(network=net, geometry=geo, phase=water)
#NBVAL_IGNORE_OUTPUT
fig, ax = plt.subplots(figsize=[5, 5])
ax.hist(phys['throat.entry_pressure'], bins=10) | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
Next, the algorithm is defined and run with no arguments or outlets defined. This will proceed step by step assessing which pores are currently invaded (i.e. inlets first), which throats connect to an uninvaded pore and of these, which throat has the lowest capillary entry pressure for invasion. Invasion then proceeds ... | #NBVAL_IGNORE_OUTPUT
alg_ip = op.algorithms.InvasionPercolation(network=net)
alg_ip.setup(phase=water)
alg_ip.set_inlets(pores=net.pores('left'))
alg_ip.run()
fig, ax = plt.subplots(figsize=(5, 5))
out = update_image(alg_ip['pore.invasion_sequence'])
plt.imshow(out.T);
def plot_invasion(seq):
data = alg_ip['pore.i... | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
Using the slider below we can interactively plot the saturation at each invasion step (this works best using the left and right arrow keys). | #NBVAL_IGNORE_OUTPUT
max_seq = alg_ip['pore.invasion_sequence'].max()
interact(plot_invasion, seq=IntSlider(min=0, max=max_seq, step=1, value=200)) | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
As with Ordinary Percolation we can plot a drainage or intrusion curve but this time the capillary pressure is plotted from one step to the next as a continuous process with dynamic pressure boundary conditions and so is allowed to increase and decrease to meet the next lowest entry pressure for the invading cluster. | #NBVAL_IGNORE_OUTPUT
fig, ax = plt.subplots(figsize=(5, 5))
alg_ip.plot_intrusion_curve(fig)
plt.show() | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
We can compare the results of the two algorithms and see that the pressure envelope, i.e. maximum pressure reached historically by the invasion process is the same as the ordinary percolation value. | #NBVAL_IGNORE_OUTPUT
fig, ax = plt.subplots(figsize=(5, 5))
alg_op = op.algorithms.OrdinaryPercolation(network=net, phase=water)
alg_op.set_inlets(net.pores('left'))
alg_op.setup(pore_volume='pore.volume',
throat_volume='throat.volume')
alg_op.run(points=1000)
alg_op.plot_intrusion_curve(fig)
alg_ip.plot_i... | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
An additional feature of the algorithm is the ability to identify where the defending phase becomes trapped. Whether this happens in reality in-fact relies on the connectivity of the defending phase and whether it can reside in the invaded pores as thin wetting films. If not then the defending phase is completely pushe... | #NBVAL_IGNORE_OUTPUT
alg_ip_t = op.algorithms.InvasionPercolation(network=net)
alg_ip_t.setup(phase=water)
alg_ip_t.set_inlets(pores=net.pores('left'))
alg_ip_t.run()
alg_ip_t.apply_trapping(outlets=net.pores(['boundary']))
fig, ax = plt.subplots(figsize=(5, 5))
out = update_image(alg_ip_t['pore.trapped'])
plt.imshow(o... | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
Here a reasonable fraction of the pore space is not invaded due to trapping of the defending phase. Generally this fraction will be lower in truly 3D networks as there are more routes out of the network because pores have higher connectivity. Also, typically if a defending phase is considered to be wetting then film fl... | #NBVAL_IGNORE_OUTPUT
fig, ax = plt.subplots(figsize=(5, 5))
alg_ip.plot_intrusion_curve(fig)
alg_ip_t.plot_intrusion_curve(fig)
plt.show() | examples/percolation/Part B - Invasion Percolation.ipynb | TomTranter/OpenPNM | mit |
HW 3.2 Analyze the performance of your Mappers, Combiners and Reducers using Counters
For this brief study the Input file will be one record (the next line only):
foo foo quux labs foo bar quux
Perform a word count analysis of this single record dataset using a Mapper and Reducer based WordCount (i.e., no combiners are... | %%writefile SimpleCounters.py
from mrjob.job import MRJob
class SimpleCounters(MRJob):
def mapper_init(self):
self.increment_counter("Mappers", "Count", 1)
def mapper(self, _, lines):
self.increment_counter("Mappers", "Tasks", 1)
for word in lines.split():
yield (word,... | week3/MIDS-W261-HW-03-Sanchez.ipynb | JasonSanchez/w261 | mit |
Please use multiple mappers and reducers for these jobs (at least 2 mappers and 2 reducers).
Perform a word count analysis of the Issue column of the Consumer Complaints Dataset using a Mapper and Reducer based WordCount (i.e., no combiners used anywhere) using user defined Counters to count up how many time the mapp... | %%writefile IssueCounter.py
from mrjob.job import MRJob
import csv
import sys
class IssueCounter(MRJob):
def mapper(self, _, lines):
self.increment_counter("Mappers", "Tasks", 1)
terms = list(csv.reader([lines]))[0]
yield (terms[3], 1)
def reducer(self, word, count):
self... | week3/MIDS-W261-HW-03-Sanchez.ipynb | JasonSanchez/w261 | mit |
Mapper tasks = 312913. The mapper was called this many times because that is how many lines there are in the file.
Reducer tasks = 80. The reducer was called this many times because that is how many unique issues there are in the file.
Reducer lines processed = 312913. The reducer was passed all of the data from the ma... | # We can easily confirm the first hypothesis
!wc -l Temp_data/Consumer_Complaints.csv | week3/MIDS-W261-HW-03-Sanchez.ipynb | JasonSanchez/w261 | mit |
Perform a word count analysis of the Issue column of the Consumer Complaints Dataset using a Mapper, Reducer, and standalone combiner (i.e., not an in-memory combiner) based WordCount using user defined Counters to count up how many time the mapper, combiner, reducer are called. What is the value of your user defined ... | %%writefile IssueCounterCombiner.py
from mrjob.job import MRJob
from mrjob.step import MRStep
import csv
import sys
class IssueCounterCombiner(MRJob):
def mapper(self, _, lines):
self.increment_counter("Mappers", "Tasks", 1)
terms = list(csv.reader([lines]))[0]
yield (terms[3], 1)
... | week3/MIDS-W261-HW-03-Sanchez.ipynb | JasonSanchez/w261 | mit |
Although the same amount of map and reduce tasks were called, because 146 combiner tasks were called, my hypothesis would be that the number of observations read by reducers was less. I went back and included a counter that kept track of the lines passed over the network. With the combiner, only 146 observations were p... | %%writefile Top50.py
from mrjob.job import MRJob
from mrjob.step import MRStep
import csv
import sys
def order_key(order_in_reducer, key_name):
number_of_stars = order_in_reducer//10 + 1
number = str(order_in_reducer%10)
return "%s %s" % ("*"*number_of_stars+number, key_name)
class Top50(MRJob):
MRJ... | week3/MIDS-W261-HW-03-Sanchez.ipynb | JasonSanchez/w261 | mit |
3.2.1
Using 2 reducers: What are the top 50 most frequent terms in your word count analysis?
Present the top 50 terms and their frequency and their relative frequency. Present the top 50 terms and their frequency and their relative frequency. If there are ties please sort the tokens in alphanumeric/string order. Prese... | !head -n 10 Temp_data/ProductPurchaseData.txt
%%writefile ProductPurchaseStats.py
from mrjob.job import MRJob
from mrjob.step import MRStep
import sys
import heapq
class TopList(list):
def __init__(self, max_size):
"""
Just like a list, except the append method adds the new value to the
... | week3/MIDS-W261-HW-03-Sanchez.ipynb | JasonSanchez/w261 | mit |
3.3.1 OPTIONAL
Using 2 reducers: Report your findings such as number of unique products; largest basket; report the top 50 most frequently purchased items, their frequency, and their relative frequency (break ties by sorting the products alphabetical order) etc. using Hadoop Map-Reduce.
HW3.4. (Computationally pro... | %%writefile PairsRecommender.py
from mrjob.job import MRJob
import heapq
import sys
def all_itemsets_of_size_two(array, key=None, return_type="string", concat_val=" "):
"""
Generator that yields all valid itemsets of size two
where each combo is returned in an order sorted by key.
key = None defa... | week3/MIDS-W261-HW-03-Sanchez.ipynb | JasonSanchez/w261 | mit |
HW3.5: Stripes
Repeat 3.4 using the stripes design pattern for finding cooccuring pairs.
Report the compute times for stripes job versus the Pairs job. Describe the computational setup used (E.g., single computer; dual core; linux, number of mappers, number of reducers)
Instrument your mapper, combiner, and reducer to... | %%writefile StripesRecommender.py
from mrjob.job import MRJob
from collections import Counter
import sys
import heapq
def all_itemsets_of_size_two_stripes(array, key=None):
"""
Generator that yields all valid itemsets of size two
where each combo is as a stripe.
key = None defaults to standard so... | week3/MIDS-W261-HW-03-Sanchez.ipynb | JasonSanchez/w261 | mit |
The pairs operation took 1 minute 30 seconds. The stripes operation took 24 seconds, which is about a quarter of the time for pairs.
HW3.6 Computing Relative Frequencies on 100K WikiPedia pages (93Meg)
Dataset description
For this assignment you will explore a set of 100,000 Wikipedia documents:
https://www.dropbox.com... | set([1,2,3])
[1,2,3][:-1] | week3/MIDS-W261-HW-03-Sanchez.ipynb | JasonSanchez/w261 | mit |
Using the Red-Black Tree
Below is a function that will allow us to visualize our tree (copied from CS207 Fall 2016 lecture notes).
Next, we create a tree, add a few nodes to it, and retrieve their contents. | demoDB = Database.connect("/tmp/test1.dbdb")
demoDB.set("rahul", 81)
demoDB.set("pavlos", 20)
demoDB.set("sarah", 29)
demoDB.set("courtney", 11)
demoDB.set("andrew", 12)
demoDB.set("laura", 81)
demoDB.get("sarah")
demoDB.get("laura") | cs207rbtree/demo_RedBlackTree.ipynb | slac207/cs207project | mit |
Multithreadedness | from cs207rbtree import RedBlackTree
from threading import Thread
from pytest import raises
import portalocker
import os
def thread_function(num):
print("FIRST FUN")
db = RedBlackTree.connect("/tmp/test6.dbdb")
db.set("kobe", "baby"+str(num))
print("1")
db.set("rahul", "veryyoung"+str(num))
p... | cs207rbtree/demo_RedBlackTree.ipynb | slac207/cs207project | mit |
If you use A=1.0, f = 10.0, phi = 1.0, fs = 50 and t = 0.1 as input to the function gen_sine() the output numpy array should be:
array([ 0.54030231, -0.63332387, -0.93171798, 0.05749049, 0.96724906])
To generate a sinewave that you can hear, it should be longer and with a higher sampling rate. For example you can use... | # E2 - 1.2: Call the function gen_sine() with the values proposed above, plot and play the output sinusoid
import IPython.display as ipd
### your code here
| notebooks/E2-Sinusoids-and-DFT.ipynb | MTG/sms-tools | agpl-3.0 |
Part 2 - Generate a complex sinusoid
The gen_complex_sine() function should generate the complex sinusoid that is used in DFT computation of length N (samples), corresponding to the frequency index k. [Note that in the DFT we use the conjugate of this complex sinusoid.]
The amplitude of such a complex sinusoid is 1, th... | # E2 - 2.1: Complete function the function gen_complex_sine()
def gen_complex_sine(k, N):
"""Generate one of the complex sinusoids used in the DFT from its frequency index and the DFT lenght.
Args:
k (integer): frequency index of the complex sinusoid of the DFT
N (integer) = length of comp... | notebooks/E2-Sinusoids-and-DFT.ipynb | MTG/sms-tools | agpl-3.0 |
If you run the function gen_complex_sine() using k=1 and N=5, it should return the following numpy array:
array([ 1. + 0.j, 0.30901699 + 0.95105652j, -0.80901699 + 0.58778525j, -0.80901699 - 0.58778525j, 0.30901699 - 0.95105652j]) | # E2 - 2.2: Call gen_complex_sine() with the values suggested above and plot the real and imaginary parts of the
# output complex sinusoid
### your code here
| notebooks/E2-Sinusoids-and-DFT.ipynb | MTG/sms-tools | agpl-3.0 |
Part 3 - Implement the discrete Fourier transform (DFT)
The function dft() should implement the discrete Fourier transform (DFT) equation given above. Given a sequence x of length N, the function should return its spectrum of length N with the frequency indexes ranging from 0 to N-1.
The input argument to the function ... | # E2 - 3.1: Complete the function dft()
def dft(x):
"""Compute the DFT of a signal.
Args:
x (numpy array): input sequence of length N
Returns:
np.array: N point DFT of the input sequence x
"""
## Your code here
| notebooks/E2-Sinusoids-and-DFT.ipynb | MTG/sms-tools | agpl-3.0 |
If you run dft() using as input x = np.array([1, 2, 3, 4]), the function shoulds return the following numpy array:
array([10.0 + 0.0j, -2. +2.0j, -2.0 - 9.79717439e-16j, -2.0 - 2.0j])
Note that you might not get an exact 0 in the output because of the small numerical errors due to the limited precision of the data in... | # E2 - 3.2: Call dft() with the values suggested above and plot the real and imaginary parts of output spectrum
### your code here
| notebooks/E2-Sinusoids-and-DFT.ipynb | MTG/sms-tools | agpl-3.0 |
Part 4 - Implement the inverse discrete Fourier transform (IDFT)
The function idft() should implement the inverse discrete Fourier transform (IDFT) equation given above. Given a frequency spectrum X of length N, the function should return its IDFT x, also of length N. Assume that the frequency index of the input spectr... | # E2 - 4.1: Complete the function idft()
def idft(X):
"""Compute the inverse-DFT of a spectrum.
Args:
X (np.array): frequency spectrum (length N)
Returns:
np.array: N point IDFT of the frequency spectrum X
"""
### Your code here
| notebooks/E2-Sinusoids-and-DFT.ipynb | MTG/sms-tools | agpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.