markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
3.6 [0] Union of sets (O(len(s)+len(t))) | a.union(b) | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
3.7. [0] Sets are MUCH more efficient for searching by content than lists | a = set(range(1000))
print(a)
%timeit '0' in a
a = list(range(1000))
print(a)
%timeit '0' in a | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
4 [0] Dictionaries
Dictionaries are sets where each element (a key) has associated an object (a value). In fact, sets can be seen as dictionaries where the elments have not associations. As sets, dictionaries are efficient for indexing by keys. | help({}) | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
4.1 [0] Static definition of a dictionary | a = {'Macinstosh':'OSX', 'PC':'Windows', 'Macintosh-Linux':'Linux', 'PC-Linux':'Linux'}
a | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
4.2 [0] Indexing of a dictionary by a key (O(1)) | a['PC'] | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
4.3 [0] Testing if a key is the dictionary (O(1)) | 'PC-Linux' in a | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
4.4 [1] Getting the keys (O(n)) | a.keys() | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
4.5 [1] Getting the values (O(n)) | a.values() | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
4.4 [1] Determining the position of a key in a dictionary (O(n)) | list(a.keys()).index("Macintosh-Linux")
for i in a.keys():
print(i) | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
4.6 [0] Inserting a new entry (O(1)) | a['Celullar'] = "Android"
a | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
[0] 4.7 Deleting an entry (O(1)) | del a['Celullar']
a
# Modifiying an entry
a.update({"PC": "Windows 10"})
a | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
4.8 [1] Dictionaries are mutable | id(a)
a['Macintosh-Linux'] = 'Linux for the Mac'
a
id(a) | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
4.9 [0] Looping a dictionary (O(n)) | for i in a:
print(i, a[i])
for i in a.values():
print(i)
for i in a.items():
print(i) | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
5. Bytes
A raw bytes sequence type.
5.1. Creation of bytes sequence | a = b'hello'
print(type(a))
print(a) | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
5.2. Indexing in a bytes sequence | chr(a[1]) | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
5.3. Concatenation of bytes sequences | b = b'world!'
print('"b" is in', id(b))
c = a + b' ' + b
print(c) | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
5.4. Bytes are inmutable | a = b'abc'
print(id(a))
a += b'efg'
print(id(a)) | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
6. Bytearray
Bytearray is a mutable implementation of an array of bytes. Therefore, appending data to a bytearray object is much faster than to a bytes object because in this last case, every append implies to create (and destroy the previous) new bytes object. | %%timeit x = b''
x += b'x'
%%timeit x = bytearray()
x.extend(b'x')
# Array of bytes = 0
x = bytearray(10)
x
len(x)
for i in range(len(x)):
x[i] += 1
x
# A byte in Python is a 0 <= value <= 255.
x[1] = -1
# A bytearray can be created from a list
x = bytearray([1,2,3])
x
import sys
x = bytearray(sys.stdin.re... | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
7. Arrays | import array as arr
a = arr.array('d', [1.1, 3.5, 4.5])
print(a) | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
Element access | a[1]
a[1] = 4.0
a | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
Slice access | a[1:2] | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
Appending elements | a.append(5.0)
a | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
Concatenating arrays | a.extend([5.0, 6.0, 7.0])
a
a += arr.array('d', [1.1, 4.0, 4.5])
a | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
Deleting elements | # By value
a.remove(4.0)
a
# By index
a.pop(3)
a | 02-basics/containers/02-lists.ipynb | vicente-gonzalez-ruiz/YAPT | cc0-1.0 |
Chi-Square Feature Selection
Feature selection is a process where you automatically select those features in your data that contribute most to the prediction variable or output in which you are interested. The benefits of performing feature selection before modeling your data are:
Avoid Overfitting: Less redundant dat... | # suppose we have the following toy text data
X = np.array(['call you tonight', 'Call me a cab', 'please call me... PLEASE!', 'he will call me'])
y = [1, 1, 2, 0]
# we'll convert it to a dense document-term matrix,
# so we can print a more readable output
vect = CountVectorizer()
X_dtm = vect.fit_transform(X)
X_dtm = ... | text_classification/chisquare.ipynb | ethen8181/machine-learning | mit |
One common feature selection method that is used with text data is the Chi-Square feature selection. The $\chi^2$ test is used in statistics to test the independence of two events. More specifically in feature selection we use it to test whether the occurrence of a specific term and the occurrence of a specific class a... | # binarize the output column,
# this makes computing the observed value a
# simple dot product
y_binarized = LabelBinarizer().fit_transform(y)
print(y_binarized)
print()
# our observed count for each class (the row)
# and each feature (the column)
observed = np.dot(y_binarized.T, X_dtm)
print(observed) | text_classification/chisquare.ipynb | ethen8181/machine-learning | mit |
e.g. the second row of the observed array refers to the total count of the terms that belongs to class 1. Then we compute the expected frequencies of each term for each class. | # compute the probability of each class and the feature count;
# keep both as a 2 dimension array using reshape
class_prob = y_binarized.mean(axis = 0).reshape(1, -1)
feature_count = X_dtm.sum(axis = 0).reshape(1, -1)
expected = np.dot(class_prob.T, feature_count)
print(expected)
chisq = (observed - expected) ** 2 / ... | text_classification/chisquare.ipynb | ethen8181/machine-learning | mit |
We can confirm our result with the scikit-learn library using the chi2 function. The following code chunk computes chi-square value for each feature. For the returned tuple, the first element is the chi-square scores, the scores are better if greater. The second element is the p-values, they are better if smaller. | chi2score = chi2(X_dtm, y)
chi2score | text_classification/chisquare.ipynb | ethen8181/machine-learning | mit |
Scikit-learn provides a SelectKBest class that can be used with a suite of different statistical tests. It will rank the features with the statistical test that we've specified and select the top k performing ones (meaning that these terms is considered to be more relevant to the task at hand than the others), where k ... | kbest = SelectKBest(score_func = chi2, k = 4)
X_dtm_kbest = kbest.fit_transform(X_dtm, y)
X_dtm_kbest | text_classification/chisquare.ipynb | ethen8181/machine-learning | mit |
Read an image | cd ~/Dropbox/dev/rainbow/notebooks
from PIL import Image
# img = Image.open('data/cbar/boxer.png')
# img = Image.open('data/cbar/fluid.png')
# img = Image.open('data/cbar/lisa.png')
# img = Image.open('data/cbar/redblu.png')
# img = Image.open('data/cbar/seismic.png')
# img = Image.open('data/cbar/drainage.jpg')
#img... | notebooks/Guessing_colourmaps-NOCROSS.ipynb | kwinkunks/rainbow | apache-2.0 |
Quantize with scikit | n_colours = 100
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
im = np.asarray(img)[..., :3] / 255.
h, w, d = im.shape
im_ = im.reshape((w * h, d))
# Define training set.
n = min(h*w//50, n_colours*10)
sample = shuffle(im_, random_state=0)[:n]
kmeans = KMeans(n_clusters=n_colours).fit(sample)... | notebooks/Guessing_colourmaps-NOCROSS.ipynb | kwinkunks/rainbow | apache-2.0 |
Colinearity adjustment
Approaches to try:
For each point...
How colinear is every triangle this point makes with every other point? (Too many)
How colinear is this point with its 2 nearest neighbours?
How colinear are the three nearest neighbours of this point with each other? (PRobably can't disconnect a point from i... | # ALL TRIPLES
# from itertools import permutations
# triples = np.array(list(permutations(p, 3)))
# triples.shape
# There are n(n - 1) values that "belong" to each point (have it first).
# So maybe I can get a measure of the local linearity of a point
# ... OK this is all too much, let's try something else...
from s... | notebooks/Guessing_colourmaps-NOCROSS.ipynb | kwinkunks/rainbow | apache-2.0 |
Travelling salesman problem
Remember that these points are essentially in random order: | from mpl_toolkits.mplot3d import Axes3D
# Set up the figure
fig = plt.figure(figsize=(8, 8))
# Result of TSP solver
ax = fig.add_subplot(111, projection='3d')
ax.scatter(*p.T, c=p, lw=0, s=40, alpha=1)
ax.plot(*p.T, color='k', alpha=0.4)
ax.set_title('Codebook')
plt.show()
from pytsp import run, dumps_matrix
p = n... | notebooks/Guessing_colourmaps-NOCROSS.ipynb | kwinkunks/rainbow | apache-2.0 |
The zero-point trick is legit. Reference from E. L. Lawler, Jan Karel Lenstra, A. H. G. Rinnooy Kan, D. B. Shmoys (1985). The Traveling Salesman Problem: A Guided Tour of Combinatorial Optimization, 1st Edition. Wiley. 476 pp. ISBN 978-0471904137. | d | notebooks/Guessing_colourmaps-NOCROSS.ipynb | kwinkunks/rainbow | apache-2.0 |
LKH implementation.
K. Helsgaun (2009). General k-opt submoves for the Lin-Kernighan TSP heuristic. Mathematical Programming Computation, 2009, doi: 10.1007/s12532-009-0004-6. | outf = "/tmp/myroute_lkh.tsp"
with open(outf, 'w') as f:
f.write(dumps_matrix(d, name="My Route"))
tour_lkh = run(outf, start=0, solver="LKH")
#result = np.array(tour_concorde['tour'])
result = np.array(tour_lkh['tour'])
result
result.size # Should be n_colours + 2
# e = np.asscalar(np.where(result == result.... | notebooks/Guessing_colourmaps-NOCROSS.ipynb | kwinkunks/rainbow | apache-2.0 |
Now result is the indices of points for the shortest path, shape (256,). And p is our quantized colormap, shape (256, 3). So we can select the points easily for an ordered colourmap.
The offsets are to account for the fact that we added a dark-blue point at the start and a zero point at the end. | c = p[result[1:-1]] | notebooks/Guessing_colourmaps-NOCROSS.ipynb | kwinkunks/rainbow | apache-2.0 |
Ideally I'd like all the distances too, but it wouldn't be too hard to compute these.
Now let's look at it all. | from mpl_toolkits.mplot3d import Axes3D
# Set up the figure
fig = plt.figure(figsize=(8, 8))
# Result of TSP solver
ax = fig.add_subplot(111, projection='3d')
ax.scatter(*c.T, c=c, lw=0, s=40, alpha=1)
ax.plot(*c.T, color='k', alpha=0.4)
ax.set_title('TSP solver')
plt.show() | notebooks/Guessing_colourmaps-NOCROSS.ipynb | kwinkunks/rainbow | apache-2.0 |
Check below an interactive version of the 3D plot. May help when there are complicated paths between points. You need to install plotly and colorlover (with pip) if you don't already have them. | import plotly.graph_objs as go
import colorlover as cl
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
init_notebook_mode(connected=True)
cb = cl.to_rgb(tuple(map(tuple, c*255)))
trace = go.Scatter3d(
name='TSP Sover',
x = c[:,0], y = c[:,1], z = c[:,2],
marker = d... | notebooks/Guessing_colourmaps-NOCROSS.ipynb | kwinkunks/rainbow | apache-2.0 |
Data preparation
We download the MNIST data using tensorflow-datasets: | import tensorflow_datasets as tfds
mnist_data, _ = tfds.load(
name="mnist", batch_size=-1, with_info=True, as_supervised=True
)
mnist_data = tfds.as_numpy(mnist_data)
data_train, data_test = mnist_data["train"], mnist_data["test"] | examples/SGLD.ipynb | blackjax-devs/blackjax | apache-2.0 |
Now we need to apply several transformations to the dataset before splitting it into a test and a test set:
- The images come into 28x28 pixels matrices; we reshape them into a vector;
- The images are arrays of RGB codes between 0 and 255. We normalize them by the maximum value to get a range between 0 and 1;
- We hot... | def one_hot_encode(x, k, dtype=np.float32):
"Create a one-hot encoding of x of size k."
return np.array(x[:, None] == np.arange(k), dtype)
def prepare_data(dataset: tuple, num_categories=10):
X, y = dataset
y = one_hot_encode(y, num_categories)
num_examples = X.shape[0]
num_pixels = 28 * 28
... | examples/SGLD.ipynb | blackjax-devs/blackjax | apache-2.0 |
Model: 3-layer perceptron
We will use a very simple (bayesian) neural network in this example: A MLP with gaussian priors on the weights. We first need a function that computes the model's logposterior density given the data and the current values of the parameters. If we note $X$ the array that represents an image an... | def predict_fn(parameters, X):
"""Returns the probability for the image represented by X
to be in each category given the MLP's weights vakues.
"""
activations = X
for W, b in parameters[:-1]:
outputs = jnp.dot(W, activations) + b
activations = nn.softmax(outputs)
final_W, fina... | examples/SGLD.ipynb | blackjax-devs/blackjax | apache-2.0 |
Sample from the posterior distribution of the perceptron's weights
Now we need to get initial values for the parameters, and we simply sample from their prior distribution: | def init_parameters(rng_key, sizes):
"""
Parameter
----------
rng_key
PRNGKey used by JAX to generate pseudo-random numbers
sizes
List of size for the subsequent layers. The first size must correspond
to the size of the input data and the last one to the number of
ca... | examples/SGLD.ipynb | blackjax-devs/blackjax | apache-2.0 |
We now sample from the model's posteriors. We discard the first 1000 samples until the sampler has reached the typical set, and then take 2000 samples. We record the model's accuracy with the current values every 100 steps. | %%time
import blackjax
from blackjax.sgmcmc.gradients import grad_estimator
data_size = len(y_train)
batch_size = int(0.01 * data_size)
layer_sizes = [784, 100, 10]
step_size = 5e-5
num_warmup = 1000
num_samples = 2000
# Batch the data
rng_key = jax.random.PRNGKey(1)
batches = batch_data(rng_key, (X_train, y_train),... | examples/SGLD.ipynb | blackjax-devs/blackjax | apache-2.0 |
Let us plot the accuracy at different points in the sampling process: | import matplotlib.pylab as plt
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111)
ax.plot(steps, accuracies)
ax.set_xlabel("Number of sampling steps")
ax.set_ylabel("Prediction accuracy")
ax.set_xlim([0, num_warmup + num_samples])
ax.set_ylim([0, 1])
ax.set_yticks([0.1, 0.3, 0.5, 0.7, 0.9])
plt.title("Sample ... | examples/SGLD.ipynb | blackjax-devs/blackjax | apache-2.0 |
Which is not a bad accuracy at all for such a simple model and after only 1000 steps! Remember though that we draw samples from the posterior distribution of the digit probabilities; we can thus use this information to filter out examples for which the model is "unsure" of its prediction.
Here we will say that the mode... | predicted_class = np.exp(
np.stack([jax.vmap(predict_fn, in_axes=(None, 0))(s, X_test) for s in samples])
)
max_predicted = [np.argmax(predicted_class[:, i, :], axis=1) for i in range(60000)]
freq_max_predicted = np.array(
[
(max_predicted[i] == np.argmax(np.bincount(max_predicted[i]))).sum() / 2000
... | examples/SGLD.ipynb | blackjax-devs/blackjax | apache-2.0 |
Let's plot a few examples where the model was very uncertain: | most_uncertain_idx = np.argsort(freq_max_predicted)
for i in range(10):
print(np.bincount(max_predicted[most_uncertain_idx[i]]) / 2000)
fig = plt.figure()
plt.imshow(X_test[most_uncertain_idx[i]].reshape(28, 28), cmap="gray")
plt.show() | examples/SGLD.ipynb | blackjax-devs/blackjax | apache-2.0 |
And now compute the average accuracy over all the samples without these uncertain predictions: | avg_accuracy = np.mean(
[compute_accuracy(s, X_test[certain_mask], y_test[certain_mask]) for s in samples]
)
print(
f"The average accuracy removing the samples for which the model is uncertain is {avg_accuracy:.3f}"
) | examples/SGLD.ipynb | blackjax-devs/blackjax | apache-2.0 |
Create batch class depended from MnistBatch | mnistset = MNIST(batch_class=MnistBatch) | examples/experiments/augmentation/augmentation.ipynb | analysiscenter/dataset | apache-2.0 |
Already familiar to us the construction to create the pipelines. These pipelines train NN on simple MNIST images, without shift. | normal_train_ppl = (
mnistset.train.p
.init_model('dynamic',
ConvModel,
'conv',
config={'inputs': dict(images={'shape': (28, 28, 1)},
labels={'classes': (10),
'transform': 'ohe'... | examples/experiments/augmentation/augmentation.ipynb | analysiscenter/dataset | apache-2.0 |
Train the model by using next_batch method | batch_size = 400
for i in tqn(range(600)):
normal_train_ppl.next_batch(batch_size, n_epochs=None)
normal_test_ppl.next_batch(batch_size, n_epochs=None) | examples/experiments/augmentation/augmentation.ipynb | analysiscenter/dataset | apache-2.0 |
Get variable from pipeline and print accuracy on data without shift | acc = normal_test_ppl.get_variable('test_accuracy')
print('Accuracy on normal data: {:.2%}'.format(acc)) | examples/experiments/augmentation/augmentation.ipynb | analysiscenter/dataset | apache-2.0 |
Now check, how change accuracy, if the first model testing on shift data | shift_test_ppl= (
mnistset.test.p
.import_model('conv', normal_train_ppl)
.shift_flattened_pic()
.init_variable('predict', init_on_each_run=int)
.predict_model('conv',
fetches='output_accuracy',
feed_dict={'images': B('images'),
'l... | examples/experiments/augmentation/augmentation.ipynb | analysiscenter/dataset | apache-2.0 |
In order for the model to be able to predict the augmentation data, we will teach it on such data | shift_train_ppl = (
mnistset.train.p
.shift_flattened_pic()
.init_model('dynamic',
ConvModel,
'conv',
config={'inputs': dict(images={'shape': (28, 28, 1)},
labels={'classes': (10),
... | examples/experiments/augmentation/augmentation.ipynb | analysiscenter/dataset | apache-2.0 |
And now check, how change accuracy on shift data | shift_test_ppl = (
mnistset.test.p
.import_model('conv', shift_train_ppl)
.shift_flattened_pic()
.init_variable('acc', init_on_each_run=list)
.init_variable('img', init_on_each_run=list)
.init_variable('predict', init_on_each_run=list)
.predict_model('conv',
fetches=['out... | examples/experiments/augmentation/augmentation.ipynb | analysiscenter/dataset | apache-2.0 |
It's really better than before.
It is interesting, on what figures we are mistaken? | acc = shift_test_ppl.get_variable('acc')
img = shift_test_ppl.get_variable('img')
predict = shift_test_ppl.get_variable('predict')
_, ax = plt.subplots(3, 4, figsize=(16, 16))
ax = ax.reshape(-1)
for i in range(12):
index = np.where(np.array(acc) == 0)[0][i]
ax[i].imshow(img[index]['images'].reshape(-1,28))
... | examples/experiments/augmentation/augmentation.ipynb | analysiscenter/dataset | apache-2.0 |
Create a very small data set | xs = [0., 1., 2., 3., 4., 5., 6., 7.] # feature (independent variable)
ys = [-.82, -.94, -.12, .26, .39, .64, 1.02, 1.] # labels (dependent variable)
fig, ax = plt.subplots()
_ = ax.scatter(xs, ys) | notebooks/tensor-fied_intro_to_tensorflow.ipynb | the-deep-learners/nyc-ds-academy | mit |
Define variables -- the model parameters we'll learn -- and initialize them with "random" values | m = tf.Variable(-0.5)
b = tf.Variable(1.0) | notebooks/tensor-fied_intro_to_tensorflow.ipynb | the-deep-learners/nyc-ds-academy | mit |
One single point at a time, define the error between the true label and the model's prediction of the label | ys_model = m*xs + b
total_error = tf.reduce_sum((ys-ys_model)**2) | notebooks/tensor-fied_intro_to_tensorflow.ipynb | the-deep-learners/nyc-ds-academy | mit |
Define optimizer as SSE-minimizing gradient descent | optimizer_operation = tf.train.GradientDescentOptimizer(learning_rate=0.005).minimize(total_error) | notebooks/tensor-fied_intro_to_tensorflow.ipynb | the-deep-learners/nyc-ds-academy | mit |
Define an operator that will initialize the graph with all available global variables | initializer_op = tf.global_variables_initializer() | notebooks/tensor-fied_intro_to_tensorflow.ipynb | the-deep-learners/nyc-ds-academy | mit |
With the computational graph designed, we initialize a session to execute it | with tf.Session() as sess:
sess.run(initializer_op)
n_epochs = 100
for iteration in range(n_epochs):
sess.run(optimizer_operation)
slope, intercept = sess.run([m, b])
slope
intercept | notebooks/tensor-fied_intro_to_tensorflow.ipynb | the-deep-learners/nyc-ds-academy | mit |
Calculate the predicted model outputs given the inputs xs | y_hat = slope*np.array(xs) + intercept
pd.DataFrame(list(zip(ys, y_hat)), columns=['y', 'y_hat'])
fig, ax = plt.subplots()
ax.scatter(xs, ys)
x_min, x_max = ax.get_xlim()
y_min, y_max = intercept, intercept + slope*(x_max-x_min)
ax.plot([x_min, x_max], [y_min, y_max])
_ = ax.set_xlim([x_min, x_max]) | notebooks/tensor-fied_intro_to_tensorflow.ipynb | the-deep-learners/nyc-ds-academy | mit |
Write a function derivs for usage with scipy.integrate.odeint that computes the derivatives for the damped, driven harmonic oscillator. The solution vector at each time will be $\vec{y}(t) = (\theta(t),\omega(t))$. | def derivs(y, t, a, b, omega0):
"""Compute the derivatives of the damped, driven pendulum.
Parameters
----------
y : ndarray
The solution vector at the current time t[i]: [theta[i],omega[i]].
t : float
The current time t[i].
a, b, omega0: float
The parameters in the ... | assignments/assignment10/ODEsEx03.ipynb | SJSlavin/phys202-2015-work | mit |
We begin with def then a space followed by the name of the function. Try to keep names relevant, for example len() is a good name for a length() function. Also be careful with names, you wouldn't want to call a function the same name as a built-in function in Python (such as len).
Next come a pair of parenthesis with a... | def say_hello():
print 'hello' | PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Functions-checkpoint.ipynb | yashdeeph709/Algorithms | apache-2.0 |
Call the function | say_hello() | PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Functions-checkpoint.ipynb | yashdeeph709/Algorithms | apache-2.0 |
Example 2: A simple greeting function
Let's write a function that greets people with their name. | def greeting(name):
print 'Hello %s' %name
greeting('Jose') | PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Functions-checkpoint.ipynb | yashdeeph709/Algorithms | apache-2.0 |
Using return
Let's see some example that use a return statement. return allows a function to return a result that can then be stored as a variable, or used in whatever manner a user wants.
Example 3: Addition function | def add_num(num1,num2):
return num1+num2
add_num(4,5)
# Can also save as variable due to return
result = add_num(4,5)
print result | PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Functions-checkpoint.ipynb | yashdeeph709/Algorithms | apache-2.0 |
What happens if we input two strings? | print add_num('one','two') | PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Functions-checkpoint.ipynb | yashdeeph709/Algorithms | apache-2.0 |
Note that because we don't declare variable types in Python, this function could be used to add numbers or sequences together! We'll later learn about adding in checks to make sure a user puts in the correct arguments into a function.
Lets also start using break,continue, and pass statements in our code. We introduced ... | def is_prime(num):
'''
Naive method of checking for primes.
'''
for n in range(2,num):
if num % n == 0:
print 'not prime'
break
else: # If never mod zero, then prime
print 'prime'
is_prime(16) | PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Functions-checkpoint.ipynb | yashdeeph709/Algorithms | apache-2.0 |
Note how we break the code after the print statement! We can actually improve this by only checking to the square root of the target number, also we can disregard all even numbers after checking for 2. We'll also switch to returning a boolean value to get an exaple of using return statements: | import math
def is_prime(num):
'''
Better method of checking for primes.
'''
if num % 2 == 0 and num > 2:
return False
for i in range(3, int(math.sqrt(num)) + 1, 2):
if num % i == 0:
return False
return True
is_prime(14) | PythonBootCamp/Complete-Python-Bootcamp-master/.ipynb_checkpoints/Functions-checkpoint.ipynb | yashdeeph709/Algorithms | apache-2.0 |
Read in file
We have a dataset saved in the repository: cascadia.npz. This contains topography and bathymetry data from Washington state. | d = np.load('../data/cascadia.npz') # data was saved in compressed numpy format | examples/numpy.ipynb | hetland/python4geosciences | mit |
What is contained in this file? | d.keys() # notice that d is a dictionary!
d['z'].shape # this is an array instead of a list, so it can have more than 1 dimension | examples/numpy.ipynb | hetland/python4geosciences | mit |
Investigate
Let's start with a quick look at the data. We'll keep it simple since we aren't to the plotting section yet. | %matplotlib inline
import matplotlib.pyplot as plt
import cmocean.cm as cmo
plt.figure(figsize=(10, 8))
plt.pcolormesh(d['lon'], d['lat'], d['z'], cmap=cmo.delta)
plt.colorbar()
plt.xlabel('Longitude [deg]')
plt.ylabel('Latitude [deg]')
plt.title('Topography and bathymetry [m]') | examples/numpy.ipynb | hetland/python4geosciences | mit |
Anyone recognize this?
Let's do a few calculations using numpy.
How about a mean: | z = d['z'] # we can rename the vertical data information to save a little space
z.mean() | examples/numpy.ipynb | hetland/python4geosciences | mit |
So overall we have a mean value of about -5 meters. But how meaningful is this? Let's break it down further.
We have both positive and negative values, and they represent pretty distinct areas: above and below water. It is logical that we separate the two. | iabove = z > 0 # indices of the z values that are above water
ibelow = z < 0 # indices of z values that are below water
print('above water: ', z[iabove])
print('below water: ', z[ibelow]) | examples/numpy.ipynb | hetland/python4geosciences | mit |
Look good! Now let's do something with them.
First, how about the mean vertical level, separate for above and below water. | z[iabove].mean()
z[ibelow].mean() | examples/numpy.ipynb | hetland/python4geosciences | mit |
This data is from the Council Grove gas reservoir in Southwest Kansas. The Panoma Council Grove Field is predominantly a carbonate gas reservoir encompassing 2700 square miles in Southwestern Kansas. This dataset is from nine wells (with 4149 examples), consisting of a set of seven predictor variables and a rock faci... | training_data['Well Name'] = training_data['Well Name'].astype('category')
training_data['Formation'] = training_data['Formation'].astype('category')
training_data['Well Name'].unique() | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
These are the names of the 10 training wells in the Council Grove reservoir. Data has been recruited into pseudo-well 'Recruit F9' to better represent facies 9, the Phylloid-algal bafflestone.
Before we plot the well data, let's define a color map so the facies are represented by consistent color in all the plots in ... | # 1=sandstone 2=c_siltstone 3=f_siltstone # 4=marine_silt_shale
#5=mudstone 6=wackestone 7=dolomite 8=packstone 9=bafflestone
facies_colors = ['#F4D03F', '#F5B041', '#DC7633','#A569BD',
'#000000', '#000080', '#2E86C1', '#AED6F1', '#196F3D']
facies_labels = ['SS', 'CSiS', 'FSiS', 'SiSh', 'MS',
... | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
This is a quick view of the statistical distribution of the input variables. Looking at the count values, most values have 4149 valid values except for PE, which has 3232. We will drop the feature vectors that don't have a valid PE entry. | PE_mask = training_data['PE'].notnull().values
training_data = training_data[PE_mask]
training_data.describe() | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Now we extract just the feature variables we need to perform the classification. The predictor variables are the five log values and two geologic constraining variables, and we are also using depth. We also get a vector of the facies labels that correspond to each feature vector. | y = training_data['Facies'].values
print y[25:40]
print np.shape(y)
X = training_data.drop(['Formation', 'Well Name','Facies','FaciesLabels'], axis=1)
print np.shape(X)
X.describe(percentiles=[.05, .25, .50, .75, .95])
scaler = preprocessing.StandardScaler().fit(X)
X = scaler.transform(X) | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Make performance scorers
Used to evaluate performance. | Fscorer = make_scorer(f1_score, average = 'micro') | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Pre-tuned SVM classifier classifier and leave one well out average F1 score
This is the Support Vector Machine classifier from our first submission. | from sklearn import svm
SVC_classifier = svm.SVC(C = 100, cache_size=2400, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma=0.01, kernel='rbf',
max_iter=-1, probability=True, random_state=49, shrinking=True,
tol=0.001, verbose=False)
f1_svc = []
wells = training_data["Well Name"].valu... | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Pre-tuned multi-layer perceptron classifier and average F1 score | from sklearn.neural_network import MLPClassifier
mlp_classifier = MLPClassifier(activation='logistic', alpha=0.01, batch_size='auto',
beta_1=0.9, beta_2=0.999, early_stopping=False, epsilon=1e-08,
hidden_layer_sizes=(100,), learning_rate='adaptive',
learning_rate_init=0.001, max_iter=1000, momentum... | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Pre-tuned extra trees
This is the RF classifier with parameters tuned in the leading submission, by George Crowther, but without his engineered features. | from sklearn.pipeline import make_pipeline
from sklearn.feature_selection import VarianceThreshold
from sklearn.ensemble import ExtraTreesClassifier
ET_classifier = make_pipeline(
VarianceThreshold(threshold=0.49),
ExtraTreesClassifier(criterion="entropy", max_features=0.71,
n_estimato... | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Plurality voting classifier (multi-class majority voting)
We will use a weighted approach, where the weights are somewhat arbitrary, but their proportion is based on the average f1 score of the individual classifiers. | from sklearn.ensemble import VotingClassifier
eclf_cv = VotingClassifier(estimators=[
('SVC', SVC_classifier), ('MLP', mlp_classifier), ('ET', ET_classifier)],
voting='soft', weights=[0.3,0.33,0.37]) | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Leave one-well-out F1 scores | f1_ens = []
wells = training_data["Well Name"].values
logo = LeaveOneGroupOut()
for train, test in logo.split(X, y, groups=wells):
well_name = wells[test[0]]
eclf_cv.fit(X[train], y[train])
pred_cv = eclf_cv.predict(X[test])
sc = f1_score(y[test], pred_cv, labels = np.arange(10), average = 'micro')
... | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Comments
Using the average F1 score from the leave-one-well out cross validation as a metric, the majority voting is superior to the individual classifiers, including the pre-tuned Random Forest from the leading submission. However, the Random Forest in the official leading submission was trained using additional new f... | blind = pd.read_csv('validation_data_nofacies.csv')
X_blind = np.array(blind.drop(['Formation', 'Well Name'], axis=1))
X_blind = scaler.transform(X_blind)
y_pred = eclf_cv.fit(X, y).predict(X_blind)
blind['Facies'] = y_pred
def make_facies_log_plot(logs, facies_colors):
#make sure logs are sorted by depth
... | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Displaying predicted versus original facies in the training data
This is a nice display to finish up with, as it gives us a visual idea of the predicted faces where we have facies from the core observations.
The plot we will use a function from the original notebook. Let's look at the well with the lowest F1 from the p... | def compare_facies_plot(logs, compadre, facies_colors):
#make sure logs are sorted by depth
logs = logs.sort_values(by='Depth')
cmap_facies = colors.ListedColormap(
facies_colors[0:len(facies_colors)], 'indexed')
ztop=logs.Depth.min(); zbot=logs.Depth.max()
cluster1 = np.repeat... | MandMs/Facies_classification-M&Ms_plurality_voting_classifier.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Your custom density file
First, let's look at an example of a custom density file.
80 day
0 9500 9e-16
1 10500 6e-16
2 12000 2e-17
The first line specifies the time in days after the explosion
After a skipped line, each row corresponds to a shell with index specified by the first column.
The second column lists the ve... | model = tardis.run_tardis('./test_config.yml') | docs/models/examples/Custom_Density_And_Boundary_Velocities.ipynb | kaushik94/tardis | bsd-3-clause |
You can check to make sure that the model loaded and used by TARDIS during the simulation is consistent with your expectations based on the custom files you provided: | print('v_inner_boundary = ',model.model.v_boundary_inner)
print('v_outer_boundary = ',model.model.v_boundary_outer)
print('\n')
print('velocities of shell boundaries: ')
print(model.model.velocity)
print('\n')
print('densities loaded by TARDIS: (NOTE that the density in the first line of the file was ignored! Densities... | docs/models/examples/Custom_Density_And_Boundary_Velocities.ipynb | kaushik94/tardis | bsd-3-clause |
Specifying boundary velocities in the config file
In addition to specifying custom density and abundance files, the user can set the v_inner_boundary and v_outer_boundary velocities in the YAML config file. This can cause some confusion, so we carefully go through some examples.
IMPORTANT
Boundary velocities set in the... | model = tardis.run_tardis('./test_config_ex1.yml') | docs/models/examples/Custom_Density_And_Boundary_Velocities.ipynb | kaushik94/tardis | bsd-3-clause |
Example 2) v_outer_boundary larger than last velocity in density file
In this example, the last velocity in the density file is 12000 km/s. The user can specify in the config file the velocity of the outer boundary to a larger velocity, say v_outer_boundary = 13000 km/s. This will cause TARDIS to raise an error. | model = tardis.run_tardis('./test_config_ex2.yml') | docs/models/examples/Custom_Density_And_Boundary_Velocities.ipynb | kaushik94/tardis | bsd-3-clause |
Example 3) v_boundaries in config file are within density file velocity range
Here the user sets v_inner_boundary = 9700 and v_outer_boundary = 11500 in the config file. Both values fall within the velocity range specified by the custom density file. | model = tardis.run_tardis('./test_config_ex3.yml')
print('v_inner_boundary = ',model.model.v_boundary_inner)
print('v_outer_boundary = ',model.model.v_boundary_outer)
print('\n')
print('velocities of shell boundaries: ')
print(model.model.velocity)
print('\n')
print('densities loaded by TARDIS: (NOTE that the density ... | docs/models/examples/Custom_Density_And_Boundary_Velocities.ipynb | kaushik94/tardis | bsd-3-clause |
The :class:Raw <mne.io.Raw> data structure: continuous data | from __future__ import print_function
import mne
import os.path as op
from matplotlib import pyplot as plt | 0.14/_downloads/plot_object_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Continuous data is stored in objects of type :class:Raw <mne.io.Raw>.
The core data structure is simply a 2D numpy array (channels × samples,
stored in a private attribute called ._data) combined with an
:class:Info <mne.Info> object (.info attribute)
(see tut_info_objects).
The most common way to load cont... | # Load an example dataset, the preload flag loads the data into memory now
data_path = op.join(mne.datasets.sample.data_path(), 'MEG',
'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(data_path, preload=True)
raw.set_eeg_reference() # set EEG average reference
# Give the sample rate
pr... | 0.14/_downloads/plot_object_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
<div class="alert alert-info"><h4>Note</h4><p>Accessing the `._data` attribute is done here for educational
purposes. However this is a private attribute as its name starts
with an `_`. This suggests that you should **not** access this
variable directly but rely on indexing syntax detailed... | # Extract data from the first 5 channels, from 1 s to 3 s.
sfreq = raw.info['sfreq']
data, times = raw[:5, int(sfreq * 1):int(sfreq * 3)]
_ = plt.plot(times, data.T)
_ = plt.title('Sample channels') | 0.14/_downloads/plot_object_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Selecting subsets of channels and samples
It is possible to use more intelligent indexing to extract data, using
channel names, types or time ranges. | # Pull all MEG gradiometer channels:
# Make sure to use .copy() or it will overwrite the data
meg_only = raw.copy().pick_types(meg=True)
eeg_only = raw.copy().pick_types(meg=False, eeg=True)
# The MEG flag in particular lets you specify a string for more specificity
grad_only = raw.copy().pick_types(meg='grad')
# Or ... | 0.14/_downloads/plot_object_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Notice the different scalings of these types | f, (a1, a2) = plt.subplots(2, 1)
eeg, times = eeg_only[0, :int(sfreq * 2)]
meg, times = meg_only[0, :int(sfreq * 2)]
a1.plot(times, meg[0])
a2.plot(times, eeg[0])
del eeg, meg, meg_only, grad_only, eeg_only, data, specific_chans | 0.14/_downloads/plot_object_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
You can restrict the data to a specific time range | raw = raw.crop(0, 50) # in seconds
print('New time range from', raw.times.min(), 's to', raw.times.max(), 's') | 0.14/_downloads/plot_object_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
And drop channels by name | nchan = raw.info['nchan']
raw = raw.drop_channels(['MEG 0241', 'EEG 001'])
print('Number of channels reduced from', nchan, 'to', raw.info['nchan']) | 0.14/_downloads/plot_object_raw.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.