markdown
stringlengths 0
37k
| code
stringlengths 1
33.3k
| path
stringlengths 8
215
| repo_name
stringlengths 6
77
| license
stringclasses 15
values |
---|---|---|---|---|
Cycling Output Container | l = CyclingOutputContainerLayoutManager()
l.setPeriod(2345); # milliseconds
l.setBorderDisplayed(False);
o = OutputContainer()
o.setLayoutManager(l)
o.addItem(plot1, "Scatter with History")
o.addItem(plot2, "Short Term")
o.addItem(plot3, "Long Term")
o | doc/python/OutputContainers.ipynb | jpallas/beakerx | apache-2.0 |
Define service account credentials | # INSERT YOUR SERVICE ACCOUNT HERE
SERVICE_ACCOUNT='[email protected]'
KEY = 'private-key.json'
!gcloud iam service-accounts keys create {KEY} --iam-account {SERVICE_ACCOUNT} | python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb | google/earthengine-api | apache-2.0 |
Create an authorized session to make HTTP requests | from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(KEY)
scoped_credentials = credentials.with_scopes(
['https://www.googleapis.com/auth/cloud-platform'])
session = AuthorizedSession(scoped_credentials)
url = 'https://earthengine.googleapis.com/v1alpha/projects/earthengine-public/assets/LANDSAT'
response = session.get(url)
from pprint import pprint
import json
pprint(json.loads(response.content))
| python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb | google/earthengine-api | apache-2.0 |
Get a list of images at a point
Query for Sentinel-2 images at a specific location, in a specific time range and with estimated cloud cover less than 10%. | import urllib
coords = [-122.085, 37.422]
project = 'projects/earthengine-public'
asset_id = 'COPERNICUS/S2'
name = '{}/assets/{}'.format(project, asset_id)
url = 'https://earthengine.googleapis.com/v1alpha/{}:listImages?{}'.format(
name, urllib.parse.urlencode({
'startTime': '2017-04-01T00:00:00.000Z',
'endTime': '2017-05-01T00:00:00.000Z',
'region': '{"type":"Point", "coordinates":' + str(coords) + '}',
'filter': 'CLOUDY_PIXEL_PERCENTAGE < 10',
}))
response = session.get(url)
content = response.content
for asset in json.loads(content)['images']:
id = asset['id']
cloud_cover = asset['properties']['CLOUDY_PIXEL_PERCENTAGE']
print('%s : %s' % (id, cloud_cover)) | python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb | google/earthengine-api | apache-2.0 |
Inspect an image
Get the asset name from the previous output and request its metadata. | asset_id = 'COPERNICUS/S2/20170430T190351_20170430T190351_T10SEG'
name = '{}/assets/{}'.format(project, asset_id)
url = 'https://earthengine.googleapis.com/v1alpha/{}'.format(name)
response = session.get(url)
content = response.content
asset = json.loads(content)
print('Band Names: %s' % ','.join(band['id'] for band in asset['bands']))
print('First Band: %s' % json.dumps(asset['bands'][0], indent=2, sort_keys=True)) | python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb | google/earthengine-api | apache-2.0 |
Get pixels from one of the images | import numpy
import io
name = '{}/assets/{}'.format(project, asset_id)
url = 'https://earthengine.googleapis.com/v1alpha/{}:getPixels'.format(name)
body = json.dumps({
'fileFormat': 'NPY',
'bandIds': ['B2', 'B3', 'B4', 'B8'],
'grid': {
'affineTransform': {
'scaleX': 10,
'scaleY': -10,
'translateX': 499980,
'translateY': 4200000,
},
'dimensions': {'width': 256, 'height': 256},
},
})
pixels_response = session.post(url, body)
pixels_content = pixels_response.content
array = numpy.load(io.BytesIO(pixels_content))
print('Shape: %s' % (array.shape,))
print('Data:')
print(array) | python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb | google/earthengine-api | apache-2.0 |
Get a thumbnail of an image
Note that name and asset are already defined from the request to get the asset metadata. | url = 'https://earthengine.googleapis.com/v1alpha/{}:getPixels'.format(name)
body = json.dumps({
'fileFormat': 'PNG',
'bandIds': ['B4', 'B3', 'B2'],
'region': asset['geometry'],
'grid': {
'dimensions': {'width': 256, 'height': 256},
},
'visualizationOptions': {
'ranges': [{'min': 0, 'max': 3000}],
},
})
image_response = session.post(url, body)
image_content = image_response.content
# Import the Image function from the IPython.display module.
from IPython.display import Image
Image(image_content) | python/examples/ipynb/Earth_Engine_REST_API_Quickstart.ipynb | google/earthengine-api | apache-2.0 |
3. Equations
Markdown allows you to write mathematical equations using LaTeX that will be rendered using MathJax. The simplest way of including an equations is to wrap the LaTeX code in sets of double dollar signs, "$$":
Planck Equation:
$$ B_{\lambda}(\lambda, T) = \frac{2hc^2}{\lambda^5} \frac{1}{e^{\frac{hc}{\lambda k_B T}} - 1}$$
Another, more difficult, method of writing equations is to instead use a cell block as a LaTeX block. This may be accomplished using "cell magics", specifically "%%latex": | %%latex
\begin{aligned}
B_{\lambda}(\lambda, T) = \frac{2hc^2}{\lambda^5} \frac{1}{e^{\frac{hc}{\lambda k_B T}} - 1}
\end{aligned} | lessons/jupyter/3_basic_demo.ipynb | ashiklom/studyGroup | apache-2.0 |
You can also use "line magics" to write LaTeX inline in Markdown cells:
%latex \begin{aligned} B_{\lambda}(\lambda, T) = \frac{2hc^2}{\lambda^5} \frac{1}{e^{\frac{hc}{\lambda k_B T}} - 1} \end{aligned}
4. Code
You can, of course, also include code in the notebook as code is the default cell type.
Let's create a function for Planck's Law: | import numpy as np
def planck(wavelength, temp):
""" Return the emitted radiation from a blackbody of a given temp and wavelength
Args:
wavelength (float): wavelength (m)
temp (float): temperature of black body (Kelvin)
Returns:
float: spectral radiance (W / (sr m^3))
"""
k_b = 1.3806488e-23 # J/K Boltzmann constant
h = 6.626070040e-34 # J s - Planck's constant
c = 3e8 # m/s - speed of light
return ((2 * h * c ** 2) / wavelength ** 5 *
1 / (np.exp(h * c / (wavelength * k_b * temp)) - 1))
for temp in (3000, 4000, 5000):
rad = planck(0.5e-6, temp)
rad_kW_per_sr_m2_nm = rad / 1e3 / 1e9 # convert from W to kW and m to nm
print('%.3f K: %.5f kW/(sr m^2 nm)' % (temp, rad_kW_per_sr_m2_nm)) | lessons/jupyter/3_basic_demo.ipynb | ashiklom/studyGroup | apache-2.0 |
5. Visualization
Not only can the notebooks display console style text outputs from the code, but it can also display and save very detaild plots.
Below I use the Python plotting library, matplotlib, to reproduce the plot displayed in section 2. | # Import and alias to "plt"
import matplotlib.pyplot as plt
# Calculate
wavelength = np.linspace(1e-7, 3e-6, 1000)
temp = np.array([3000, 4000, 5000])
rad = np.zeros((wavelength.size, temp.size), dtype=np.float)
for i, t in enumerate(temp):
rad[:, i] = planck(wavelength, t)
% matplotlib nbagg
# Plot
text_x = wavelength[rad.argmax(axis=0)] * 1e6
text_y = rad.max(axis=0) / 1e3 / 1e9
temp_str = ['%.2f K' % t for t in temp]
fig, ax = plt.subplots()
ax.plot(wavelength * 1e6, rad / 1e3 / 1e9)
for _x, _y, _temp in zip(text_x, text_y, temp_str):
ax.text(_x, _y, _temp, ha='center')
plt.legend(labels=['%.2f K' % t for t in temp])
plt.xlabel(r'Wavelength ($\mu m$)')
plt.ylabel(r'Spectral radiance ($kW \cdot sr^{-1} \cdot m^{-2} \cdot nm^{-1}$)') | lessons/jupyter/3_basic_demo.ipynb | ashiklom/studyGroup | apache-2.0 |
Load data
Similar to previous exercises, we will load CIFAR-10 data from disk. | from utils.data_utils import get_CIFAR10_data
cifar10_dir = 'datasets/cifar-10-batches-py'
X_train, y_train, X_val, y_val, X_test, y_test = get_CIFAR10_data(cifar10_dir, num_training=49000, num_validation=1000, num_test=1000)
print (X_train.shape, y_train.shape, X_val.shape, y_val.shape, X_test.shape, y_test.shape) | test/features.ipynb | zklgame/CatEyeNets | mit |
Extract Features
For each image we will compute a Histogram of Oriented
Gradients (HOG) as well as a color histogram using the hue channel in HSV
color space. We form our final feature vector for each image by concatenating
the HOG and color histogram feature vectors.
Roughly speaking, HOG should capture the texture of the image while ignoring
color information, and the color histogram represents the color of the input
image while ignoring texture. As a result, we expect that using both together
ought to work better than using either alone. Verifying this assumption would
be a good thing to try for the bonus section.
The hog_feature and color_histogram_hsv functions both operate on a single
image and return a feature vector for that image. The extract_features
function takes a set of images and a list of feature functions and evaluates
each feature function on each image, storing the results in a matrix where
each column is the concatenation of all feature vectors for a single image. | from utils.features_utils import extract_features, hog_feature, color_histogram_hsv
num_color_bins = 10 # Number of bins in the color histogram
feature_fns = [hog_feature, lambda img: color_histogram_hsv(img, nbin=num_color_bins)]
X_train_feats = extract_features(X_train, feature_fns, verbose=True)
X_val_feats = extract_features(X_val, feature_fns)
X_test_feats = extract_features(X_test, feature_fns)
# Preprocessing: Subtract the mean feature
mean_feat = np.mean(X_train_feats, axis=0, keepdims=True)
X_train_feats -= mean_feat
X_val_feats -= mean_feat
X_test_feats -= mean_feat
# Preprocessing: Divide by standard deviation.
# This ensures that each feature has roughly the same scale.
std_feat = np.std(X_train_feats, axis=0, keepdims=True)
X_train_feats /= std_feat
X_val_feats /= std_feat
X_test_feats /= std_feat
# Preprocessing: Add a bias dimension
X_train_feats = np.hstack([X_train_feats, np.ones([X_train_feats.shape[0], 1])])
X_val_feats = np.hstack([X_val_feats, np.ones([X_val_feats.shape[0], 1])])
X_test_feats = np.hstack([X_test_feats, np.ones([X_test_feats.shape[0], 1])]) | test/features.ipynb | zklgame/CatEyeNets | mit |
Train SVM on features
Using the multiclass SVM code developed earlier in the assignment, train SVMs on top of the features extracted above; this should achieve better results than training SVMs directly on top of raw pixels. | # Use the validation set to tune the learning rate and regularization strength
# val accuracy should reach near 0.44
from classifiers.linear_classifier import LinearSVM
learning_rates = [1e-4, 3e-4, 9e-4, 1e-3, 3e-3, 9e-3, 1e-2, 3e-2, 9e-2, 1e-1]
regularization_strengths = [1e-1, 3e-1, 9e-1, 1, 3, 9]
# results[(learning_rate, reg)] = (train_accuracy, val_accuracy)
results = {}
best_val = -1
best_svm = None
for learning_rate in learning_rates:
for reg in regularization_strengths:
model = LinearSVM()
model.train(X_train_feats, y_train, learning_rate=learning_rate, reg=reg, num_iters=5000,
batch_size=300, verbose=True)
y_train_pred = model.predict(X_train_feats)
train_accuracy = np.mean(y_train == y_train_pred)
y_val_pred = model.predict(X_val_feats)
val_accuracy = np.mean(y_val == y_val_pred)
results[(learning_rate, reg)] = (train_accuracy, val_accuracy)
if val_accuracy > best_val:
best_val = val_accuracy
best_svm = model
print('lr %e reg %e train_accuracy: %f val_accuracy: %f' % (learning_rate, reg, train_accuracy, val_accuracy))
print
for lr, reg in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print('lr %e reg %e train_accuracy: %f val_accuracy: %f' % (lr, reg, train_accuracy, val_accuracy))
print('best validation accuracy achieved during cross-validation: %f' % best_val)
for lr, reg in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print('lr %e reg %e train_accuracy: %f val_accuracy: %f' % (lr, reg, train_accuracy, val_accuracy))
# Evaluate the best svm on test set
y_test_pred = best_svm.predict(X_test_feats)
test_accuracy = np.mean(y_test == y_test_pred)
print('linear SVM on raw pixels final test set accuracy: %f' % test_accuracy)
# An important way to gain intuition about how an algorithm works is to
# visualize the mistakes that it makes. In this visualization, we show examples
# of images that are misclassified by our current system. The first column
# shows images that our system labeled as "plane" but whose true label is
# something other than "plane".
examples_per_class = 8
classes = ['plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
for cls, cls_name in enumerate(classes):
idxs = np.where((y_test != cls) & (y_test_pred == cls))[0]
idxs = np.random.choice(idxs, examples_per_class, replace=False)
for i, idx in enumerate(idxs):
plt.subplot(examples_per_class, len(classes), i * len(classes) + cls + 1)
plt.imshow(X_test[idx].astype('uint8'))
plt.axis('off')
if i == 0:
plt.title(cls_name)
plt.show() | test/features.ipynb | zklgame/CatEyeNets | mit |
Inline question 1:
Describe the misclassification results that you see. Do they make sense?
not obvious sense
Neural Network on image features
Earlier in this assigment we saw that training a two-layer neural network on raw pixels achieved better classification performance than linear classifiers on raw pixels. In this notebook we have seen that linear classifiers on image features outperform linear classifiers on raw pixels.
For completeness, we should also try training a neural network on image features. This approach should outperform all previous approaches: you should easily be able to achieve over 55% classification accuracy on the test set; our best model achieves about 60% classification accuracy. | print(X_train_feats.shape)
from classifiers.neural_net import TwoLayerNet
input_dim = X_train_feats.shape[1]
hidden_dim = 500
num_classes = 10
learning_rates = [3e-1, 9e-1, 1]
regularization_strengths = [3e-3, 4e-3, 5e-3, 6e-3, 7e-3, 8e-3, 9e-3, 1e-2]
results = {}
best_model = None
best_val = -1
for lr in learning_rates:
for reg in regularization_strengths:
model = TwoLayerNet(input_dim, hidden_dim, num_classes, std=1e-1)
stats = model.train(X_train_feats, y_train, X_val_feats, y_val,
learning_rate=lr, learning_rate_decay=0.95,
reg=reg, num_iters=5000, batch_size=200, verbose=True)
train_acc = (model.predict(X_train_feats) == y_train).mean()
val_acc = (model.predict(X_val_feats) == y_val).mean()
print('lr: %e, reg: %e, train_acc: %f, val_acc: %f' % (lr, reg, train_acc, val_acc))
results[(lr, reg)] = (train_acc, val_acc)
if val_acc > best_val:
best_val = val_acc
best_model = model
print
print('best val_acc: %f' % (best_val))
old_lr = -1
for lr, reg in sorted(results):
if old_lr != lr:
old_lr = lr
print
train_acc, val_acc = results[(lr, reg)]
print('lr: %e, reg: %e, train_acc: %f, val_acc: %f' % (lr, reg, train_acc, val_acc))
old_lr = -1
for lr, reg in sorted(results):
if old_lr != lr:
old_lr = lr
print
train_acc, val_acc = results[(lr, reg)]
print('lr: %e, reg: %e, train_acc: %f, val_acc: %f' % (lr, reg, train_acc, val_acc))
# get more than 55% accuracy
test_acc = (best_model.predict(X_test_feats) == y_test).mean()
print('Test accuracy: ', test_acc) | test/features.ipynb | zklgame/CatEyeNets | mit |
Note how tuples are returned. What if one iterable is longer than the other? | x = [1,2,3]
y = [4,5,6,7,8]
# Zip the lists together
zip(x,y) | Zip.ipynb | jserenson/Python_Bootcamp | gpl-3.0 |
Note how the zip is defined by the shortest iterable length. Its generally advised not to zip unequal length iterables unless your very sure you only need partial tuple pairings.
What happens if we try to zip together dictionaries? | d1 = {'a':1,'b':2}
d2 = {'c':4,'d':5}
zip(d1,d2) | Zip.ipynb | jserenson/Python_Bootcamp | gpl-3.0 |
The shop-talk around "ø up" and "ø down" involves scaling all linear dimensions of a shape, whereby volume actually increases or decreases by a factor of ø to the 3rd power. When you think "ø to the 3rd" sometimes imagine a tetrahedron of edges ø vis-a-vis a regular tetrahedron of edges 1 (D). Remember in Synergetics we may use this alternative model of 3rd powering, where our unit-tetrahedron comes from in the first place. | Blue = ø_down
Red = rt2(ø ** 2+1)
Orange = ø/Red
for item in Blue, Orange, Red:
print(item) | CuboidalE3.ipynb | 4dsolutions/Python5 | mit |
For the purposes of Synergetics, our canonical bridge to the Platonics involves making the unit edge of the tetrahedron serve as our D, the Diameter of a unit-radius sphere (D = 2R). We often call this edge length 2, using R as our unit.
The Icosahedron with edges D, for example, is our volume of ~18.51..., which Jitterbugs to become the Cuboctahedron (VE) of volume 20. The octahedron of edges D has volume 4, the cube of face diagonals D has edges 3, and the unit of volume, the regular tetrahedron of edges D, is of course volume 1.
Links to Volumes Table:
* on Codepen
* [in Wikipedia](https://en.wikipedia.org/wiki/Synergetics_(Fuller)
* at Synergetics on the Web
The dual of said Icosahedron, its edges made to intersect said Icosa's at 90 degrees, gives the superstructure of our SuperRT, the one fragmenting into 120 E3 modules, as depicted in Figure One.
What is the volume of the E3? In tetravolumes, we take the SuperRT volume of 15√2 (equivalently vol(CO) * S3)... | RT3_vol = 15 * rt2(2)
print(RT3_vol) | CuboidalE3.ipynb | 4dsolutions/Python5 | mit |
... and simply divide by 120. | E_vol = (RT3_vol * ø_down ** 3)/120 # a little more than 1/24, volume of T module
print(E_vol) | CuboidalE3.ipynb | 4dsolutions/Python5 | mit |
Another expression (in Python) for the E's volume is (rt2(2)/8) * (φ ** -3).
For exercise, lets computer these expressions for E's and SuperRT's volume to a hundred places of decimal precision. | from decimal import Decimal, localcontext
with localcontext() as cm:
cm.prec = 300 # 100 decimal points of precision
Phi = (Decimal(1) + Decimal(5).sqrt())/Decimal(2)
RT3_vol = Decimal('15') * Decimal('2').sqrt()
check_RT = Decimal('20') * (Decimal('9')/Decimal('8')).sqrt()
E_volume = (Decimal('2').sqrt() / Decimal('8')) * Phi ** -3 # simplified expression
check_E = (RT3_vol * Phi ** -3) / Decimal('120') # shrink SuperRT and explode
print("E3*120 {:80.78f}".format(RT3_vol))
print("Check: {:80.78f}".format(check_RT))
print("E vol: {:80.78f}".format(E_volume))
print("Check: {:80.78f}".format(check_E)) | CuboidalE3.ipynb | 4dsolutions/Python5 | mit |
How about we redo those calcs with gmpy2, why not? | import gmpy2
gmpy2.get_context().precision=300
Ø = (1 + gmpy2.root(5, 2))/2
vol_scale_factor = 1.5
rad_scale_factor = gmpy2.root(vol_scale_factor, 3)
S3 = gmpy2.root(9/8, 2)
SuperRT_vol = S3 * 20
Emod_RT_vol = SuperRT_vol * (1/Ø)**3
print("E3*120: {:80.78f}".format( SuperRT_vol))
print("E vol: {:80.78f}".format( Emod_RT_vol/120 )) | CuboidalE3.ipynb | 4dsolutions/Python5 | mit |
Here we need to do a bit of preprocessing and getting the images into a form where we can pass batches to the network. First off, we need to rescale the images to a range of -1 to 1, since the output of our generator is also in that range. We also have a set of test and validation images which could be used if we're trying to identify the numbers in the images. | def scale(x, feature_range=(-1, 1)):
# scale to (0, 1)
x = ((x - x.min())/(255 - x.min()))
# scale to feature_range
min, max = feature_range
x = x * (max - min) + min
return x
class Dataset:
def __init__(self, train, test, val_frac=0.5, shuffle=False, scale_func=None):
split_idx = int(len(test['y'])*(1 - val_frac))
self.test_x, self.valid_x = test['X'][:,:,:,:split_idx], test['X'][:,:,:,split_idx:]
self.test_y, self.valid_y = test['y'][:split_idx], test['y'][split_idx:]
self.train_x, self.train_y = train['X'], train['y']
self.train_x = np.rollaxis(self.train_x, 3)
self.valid_x = np.rollaxis(self.valid_x, 3)
self.test_x = np.rollaxis(self.test_x, 3)
if scale_func is None:
self.scaler = scale
else:
self.scaler = scale_func
self.shuffle = shuffle
def batches(self, batch_size):
if self.shuffle:
idx = np.arange(len(self.train_x))
np.random.shuffle(idx)
self.train_x = self.train_x[idx]
self.train_y = self.train_y[idx]
n_batches = len(self.train_y)//batch_size
for ii in range(0, len(self.train_y), batch_size):
x = self.train_x[ii:ii+batch_size]
y = self.train_y[ii:ii+batch_size]
yield self.scaler(x), y | dcgan-svhn/DCGAN.ipynb | ktmud/deep-learning | mit |
Gradient Descent
Now we will write a function that performs a gradient descent. The basic premise is simple. Given a starting point we update the current weights by moving in the negative gradient direction. Recall that the gradient is the direction of increase and therefore the negative gradient is the direction of decrease and we're trying to minimize a cost function.
The amount by which we move in the negative gradient direction is called the 'step size'. We stop when we are 'sufficiently close' to the optimum. We define this by requiring that the magnitude (length) of the gradient vector to be smaller than a fixed 'tolerance'.
With this in mind, complete the following gradient descent function below using your derivative function above. For each step in the gradient descent we update the weight for each feature befofe computing our stopping criteria | from math import sqrt # recall that the magnitude/length of a vector [g[0], g[1], g[2]] is sqrt(g[0]^2 + g[1]^2 + g[2]^2)
def regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance):
converged = False
weights = np.array(initial_weights) # make sure it's a numpy array
while not converged:
# compute the predictions based on feature_matrix and weights using your predict_output() function
predictions = predict_output(feature_matrix, weights)
# compute the errors as predictions - output
errors = predictions - output
gradient_sum_squares = 0 # initialize the gradient sum of squares
# while we haven't reached the tolerance yet, update each feature's weight
for i in range(len(weights)): # loop over each weight
# Recall that feature_matrix[:, i] is the feature column associated with weights[i]
# compute the derivative for weight[i]:
derivative = feature_derivative(errors, feature_matrix[:, i])
# add the squared value of the derivative to the gradient sum of squares (for assessing convergence)
gradient_sum_squares = gradient_sum_squares + derivative * derivative
# subtract the step size times the derivative from the current weight
weights[i] = weights[i] - derivative * step_size
# compute the square-root of the gradient sum of squares to get the gradient matnigude:
gradient_magnitude = sqrt(gradient_sum_squares)
if gradient_magnitude < tolerance:
converged = True
return(weights) | Linear_Regression_2_multiple_regression_assignment_2.ipynb | Benedicto/ML-Learning | gpl-3.0 |
Now compute your predictions using test_simple_feature_matrix and your weights from above. | predictions = predict_output(test_simple_feature_matrix, weights) | Linear_Regression_2_multiple_regression_assignment_2.ipynb | Benedicto/ML-Learning | gpl-3.0 |
Now that you have the predictions on test data, compute the RSS on the test data set. Save this value for comparison later. Recall that RSS is the sum of the squared errors (difference between prediction and output). | errors = predictions - test_output
RSS = np.dot(errors, errors)
print RSS | Linear_Regression_2_multiple_regression_assignment_2.ipynb | Benedicto/ML-Learning | gpl-3.0 |
Use the above parameters to estimate the model weights. Record these values for your quiz. | weights2 = regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance) | Linear_Regression_2_multiple_regression_assignment_2.ipynb | Benedicto/ML-Learning | gpl-3.0 |
Use your newly estimated weights and the predict_output function to compute the predictions on the TEST data. Don't forget to create a numpy array for these features from the test set first! | (test_feature_matrix, test_output) = get_numpy_data(test_data, model_features, my_output)
predictions_test = predict_output(test_feature_matrix, weights2) | Linear_Regression_2_multiple_regression_assignment_2.ipynb | Benedicto/ML-Learning | gpl-3.0 |
Quiz Question: What is the predicted price for the 1st house in the TEST data set for model 2 (round to nearest dollar)? | predictions_test[0] | Linear_Regression_2_multiple_regression_assignment_2.ipynb | Benedicto/ML-Learning | gpl-3.0 |
Quiz Question: Which estimate was closer to the true price for the 1st house on the Test data set, model 1 or model 2?
Now use your predictions and the output to compute the RSS for model 2 on TEST data. | errors2 = predictions_test - test_output
RSS2 = np.dot(errors2, errors2)
print RSS2 | Linear_Regression_2_multiple_regression_assignment_2.ipynb | Benedicto/ML-Learning | gpl-3.0 |
Quiz Question: Which model (1 or 2) has lowest RSS on all of the TEST data? | print RSS > RSS2 | Linear_Regression_2_multiple_regression_assignment_2.ipynb | Benedicto/ML-Learning | gpl-3.0 |
Now we call DBSCAN function from sklearn, giving as input the list of g-vectors. The parameters eps and min_samples are be system/simulation dependent. As a rough rule-of-thumb, reasonable results are obtained by setting eps in the range 0.2-0.6. A pragmatic choice is to tune eps/min sample so as to obtain ~ 10 clusters with a intra-centroid (IC) eRMSD distance below 0.9. | import barnaba.cluster as cc
# calculate clusters. Call the function dbscan and return list of labels and center indeces
new_labels, center_idx = cc.dbscan(gvecs,list(qq),eps=0.45,min_samples=70)
# write to pickle for later
pickle.dump([new_labels,center_idx],open("cluster.p", "w"))
| manuscript_figures/04_figure.ipynb | srnas/barnaba | gpl-3.0 |
One possible way to visualize the cluster is to perform a principal component analysis and make a scatter plot. | # Do plots. Import matplotlib and seaborn
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("white")
import matplotlib as mpl
from matplotlib.collections import PatchCollection
import matplotlib.patches as mpatches
# calculate PCA
v,w = cc.pca(gvecs,nevecs=3)
# Define figure and set aspect
fig, ax = plt.subplots(figsize=(6.3,4.8))
ax.set_aspect(1)
# calculate explained variance for the first two components
plt.xlabel(r'PC1 (%2.0f%s)' % (v[0]*100,"%"),fontsize=12)
plt.ylabel(r'PC2 (%2.0f%s)' % (v[1]*100-v[0]*100,"%"),fontsize=12)
print("# Cumulative explained variance of component: 1=%5.1f 2:=%5.1f 3=%5.1f" % (v[0]*100,v[1]*100,v[2]*100))
# define colors fxor clusters. Noise is gray point
cp = sns.color_palette("hls",n_colors=len(center_idx),desat=0.8)
colors = [cp[j-1] if(j!=0) else (0.77,0.77,0.77) for j in new_labels]
size = [0.12 if(j==0) else 0.0 for j in new_labels]
# scatterplot the noise
plt.scatter(w[:,0],w[:,1],s=size,c=colors,zorder=0)
# make circles in the center of the cluster
patches = []
new_labels = np.array(new_labels)
for i,k in enumerate(center_idx):
plt.text(w[k,0],w[k,1],str(i+1),ha='center',va='center',fontsize=12)
rr = np.sqrt(1.*len(np.where(new_labels==i+1)[0])/len(new_labels))
circle = mpatches.Circle((w[k,0],w[k,1]), rr, ec='k')
patches.append(circle)
p = PatchCollection(patches, cmap=mpl.cm.tab10, alpha=0.6)
p.set_array(np.arange(len(center_idx))+1)
ax.add_collection(p)
# set nice limits
ax.xaxis.label.set_size(6)
ax.yaxis.label.set_size(6)
ax.set_xlim([-2.5,3.1])
ax.set_ylim([-2.,2.3])
ax.set_xticks([-2,-1,0,1,2,3])
ax.set_yticks([-2,-1,0,1,2])
#plt.savefig("clusters.png",dpi=600)
#plt.close()
plt.show() | manuscript_figures/04_figure.ipynb | srnas/barnaba | gpl-3.0 |
As a last step, we analyze all the cluster individually. We save centroids to a PDB and cluster members to an xtc trajectory file. For each cluster, we calculate the ermsd and rmsd between centroid and cluster memebers. | import mdtraj as md
import barnaba as bb
print("# Write centroids to PDB files and cluster members to .xtc")
top = "topology.pdb"
traj = "trajectory.dcd"
t = md.load(traj, top=top)
dd1 = []
dd2 = []
ll = []
for i,k in enumerate(center_idx):
t[qq[k]].save_pdb("cluster_%03d.test.pdb" % (i))
idxs = [ii for ii,kk in enumerate(new_labels) if(kk==i+1)]
t[qq[idxs]].save_xtc("cluster_%03d.traj.xtc" % (i))
ll.append(100.*len(idxs)/(n))
ermsd_t = bb.ermsd("cluster_%03d.test.pdb" % (i),"cluster_%03d.traj.xtc" % (i),topology=top)
rmsd_t = bb.rmsd("cluster_%03d.test.pdb" % (i),"cluster_%03d.traj.xtc" % (i),topology=top)
dd1.append(ermsd_t)
dd2.append(rmsd_t)
| manuscript_figures/04_figure.ipynb | srnas/barnaba | gpl-3.0 |
And now we box-plot the data. |
# define figure
f, (ax1, ax2) = plt.subplots(2, 1, sharex=True,figsize=(6.2,6.3))
# do the boxplot
ax1 = sns.boxplot(data=dd1,color='0.5',ax=ax1,fliersize=2.5)
ax2 = sns.boxplot(data=dd2,color='0.5',ax=ax2,fliersize=2.5)
# write percentages
for j in range(9):
ax1.text(j,1.5,"%4.0f%s" % (ll[j],"%"),ha="center",va="center",rotation=90,fontsize=12)
# set limits and labels
ax1.set_ylim(0,1.4)
ax1.set_ylabel("eRMSD from centroid",fontsize="12")
ax2.set_ylim(0,0.5)
ax2.set_ylabel("RMSD from centroid (nm)",fontsize="12")
ax2.set_xlabel("Cluster number",fontsize="7")
ax2.set_xticklabels(["1","2","3","4","5","6","7","8","9"])
plt.subplots_adjust(right=0.98, top=0.98)
#plt.savefig("cluster_stats.png",dpi=600)
#plt.close()
plt.show()
| manuscript_figures/04_figure.ipynb | srnas/barnaba | gpl-3.0 |
Finally, we produce the dynamic secondary structures. We start from native | import os
native = "2KOC"
cmd1 = "barnaba ANNOTATE --trj %s.pdb --top %s.pdb -o %s" % (native,native,native)
cmd2 = "barnaba SEC_STRUCTURE --ann %s.ANNOTATE.stacking.out %s.ANNOTATE.pairing.out -o %s" % (native,native,native)
os.system(cmd1)
os.system(cmd2)
| manuscript_figures/04_figure.ipynb | srnas/barnaba | gpl-3.0 |
Native
<img src="2KOC.SEC_STRUCTURE_175steps.svg" width=300 height=300>
And we do the same for the first three clusters: | top = "topology.pdb"
for i in range(3):
cmd1 = "barnaba ANNOTATE --trj cluster_00%d.traj.xtc --top %s -o c%d" % (i,top,i)
cmd2 = "barnaba SEC_STRUCTURE \
--ann c%d.ANNOTATE.stacking.out c%d.ANNOTATE.pairing.out -o c%d" % (i,i,i)
os.system(cmd1)
os.system(cmd2)
print cmd1
%ls *.svg
| manuscript_figures/04_figure.ipynb | srnas/barnaba | gpl-3.0 |
LSTM + CTC Training on UW3
Let's start by downloading the dataset. | !test -f uw3-dew.h5 || (curl http://www.tmbdev.net/ocrdata-hdf5/uw3-dew.h5.gz > uw3-dew.h5.gz && gunzip uw3-dew.h5.gz) | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
In HDF5 data files for CLSTM, row t represents the input vector at time step t. For MNIST, we scan through the original image left-to-right over time.
Transcripts are stored in a separate ragged array of integers; each integer represents a class that can be mapped to a Unicode codepoint using the codec array. Class 0 is special and used for skips in the CTC.
Image storage in HDF5 would have to be a rank 3 doubly ragged array, but HDF5 supports only rank 2 arrays. We therefore store image dimensions in a separate array. | index = 5
h5 = h5py.File("uw3-dew.h5","r")
imshow(h5["images"][index].reshape(*h5["images_dims"][index]).T)
print h5["transcripts"][index] | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
All input vectors need to have the same length, so we just take that off the first vector in the dataset. The number of outputs can be taken from the codec. | ninput = int(h5["images_dims"][0][1])
noutput = len(h5["codec"])
print ninput,noutput | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
Let's create a small bidirectional LSTM network. | net = clstm.make_net_init("bidi","ninput=%d:nhidden=50:noutput=%d"%(ninput,noutput))
net.setLearningRate(1e-4,0.9)
print clstm.network_info(net)
index = 22
xs = array(h5["images"][index].reshape(-1,48,1),'f')
transcript = h5["transcripts"][index]
imshow(xs.reshape(-1,48).T,cmap=cm.gray) | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
Forward propagation is quite simple: we take the input data and put it into the input sequence of the network, call the forward method, and take the result out of the output sequence.
Note that all sequences (including xs) in clstm are of rank 3, with indexes giving the time step, the feature dimension, and the batch index, in order.
The output from the network is a vector of posterior probabilities at each time step. | net.inputs.aset(xs)
net.forward()
pred = net.outputs.array()
imshow(pred.reshape(-1,noutput).T, interpolation='none') | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
Target arrays are similar to the output array but may have a different number of timesteps. They are aligned with the output using CTC. | def mktarget(transcript,noutput):
N = len(transcript)
target = zeros((2*N+1,noutput),'f')
assert 0 not in transcript
target[0,0] = 1
for i,c in enumerate(transcript):
target[2*i+1,c] = 1
target[2*i+2,0] = 1
return target
target = mktarget(transcript,noutput)
imshow(target.T) | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
The CTC alignment now combines the network output with the ground truth. | seq = clstm.Sequence()
seq.aset(target.reshape(-1,noutput,1))
aligned = clstm.Sequence()
clstm.seq_ctc_align(aligned,net.outputs,seq)
aligned = aligned.array()
imshow(aligned.reshape(-1,noutput).T, interpolation='none') | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
If we repeat these steps over and over again, we eventually end up with a trained network. | for i in range(10000):
index = int(rand()*len(h5["images"]))
xs = array(h5["images"][index].reshape(-1,ninput,1),'f')
transcript = h5["transcripts"][index]
net.inputs.aset(xs)
net.forward()
pred = net.outputs.array()
target = mktarget(transcript,noutput)
seq = clstm.Sequence()
seq.aset(target.reshape(-1,noutput,1))
aligned = clstm.Sequence()
clstm.seq_ctc_align(aligned,net.outputs,seq)
aligned = aligned.array()
deltas = aligned - net.outputs.array()
net.d_outputs.aset(deltas)
net.backward()
net.update()
figsize(15,3)
imshow(xs.reshape(-1,ninput).T)
def log10max(a,eps=1e-3):
return log10(maximum(a,eps))
figsize(10,10)
subplot(211); imshow(xs.reshape(-1,ninput)[:200].T)
subplot(212); imshow(pred.reshape(-1,noutput)[:200].T) | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
Let's write a simple decoder. | classes = argmax(pred,axis=1)[:,0]
print classes[:100] | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
When we turn this back into a string using a really simple decoder, it doesn't come out too well, but we haven't trained that long anyway. In addition, this decoder is actually very simple | codes = classes[(classes!=0) & (roll(classes,1)==0)]
chars = [chr(h5["codec"][c]) for c in codes]
print "".join(chars) | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
Let's wrap this up as a function: | def decode1(pred):
classes = argmax(pred,axis=1)[:,0]
codes = classes[(classes!=0) & (roll(classes,1)==0)]
chars = [chr(h5["codec"][c]) for c in codes]
return "".join(chars)
decode1(pred) | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
Here is another idea for decoding: look for minima in the posterior of the epsilon class and then return characters at those locations: | from scipy.ndimage import filters
def decode2(pred,threshold=.5):
eps = filters.gaussian_filter(pred[:,0,0],2,mode='nearest')
loc = (roll(eps,-1)>eps) & (roll(eps,1)>eps) & (eps<threshold)
classes = argmax(pred,axis=1)[:,0]
codes = classes[loc]
chars = [chr(h5["codec"][c]) for c in codes]
return "".join(chars)
decode2(pred) | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
It's often useful to look at this in the log domain. We see that the classifier still has considerable uncertainty. | imshow(log10max(pred.reshape(-1,noutput)[:200].T)) | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
The aligned output looks much cleaner. | imshow(aligned.reshape(-1,noutput)[:200].T)
imshow(log10max(aligned.reshape(-1,noutput)[:200].T)) | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
We can also decode the aligned outut directly. | print decode1(aligned)
print decode2(aligned,0.9) | misc/lstm-uw3-py.ipynb | MichalBusta/clstm | apache-2.0 |
Model Creation
An EBM model instance is created through | # model creation
ebm_boltz = climlab.EBM(D=0.8, Tf=-2) | docs/source/courseware/Boltzmann_EBM.ipynb | cjcardinale/climlab | mit |
The model is set up by default with a linearized OLR parametrization (A+BT). | # print model states and suprocesses
print(ebm_boltz) | docs/source/courseware/Boltzmann_EBM.ipynb | cjcardinale/climlab | mit |
Create new subprocess
The creation of a subprocess needs some information from the model, especially on which model state the subprocess should be defined on. | # create Boltzmann subprocess
LW_boltz = climlab.radiation.Boltzmann(eps=0.65, tau=0.95,
state=ebm_boltz.state,
**ebm_boltz.param) | docs/source/courseware/Boltzmann_EBM.ipynb | cjcardinale/climlab | mit |
Note that the model's whole state dictionary is given as input to the subprocess. In case only the temperature field ebm_boltz.state['Ts'] would be given, a new state dictionary would be created which holds the surface temperature with the key 'default'. That raises an error as the Boltzmann process refers the temperature with key 'Ts'.
Now the new OLR subprocess has to be merged into the model. Therefore, the AplusBT subprocess has to be removed first. | # remove the old longwave subprocess
ebm_boltz.remove_subprocess('LW')
# add the new longwave subprocess
ebm_boltz.add_subprocess('LW',LW_boltz) | docs/source/courseware/Boltzmann_EBM.ipynb | cjcardinale/climlab | mit |
Note that the new OLR subprocess has to have the same key 'LW' as the old one, as the model refers to this key for radiation balance computation.
That is why the old process has to be removed before the new one is added. | print(ebm_boltz) | docs/source/courseware/Boltzmann_EBM.ipynb | cjcardinale/climlab | mit |
Model integration & Plotting
To visualize the model state at beginning of integration we first integrate the model only for one timestep: | # integrate model for a single timestep
ebm_boltz.step_forward() | docs/source/courseware/Boltzmann_EBM.ipynb | cjcardinale/climlab | mit |
The following code plots the current surface temperature, albedo and energy budget: | # creating plot figure
fig = plt.figure(figsize=(15,10))
# Temperature plot
ax1 = fig.add_subplot(221)
ax1.plot(ebm_boltz.lat,ebm_boltz.Ts)
ax1.set_xticks([-90,-60,-30,0,30,60,90])
ax1.set_xlim([-90,90])
ax1.set_title('Surface Temperature', fontsize=14)
ax1.set_ylabel('(degC)', fontsize=12)
ax1.grid()
# Albedo plot
ax2 = fig.add_subplot(223, sharex = ax1)
ax2.plot(ebm_boltz.lat,ebm_boltz.albedo)
ax2.set_title('Albedo', fontsize=14)
ax2.set_xlabel('latitude', fontsize=10)
ax2.set_ylim([0,1])
ax2.grid()
# Net Radiation plot
ax3 = fig.add_subplot(222, sharex = ax1)
ax3.plot(ebm_boltz.lat, ebm_boltz.OLR, label='OLR',
color='cyan')
ax3.plot(ebm_boltz.lat, ebm_boltz.ASR, label='ASR',
color='magenta')
ax3.plot(ebm_boltz.lat, ebm_boltz.ASR-ebm_boltz.OLR,
label='net radiation',
color='red')
ax3.set_title('Net Radiation', fontsize=14)
ax3.set_ylabel('(W/m$^2$)', fontsize=12)
ax3.legend(loc='best')
ax3.grid()
# Energy Balance plot
net_rad = np.squeeze(ebm_boltz.net_radiation)
transport = ebm_boltz.heat_transport_convergence
ax4 = fig.add_subplot(224, sharex = ax1)
ax4.plot(ebm_boltz.lat, net_rad, label='net radiation',
color='red')
ax4.plot(ebm_boltz.lat, transport, label='diffusion transport',
color='blue')
ax4.plot(ebm_boltz.lat, net_rad+np.squeeze(transport), label='balance',
color='black')
ax4.set_title('Energy', fontsize=14)
ax4.set_xlabel('latitude', fontsize=10)
ax4.set_ylabel('(W/m$^2$)', fontsize=12)
ax4.legend(loc='best')
ax4.grid()
| docs/source/courseware/Boltzmann_EBM.ipynb | cjcardinale/climlab | mit |
The two right sided plots show that the model is not in equilibrium. The net radiation reveals that the model currently gains heat and therefore warms up at the poles and loses heat at the equator. From the Energy plot we can see that latitudinal energy balance is not met.
Now we integrate the model as long there are no more changes in the surface temperature and the model reached equilibrium: | # integrate model until solution converges
ebm_boltz.integrate_converge() | docs/source/courseware/Boltzmann_EBM.ipynb | cjcardinale/climlab | mit |
We run the same code as above to plot the results: | # creating plot figure
fig = plt.figure(figsize=(15,10))
# Temperature plot
ax1 = fig.add_subplot(221)
ax1.plot(ebm_boltz.lat,ebm_boltz.Ts)
ax1.set_xticks([-90,-60,-30,0,30,60,90])
ax1.set_xlim([-90,90])
ax1.set_title('Surface Temperature', fontsize=14)
ax1.set_ylabel('(degC)', fontsize=12)
ax1.grid()
# Albedo plot
ax2 = fig.add_subplot(223, sharex = ax1)
ax2.plot(ebm_boltz.lat,ebm_boltz.albedo)
ax2.set_title('Albedo', fontsize=14)
ax2.set_xlabel('latitude', fontsize=10)
ax2.set_ylim([0,1])
ax2.grid()
# Net Radiation plot
ax3 = fig.add_subplot(222, sharex = ax1)
ax3.plot(ebm_boltz.lat, ebm_boltz.OLR, label='OLR',
color='cyan')
ax3.plot(ebm_boltz.lat, ebm_boltz.ASR, label='ASR',
color='magenta')
ax3.plot(ebm_boltz.lat, ebm_boltz.ASR-ebm_boltz.OLR,
label='net radiation',
color='red')
ax3.set_title('Net Radiation', fontsize=14)
ax3.set_ylabel('(W/m$^2$)', fontsize=12)
ax3.legend(loc='best')
ax3.grid()
# Energy Balance plot
net_rad = np.squeeze(ebm_boltz.net_radiation)
transport = ebm_boltz.heat_transport_convergence
ax4 = fig.add_subplot(224, sharex = ax1)
ax4.plot(ebm_boltz.lat, net_rad, label='net radiation',
color='red')
ax4.plot(ebm_boltz.lat, transport, label='diffusion transport',
color='blue')
ax4.plot(ebm_boltz.lat, net_rad+np.squeeze(transport), label='balance',
color='black')
ax4.set_title('Energy', fontsize=14)
ax4.set_xlabel('latitude', fontsize=10)
ax4.set_ylabel('(W/m$^2$)', fontsize=12)
ax4.legend(loc='best')
ax4.grid()
plt.show() | docs/source/courseware/Boltzmann_EBM.ipynb | cjcardinale/climlab | mit |
Now we can see that the latitudinal energy balance is statisfied. Each latitude gains as much heat (net radiation) as is transported out of it (diffusion transport). There is a net radiation surplus in the equator region, so more shortwave radiation is absorbed there than is emitted through longwave radiation. At the poles there is a net radiation deficit. That imbalance is compensated by the diffusive energy transport term.
Global mean temperature
We use climlab to compute the global mean temperature and print the ice edge latitude: | print('The global mean temperature is %.2f deg C.' %climlab.global_mean(ebm_boltz.Ts))
print('The modeled ice edge is at %.2f deg latitude.' %np.max(ebm_boltz.icelat)) | docs/source/courseware/Boltzmann_EBM.ipynb | cjcardinale/climlab | mit |
Import Libs and configure Plotly | import IPython
import plotly
import plotly.offline as py
import plotly.graph_objs as go
import math
import json
import numpy as np
import pandas as pd
import re
from scipy import spatial
from scipy.spatial import distance
from sklearn.cluster import KMeans
from google.colab import drive
from google.colab import auth
from sklearn import preprocessing
from sklearn.preprocessing import scale
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.preprocessing import MinMaxScaler
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from IPython.display import display
import matplotlib as mpl
py.init_notebook_mode(connected=False)
%matplotlib inline
py.init_notebook_mode(connected=False)
| pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb | google/data-pills | apache-2.0 |
Mount Drive and read the Customer Match Insights CSVs | if (isUsingGDrive):
drive.mount('/gdrive')
df_1 = pd.read_csv(audience1_file_location,usecols=['Dimension','Audience','List distribution'])
df_1['List distribution'] = round(df_1['List distribution']*audience1_size)
df_2 = pd.read_csv(audience2_file_location,usecols=['Dimension','Audience','List distribution'])
df_2['List distribution'] = round(df_2['List distribution']*audience2_size)
if ((audience3_name != "") & (audience3_file_location != "") & (audience3_size > 0)):
audience3_enabled = True
df_3 = pd.read_csv(audience3_file_location,usecols=['Dimension','Audience','List distribution'])
df_3['List distribution'] = round(df_3['List distribution']*audience3_size)
else:
audience3_enabled = False | pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb | google/data-pills | apache-2.0 |
Define TF-IDF Function | def scalarToSigmod(scalar):#0-1 input
x = (scalar-.5)*8
return 1 / (1 + math.exp(-x))
def scalarToTanh(scalar):
x = (scalar-.5)*6
return (math.tanh(x)+1)/2
def calc_tfidf(df, label_col_name, transformation='tanh'):
transformer = TfidfTransformer(smooth_idf=True, norm='l1', use_idf=False)
X = df.copy()
y = X[label_col_name]
X = X.drop([label_col_name], axis=1)
tfidf = transformer.fit_transform(X)
#create pd with results
results = pd.DataFrame.from_records(tfidf.toarray() , columns=list(X.columns.values))
#transpose
results_transposed = results.T.reset_index()
results_transposed.columns = ["COMPARED_USERLIST_FULL_NAME"] + list(y)
results_transposed
#scale to 0-1
scaler = MinMaxScaler()
results_transposed[list(y)] = scaler.fit_transform(results_transposed[list(y)])
for col in list(y):
if transformation == 'sig':
results_transposed[col] = results_transposed.apply(lambda x: scalarToSigmod(x[col]), axis=1)
elif transformation == 'tanh':
results_transposed[col] = results_transposed.apply(lambda x: scalarToTanh(x[col]), axis=1)
return results_transposed | pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb | google/data-pills | apache-2.0 |
Define GA API reporting functions | def process_report(report):
data=[]
columnHeader = report.get('columnHeader', {})
dimensionHeaders = columnHeader.get('dimensions', [])
metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])
metricHeaders = [header['name'] for header in metricHeaders]
df_headers = dimensionHeaders + metricHeaders
for row in report['data']['rows']:
d = row['dimensions']
m = row['metrics'][0]['values']
data.append(d+m)
df = pd.DataFrame(data, columns=df_headers)
pivot = pd.pivot_table(df,
index=[df.columns[0]],
columns=['ga:segment'],
aggfunc='sum').T
df = pd.DataFrame(pivot.fillna(0).to_records())
return df[df.columns[1:]] | pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb | google/data-pills | apache-2.0 |
Run TF-IDF | df_1['Segmento'] = audience1_name
df_2['Segmento'] = audience2_name
if (audience3_enabled):
df_3['Segmento'] = audience3_name
df_list = [df_1,df_2,df_3]
else:
df_list = [df_1,df_2]
df = pd.concat(df_list)
df = df.loc[df['Dimension'] != 'City']
df = df.loc[df['Dimension'] != 'Country']
df['Audience'] = df['Dimension'] + ' | ' + df['Audience']
df.drop(['Dimension'],axis=1,inplace=True)
df_pivot = pd.pivot_table(df, index=['Segmento'], columns=['Audience'],aggfunc='sum').fillna(0)
df_pivot.columns = df_pivot.columns.droplevel(level=0)
df_pivot.reset_index(level=[0],inplace=True)
cmi_df = calc_tfidf(df_pivot,'Segmento')
cmi_df.head() | pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb | google/data-pills | apache-2.0 |
Plot the results | def plot_3d(cmi_df):
configure_plotly_browser_state()
y = list(cmi_df.drop(['COMPARED_USERLIST_FULL_NAME'],axis=1).columns)
plot3d(cmi_df,'COMPARED_USERLIST_FULL_NAME',list(y))
def print_ordered_list(cmi_df):
vecs = [[1,0,0], [0,1,0], [0,0,1]]
segments = list(cmi_df.columns[1:])
cmi_df['vector'] = cmi_df[[*segments]].values.tolist()
for i in range(len(segments)):
data = []
col = 'distance_{}'.format(segments[i])
for row in cmi_df.iterrows():
euc = distance.euclidean(row[1]['vector'], vecs[i])
data.append(euc)
cmi_df[col] = data
for col in cmi_df.columns[-3:]:
display(cmi_df[['COMPARED_USERLIST_FULL_NAME', col]].sort_values(by=col, ascending=True))
plot_3d(cmi_df)
print_ordered_list(cmi_df) | pills/Google Ads/[DATA_PILL]_[Google_Ads]_Customer_Market_Intelligence_(CMI).ipynb | google/data-pills | apache-2.0 |
comment data 가져오기 및 전처리 | episode_comment = pd.read_csv("data/webnovel/episode_comments.csv", index_col=0, encoding="cp949")
episode_comment["ID"] = episode_comment["object_id"].apply(lambda x: x.split("-")[0])
episode_comment["volume"] = episode_comment["object_id"].apply(lambda x: x.split("-")[1]).astype("int")
episode_comment["writer_nickname"].fillna("", inplace=True)
def make_user_id(i):
if episode_comment["writer_nickname"].loc[i] == "":
return episode_comment["writer_ip"].loc[i] + episode_comment["writer_id"].loc[i]
else:
return episode_comment["writer_nickname"].loc[i] + episode_comment["writer_id"].loc[i]
user_id = [
make_user_id(i)
for i in range(len(episode_comment))
]
episode_comment["user_id"] = user_id
episode_comment.drop(
[
"contents",
"down_count",
"modified_ymdt",
"registered_ymdt",
"ticket",
"up_count",
"writer_ip",
"writer_id",
"writer_nickname",
"writer_profile_type",
"object_id",
],
axis=1,
inplace=True
)
episode_comment.head()
main_comment = pd.read_csv("data/webnovel/main_comments.csv", index_col=0, encoding="cp949")
main_comment["ID"] = main_comment["object_id"].apply(lambda x: x.split("-")[1])
main_comment["volume"] = 0
main_comment["writer_nickname"].fillna("", inplace=True)
def make_user_id(i):
if main_comment["writer_nickname"].loc[i] == "":
return main_comment["writer_ip"].loc[i] + main_comment["writer_id"].loc[i]
else:
return main_comment["writer_nickname"].loc[i] + main_comment["writer_id"].loc[i]
user_id = [
make_user_id(i)
for i in range(len(main_comment))
]
main_comment["user_id"] = user_id
main_comment.drop(
[
"contents",
"down_count",
"modified_ymdt",
"registered_ymdt",
"ticket",
"up_count",
"writer_ip",
"writer_id",
"writer_nickname",
"writer_profile_type",
"object_id",
],
axis=1,
inplace=True
)
main_comment.head() | Recommand System.ipynb | kmsmoo/Webnovel | mit |
user dataframe 만들기 | user_df = pd.concat([episode_comment, main_comment]).groupby(["user_id", "ID"], as_index=False).agg({"volume":np.size})
len(user_df)
df = pd.read_csv("data/webnovel/main_df.csv", encoding="cp949", index_col=0)
df["ID"] = df["ID"].astype("str")
df = user_df.merge(df, on="ID")[["user_id", "genre", "volume"]].drop_duplicates()
len(df["user_id"].unique())
romance = df[df["genre"] == 101]
no_romance = df[df["genre"] != 101]
len(romance.merge(no_romance, on="user_id")) | Recommand System.ipynb | kmsmoo/Webnovel | mit |
user, book 인덱스 및 처리 | user_size = len(user_df["user_id"].unique())
users = user_df["user_id"].unique()
users_index = {
user:index
for index, user in enumerate(users)
}
book_df = pd.read_csv("data/webnovel/main_df.csv", encoding="cp949", index_col=0)
book_size = len(book_df.ID.unique())
books = book_df.ID.unique()
len(books)
books_index = {
str(book):index
for index, book in enumerate(books)
}
user_df["book_index"] = user_df["ID"].apply(lambda x: books_index[x])
user_df["user_index"] = user_df["user_id"].apply(lambda x: users_index[x]) | Recommand System.ipynb | kmsmoo/Webnovel | mit |
user * book matrix 만들기 | empty_matrix = np.zeros((user_size, book_size))
for index, i in user_df.iterrows():
empty_matrix[i["user_index"], i["book_index"]] = i["volume"]
user_book_matrix = pd.DataFrame(empty_matrix, columns=books)
user_book_matrix.index = users
user_book_matrix | Recommand System.ipynb | kmsmoo/Webnovel | mit |
user * user cosine similarity 매트릭스 만들기
1 권 169464 명 1분 59초
2 권 57555 명 40.6초
3 권 31808 명 22.4초
4 권 20470 명 14.5초
5 권 14393 명 10.2초
6 권 10630 명 7.58초
7 권 8074 명 5.8초
8 권 6306 명 4.54초
9 권 4995 명 3.56초
10 권 4052 명 2.91초 | for i in range(15):
print(i+1, "권 이상 읽은 사람은",len(user_book_matrix[user_book_matrix.sum(axis=1)>i]), "명 입니다.")
from scipy.spatial import distance
def cosine_distance(a, b):
return 1 - distance.cosine(a, b)
def make_score(books):
"""
MAE 스코어 계산
"""
user_books_matrix_two = user_book_matrix[user_book_matrix.sum(axis=1)>books]
empty_matrix = np.zeros((50, len(user_books_matrix_two))) # 샘플 10명
users_two_index = user_books_matrix_two.index
user_books_matrix_two.index = range(len(user_books_matrix_two))
for index_1, i in user_books_matrix_two[:10].iterrows():
for index_2, j in user_books_matrix_two[index_1+1:].iterrows():
empty_matrix[index_1, index_2] = cosine_distance(i, j)
score_list = []
for i in range(10):
ID_index = []
while len(ID_index) < 11:
if empty_matrix[i].argmax() >= 1:
empty_matrix[i, empty_matrix[i].argmax()] = 0
else:
ID_index.append(empty_matrix[i].argmax())
empty_matrix[i, empty_matrix[i].argmax()] = 0
data = user_books_matrix_two.loc[i]
predict = user_books_matrix_two.loc[ID_index].mean()
score = data[data > 0] - predict[data > 0]
score_list.append(np.absolute(score).sum()/len(score))
print(np.array(score_list).mean())
return np.array(score_list).mean()
scores = list(map(make_score, [0,1,2,3,4,5,6,7,8,9]))
user_df[user_df["user_id"] == users_two_index[empty_matrix[0].argmax()]]
user_df[user_df["user_id"] == users_two_index[0]]
user_books_matrix_two | Recommand System.ipynb | kmsmoo/Webnovel | mit |
Set your Processor Variables | # TODO(developer): Fill these variables with your values before running the sample
PROJECT_ID = "YOUR_PROJECT_ID_HERE"
LOCATION = "us" # Format is 'us' or 'eu'
PROCESSOR_ID = "PROCESSOR_ID" # Create processor in Cloud Console
DOCUMENT_PATH = "../resources/general/form.tiff" # Path of target document | general/form_parser.ipynb | GoogleCloudPlatform/documentai-notebooks | apache-2.0 |
The following code calls the synchronous API and parses the form fields and values. | def process_document_sample():
# Instantiates a client
client_options = {"api_endpoint": "{}-documentai.googleapis.com".format(LOCATION)}
client = documentai.DocumentProcessorServiceClient(client_options=client_options)
# The full resource name of the processor, e.g.:
# projects/project-id/locations/location/processor/processor-id
# You must create new processors in the Cloud Console first
name = f"projects/{PROJECT_ID}/locations/{LOCATION}/processors/{PROCESSOR_ID}"
with open(DOCUMENT_PATH, "rb") as image:
image_content = image.read()
# Read the file into memory
document = {"content": image_content, "mime_type": "image/tiff"}
# Configure the process request
request = {"name": name, "raw_document": document}
# Recognizes text entities in the PDF document
result = client.process_document(request=request)
document = result.document
print("Document processing complete.\n\n")
# For a full list of Document object attributes, please reference this page: https://googleapis.dev/python/documentai/latest/_modules/google/cloud/documentai_v1beta3/types/document.html#Document
document_pages = document.pages
keys = []
keysConf = []
values = []
valuesConf = []
# Grab each key/value pair and their corresponding confidence scores.
for page in document_pages:
for form_field in page.form_fields:
fieldName=get_text(form_field.field_name,document)
keys.append(fieldName.replace(':', ''))
nameConfidence = round(form_field.field_name.confidence,4)
keysConf.append(nameConfidence)
fieldValue = get_text(form_field.field_value,document)
values.append(fieldValue.replace(':', ''))
valueConfidence = round(form_field.field_value.confidence,4)
valuesConf.append(valueConfidence)
# Create a Pandas Dataframe to print the values in tabular format.
df = pd.DataFrame({'Key': keys, 'Key Conf': keysConf, 'Value': values, 'Value Conf': valuesConf})
display(df)
return document
def get_text(doc_element: dict, document: dict):
"""
Document AI identifies form fields by their offsets
in document text. This function converts offsets
to text snippets.
"""
response = ""
# If a text segment spans several lines, it will
# be stored in different text segments.
for segment in doc_element.text_anchor.text_segments:
start_index = (
int(segment.start_index)
if segment in doc_element.text_anchor.text_segments
else 0
)
end_index = int(segment.end_index)
response += document.text[start_index:end_index]
return response
doc = process_document_sample() | general/form_parser.ipynb | GoogleCloudPlatform/documentai-notebooks | apache-2.0 |
Draw the bounding boxes
We will now download the pdf above a jpg and use the spatial data to mark our values. | document_image = Image.open(DOCUMENT_PATH)
draw = ImageDraw.Draw(document_image)
for form_field in doc.pages[0].form_fields:
# Draw the bounding box around the form_fields
# First get the co-ords of the field name
vertices = []
for vertex in form_field.field_name.bounding_poly.normalized_vertices:
vertices.append({'x': vertex.x * document_image.size[0], 'y': vertex.y * document_image.size[1]})
draw.polygon([
vertices[0]['x'], vertices[0]['y'],
vertices[1]['x'], vertices[1]['y'],
vertices[2]['x'], vertices[2]['y'],
vertices[3]['x'], vertices[3]['y']], outline='red')
vertices = []
for vertex in form_field.field_value.bounding_poly.normalized_vertices:
vertices.append({'x': vertex.x * document_image.size[0], 'y': vertex.y * document_image.size[1]})
draw.polygon([
vertices[0]['x'], vertices[0]['y'],
vertices[1]['x'], vertices[1]['y'],
vertices[2]['x'], vertices[2]['y'],
vertices[3]['x'], vertices[3]['y']], outline='blue')
document_image | general/form_parser.ipynb | GoogleCloudPlatform/documentai-notebooks | apache-2.0 |
Note que a imagem possui 174 linhas e 314 colunas, totalizando mais de 54 mil pixels. A representação do pixel é pelo tipo
uint8, isto é, valores de 8 bits sem sinal, de 0 a 255. Note também que a impressão de todos os pixels é feita de
forma especial. Se todos os 54 mil pixels tivessem que ser impressos, o resultado da impressão seria proibitivo. Neste caso, quando
a imagem (matriz) for muito grande, o NumPy imprime apenas os pixels dos quatro cantos da imagem.
Visualização de uma imagem
No Adessowiki, a visualização de uma imagem é feita unicamente pela função adshow, que internamente utiliza o pacote PIL já
mencionado. O processo de exibição de uma imagem cria uma representação gráfica desta matriz
em que os valores do pixel é atribuído a um nível de cinza (imagem monocromática) ou a uma cor particular. Quando o pixel da imagem
é uint8, o valor zero é atribuído ao preto e o valor 255 ao branco e gerando um tom de cinza proporcional ao valor do pixel.
Veja abaixo a visualização da imagem cookies.tif já lida no trecho de programa anterior. Note que a função adshow possui
dois parâmetros, a imagem e um string para ser exibido na legenda da visualização da imagem. | plt.imshow(f,cmap='gray') | master/tutorial_img_ds.ipynb | robertoalotufo/ia898 | mit |
O segundo tipo de imagem que o adshow visualiza é a imagem com pixels do tipo booleano. Como ilustração, faremos uma
operação comparando cada pixel da imagem cookies com o valor 128 gerando assim uma nova imagem f_bin onde cada pixel será
True ou False dependendo do resultado da comparação. O adshow mapeia os pixels verdadeiros como branco e os pixels
falsos como preto: | f_bin = f > 128
print('Tipo do pixel:', f_bin.dtype)
plt.imshow(f_bin,cmap='gray')
plt.colorbar()
print(f_bin.min(), f_bin.max())
f_f = f_bin.astype(np.float)
f_i = f_bin.astype(np.int)
print(f_f.min(),f_f.max())
print(f_i.min(),f_i.max())
| master/tutorial_img_ds.ipynb | robertoalotufo/ia898 | mit |
Por fim, além destes dois modos de exibição, o adshow pode também exibir imagens coloridas no formato RGB e tipo de pixel uint8.
No NumPy a imagem RGB é representada como três images armazenadas na dimensão profundidade. Neste caso o array tem 3
dimensões e seu shape tem o formato (3,H,W). | f_cor = mpimg.imread('../data/boat.tif')
print('Dimensões: ', f_cor.shape)
print('Tipo do pixel:', f_cor.dtype)
plt.imshow(f_cor)
f_roi = f_cor[:2,:3,:]
print(f_roi) | master/tutorial_img_ds.ipynb | robertoalotufo/ia898 | mit |
Neste curso, por motivos didáticos, o adshow somente visualiza estes 3 tipos de imagens. Qualquer outro tipo de imagem,
seja de valores maiores que 255, negativos ou complexos, precisam ser explicitamente convertidos para os valores entre 0 e 255
ou True e False.
Maiores informações no uso do adshow podem ser vistas em ia636:adshow.
.. note:: Uma das principais causas de erro em processamento de imagens é não prestar atenção no tipo do pixel ou nas dimensões da
imagem. Recomenda-se verificar esta informações. Uma função que é bastante útil é a ia636:iaimginfo que foi criada para
verificar rapidamente o tipo de pixel, dimensões e os valores mínimo e máximo da imagem. Veja a seguir um exemplo do seu uso
nas três imagens processadas anteriormente:
import ia636
print 'f: ', ia636.iaimginfo(f)
print 'f_bin:', ia636.iaimginfo(f_bin)
print 'f_cor:', ia636.iaimginfo(f_cor)
Visualizando numericamente uma pequena região de interesse da imagem
Para verificar que a imagem lida é composta de valores entre 0 e 255, vamos imprimir numericamente
apenas uma pequena região de 7 linhas e 10 colunas do canto superior esquerdo da imagem. Fazemos isto
com fatiamento: | f= mpimg.imread('../data/gull.pgm')
plt.imshow(f,cmap='gray')
g = f[:7,:10]
print('g=')
print(g) | master/tutorial_img_ds.ipynb | robertoalotufo/ia898 | mit |
Read nino3 SSTA time series, Plot and Save the image
In this noteboo, we will finish the following operations
* read time series data produced bya previous notebook
* have a quick plot
* decorate plots
* save image
1. Load basic libraries | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt # to generate plots | ex04-Read nino3 SSTA series in npz format, plot and save the image.ipynb | royalosyin/Python-Practical-Application-on-Climate-Variability-Studies | mit |
2. Load nino3 SSTA series
Please keep in mind that the nino3 SSTA series lies between 1970 and 1999 <br>
Recall ex2 | npzfile = np.load('data/ssta.nino3.30y.npz')
npzfile.files
ssta_series = npzfile['ssta_series']
ssta_series.shape | ex04-Read nino3 SSTA series in npz format, plot and save the image.ipynb | royalosyin/Python-Practical-Application-on-Climate-Variability-Studies | mit |
3. Have a quick plot | plt.plot(ssta_series) | ex04-Read nino3 SSTA series in npz format, plot and save the image.ipynb | royalosyin/Python-Practical-Application-on-Climate-Variability-Studies | mit |
4. Make it beautiful
4.1 Add Year ticks and grid lines, etc.
More info can be found from https://matplotlib.org/users/pyplot_tutorial.html | fig = plt.figure(figsize=(15, 6))
ax = fig.add_subplot(111)
plt.plot(ssta_series, 'g-', linewidth=2)
plt.xlabel('Years')
plt.ylabel('[$^oC$]')
plt.title('nino3 SSTA 30-year (1970-1999)', fontsize=12)
ax.set_xlim(0,361)
ax.set_ylim(-3.5,3.5)
ax.set_xticklabels(range(1970,2000,1*4))
ax.axhline(0, color='r')
plt.grid(True)
ax.autoscale_view()
plt.savefig('image/ssta_series_30y.png') | ex04-Read nino3 SSTA series in npz format, plot and save the image.ipynb | royalosyin/Python-Practical-Application-on-Climate-Variability-Studies | mit |
4.2 More professional
Just like the image from https://www.esrl.noaa.gov/psd/enso/mei/ | fig = plt.figure(figsize=(15, 6))
ax = fig.add_subplot(111)
xtime = np.linspace(1,360,360)
ssta_series = ssta_series.reshape((360))
ax.plot(xtime, ssta_series, 'black', alpha=1.00, linewidth=2)
ax.fill_between(xtime, 0., ssta_series, ssta_series> 0., color='red', alpha=.75)
ax.fill_between(xtime, 0., ssta_series, ssta_series< 0., color='blue', alpha=.75)
plt.xlabel('Years')
plt.ylabel('[$^oC$]')
plt.title('nino3 SSTA 30-year (1970-1999)', fontsize=12)
ax.set_xlim(0, 361)
ax.set_ylim(-4, 4)
ax.set_xticklabels(range(1970,2000,1*4))
plt.grid(True)
ax.autoscale_view() | ex04-Read nino3 SSTA series in npz format, plot and save the image.ipynb | royalosyin/Python-Practical-Application-on-Climate-Variability-Studies | mit |
Load trajectories | from evo.tools import file_interface
from evo.core import sync | notebooks/metrics_interactive.ipynb | MichaelGrupp/evo | gpl-3.0 |
Load KITTI files with entries of the first three rows of $\mathrm{SE}(3)$ matrices per line (no timestamps): | traj_ref = file_interface.read_kitti_poses_file("../test/data/KITTI_00_gt.txt")
traj_est = file_interface.read_kitti_poses_file("../test/data/KITTI_00_ORB.txt") | notebooks/metrics_interactive.ipynb | MichaelGrupp/evo | gpl-3.0 |
...or load a ROS bagfile with geometry_msgs/PoseStamped, geometry_msgs/TransformStamped, geometry_msgs/PoseWithCovarianceStamped or nav_msgs/Odometry topics: | from rosbags.rosbag1 import Reader as Rosbag1Reader
with Rosbag1Reader("../test/data/ROS_example.bag") as reader:
traj_ref = file_interface.read_bag_trajectory(reader, "groundtruth")
traj_est = file_interface.read_bag_trajectory(reader, "ORB-SLAM")
traj_ref, traj_est = sync.associate_trajectories(traj_ref, traj_est) | notebooks/metrics_interactive.ipynb | MichaelGrupp/evo | gpl-3.0 |
... or load TUM files with 3D position and orientation quaternion per line ($x$ $y$ $z$ $q_x$ $q_y$ $q_z$ $q_w$): | traj_ref = file_interface.read_tum_trajectory_file("../test/data/fr2_desk_groundtruth.txt")
traj_est = file_interface.read_tum_trajectory_file("../test/data/fr2_desk_ORB_kf_mono.txt")
traj_ref, traj_est = sync.associate_trajectories(traj_ref, traj_est)
print(traj_ref)
print(traj_est) | notebooks/metrics_interactive.ipynb | MichaelGrupp/evo | gpl-3.0 |
APE
Algorithm and API explanation: see here
Interactive APE Demo
Run the code below, configure the parameters in the GUI and press the update button.
(uses the trajectories loaded above) | import evo.main_ape as main_ape
import evo.common_ape_rpe as common
count = 0
results = []
def callback_ape(pose_relation, align, correct_scale, plot_mode, show_plot):
global results, count
est_name="APE Test #{}".format(count)
result = main_ape.ape(traj_ref, traj_est, est_name=est_name,
pose_relation=pose_relation, align=align, correct_scale=correct_scale)
count += 1
results.append(result)
if show_plot:
fig = plt.figure()
ax = plot.prepare_axis(fig, plot_mode)
plot.traj(ax, plot_mode, traj_ref, style="--", alpha=0.5)
plot.traj_colormap(
ax, result.trajectories[est_name], result.np_arrays["error_array"], plot_mode,
min_map=result.stats["min"], max_map=result.stats["max"])
_ = ipywidgets.interact_manual(callback_ape, pose_relation=pose_relation_selector, plot_mode=plotmode_selector,
**{c.description: c.value for c in check_boxes_ape}) | notebooks/metrics_interactive.ipynb | MichaelGrupp/evo | gpl-3.0 |
RPE
Algorithm and API explanation: see here
Interactive RPE Demo
Run the code below, configure the parameters in the GUI and press the update button.
(uses the trajectories loaded above, alignment only useful for visualization here) | import evo.main_rpe as main_rpe
count = 0
results = []
def callback_rpe(pose_relation, delta, delta_unit, all_pairs, align, correct_scale, plot_mode, show_plot):
global results, count
est_name="RPE Test #{}".format(count)
result = main_rpe.rpe(traj_ref, traj_est, est_name=est_name,
pose_relation=pose_relation, delta=delta, delta_unit=delta_unit,
all_pairs=all_pairs, align=align, correct_scale=correct_scale,
support_loop=True)
count += 1
results.append(result)
if show_plot:
fig = plt.figure()
ax = plot.prepare_axis(fig, plot_mode)
plot.traj(ax, plot_mode, traj_ref, style="--", alpha=0.5)
plot.traj_colormap(
ax, result.trajectories[est_name], result.np_arrays["error_array"], plot_mode,
min_map=result.stats["min"], max_map=result.stats["max"])
_ = ipywidgets.interact_manual(callback_rpe, pose_relation=pose_relation_selector, plot_mode=plotmode_selector,
delta=delta_input, delta_unit=delta_unit_selector,
**{c.description: c.value for c in check_boxes_rpe}) | notebooks/metrics_interactive.ipynb | MichaelGrupp/evo | gpl-3.0 |
Do stuff with the result objects: | import pandas as pd
from evo.tools import pandas_bridge
df = pd.DataFrame()
for result in results:
df = pd.concat((df, pandas_bridge.result_to_df(result)), axis="columns")
df
df.loc["stats"] | notebooks/metrics_interactive.ipynb | MichaelGrupp/evo | gpl-3.0 |
Aiyagari Economy
The economy can be represented by the following system of equations which we aim to solve numerically:
$$
\begin{align}
\rho v_1(a) &= \max_c \ u(c) + v_1'(a)(wz_1 + ra - c) + \lambda_1(v_2(a) - v_1(a))\
\rho v_2(a) &= \max_c \ u(c) + v_2'(a)(wz_2 + ra - c) + \lambda_2(v_1(a) - v_2(a))\
0 &= - \frac{d}{da}[s_1(a)g_1(a)] - \lambda_1 g_1(a) + \lambda_2 g_2(a)\
0 &= - \frac{d}{da}[s_2(a)g_2(a)] - \lambda_2 g_2(a) + \lambda_1 g_1(a)\
1 &= \int_{\underline{a}}^\infty g_1(a)da + \int_{\underline{a}}^\infty g_2(a)da\
K &= \int_{\underline{a}}^\infty a g_1(a)da + \int_{\underline{a}}^\infty a g_2(a)da\
r &= \alpha K^{\alpha-1} - \delta, \quad w=(1-\alpha)K^\alpha
\end{align}
$$
where $z_1$ < $z_2$ and $s_j(a)=wz_j + ra -c_j(a)$ and $c_j(a) = (u')^{-1}(v_j(a))$ are optimal savings and consumption. Finally, there is a state constraint $a\geq \underline{a}$. The first order condition $u'(c_j(\underline{a}))=v'_j(\underline{a})$ still holds at the borrowing constraint. However, in order to respect the constraint we need $s_j(\underline{a}) = z_j + ra - c_j(\underline{a}) \geq 0$. Combining this with the FOC, the state constraint motivates a boundary condition
$$
\begin{align} v_j'(\underline{a}) \geq u'(z_j + r \underline{a}), \quad j=1,2 \end{align}
$$
We use a finite difference method, an in particular an "implicit upwind scheme." The details are explained in the paper's online Appendix. We here provide a brief summary. We approximate the functions $(v_1,v_2,g_1,g_2)$ at $I$ discrete points in the space dimension, $a_i,i=1,...,I$. We use equispaced grids, denote by $\Delta a$ the distance between grid points, and use the short-hand notation $v_{i,j} \equiv v_j(a_i)$ and so on. The derivative $v_{i,j}'=v_j'(a_i)$ is approximated with either a forward or a backward difference approximation
$$
\begin{align}
v_j'(a_i) \approx \frac{v_{i+1,j} - v_{i,j}}{\Delta a} \equiv v_{i,j,F}' \
v_j'(a_i) \approx \frac{v_{i-1,j} - v_{i,j}}{\Delta a} \equiv v_{i,j,B}'
\end{align}
$$
An upwind scheme means that we approximate the derivative $v_j'(a_i)$ with a forward difference approximation whenever the drift of the state variable is positive and the backward difference approximation whenever it is negative. An implicit scheme is a particular way of iterating on the value function.
In a nutshell, the discretized HJB equation can be written as
$$\rho v = u + \mathbf{A} v$$
where $\mathbf{A}$ is $N \times N$ transition matrix with $N = 2 \times I$ and where $I$ is the number of wealth grid points. The matrix $\mathbf{A}$ depends on $v$, i.e. this is a nonlinear problem and we therefore need to iterate (this is where the implicit scheme comes in). The matrix $\mathbf{A}$ has the interpretation of a Poisson transition matrix (or "intensity matrix") on the discretized state space $(a_i,z_j)$.
Similarly, one can show that the discretized Kolmogorov Forward equation is
$$0 = \mathbf{A}^T g$$
which is an eigenvalue problem. That is, the discretized stationary distribution $g$ is the eigenvector corresponding to a zero eigenvalue of the transpose of the Poisson transition matrix $\mathbf{A}$. The transpose comes from the fact that the differential operator in the KF equation is the "adjoint" of the operator in the HJB equation. And an "adjoint" is the infinite-dimensional analogue of matrix transpose.
The matrix $\mathbf{A}$ is found from the discretized HJB equation. Skipping a number of steps it can be written as
$$
\begin{align}
&\frac{v^{n+1}{i,j} - v^{n}{i,j}}{\Delta} + \rho v_{i,j}^{n+1} = u(c_{i,j}^n) + v_{i-1,j}^{n+1}x_{i,j} + v^{n+1}{i,j} y{i,j} + v_{i+1,j}^{n+1} z_{i,j} + v_{i,-j}^{n+1}\lambda_j \quad \mbox{where}\
&x_{i,j} = -\frac{(s^n_{i,j,B})^-}{\Delta a},\
&y_{i,j} = - \frac{(s^n_{i,j,F})^+}{\Delta a} + \frac{ (s^n_{i,j,B})^-}{\Delta a} - \lambda_j,\
&z_{i,j} = \frac{(s^n_{i,j,F})^+}{\Delta a}
\end{align}
$$
where $s^n_{i,j,F}$ and $s^n_{i,j,B}$ are the discretized optimal household savings at grid points $(a_i,z_j)$ using forward and backward approximations, and where for any number $x$, the notation $x^+$ means "the positive part of $x$", i.e. $x^+ = \max{x,0}$ and analogously $x^{-} = \min{x,0}$. This part is what makes it an upwind scheme.
This is a system of $2 \times I$ linear equations which can be written in matrix notation as:
\begin{equation}\frac{1}{\Delta}(v^{n+1} - v^n) + \rho v^{n+1} = u^n + \mathbf{A}^n v^{n+1} \end{equation}
where
$$\mathbf{A}^n = \left[\begin{matrix}y_{1,1} & z_{1,1} & 0 & \cdots & 0 & \lambda_1 & 0 & 0 & \cdots & 0 \ x_{2,1} & y_{2,1} & z_{2,1} & 0 & \cdots & 0 & \lambda_1 & 0 & 0 & \cdots \ 0 & x_{3,1} & y_{3,1} & z_{3,1} & 0 & \cdots & 0 & \lambda_1 & 0 & 0 \ \vdots & \ddots & \ddots & \ddots & \ddots & \ddots & \ddots & \ddots & \ddots & \vdots \ 0 & \ddots & \ddots & x_{I,1} & y_{I,1} & 0 & 0 & 0 & 0 & \lambda_1\ \lambda_2 & 0 & 0 & 0 & 0 & y_{1,2} & z_{1,2} & 0 & 0 & 0 \ 0 & \lambda_2 & 0 & 0 & 0 & x_{2,2} & y_{2,2} & z_{2,2} & 0 & 0 \ 0 & 0 & \lambda_2 & 0 & 0 & 0 & x_{3,2} & y_{3,2} & z_{3,2} & 0 \ 0 & 0 & \ddots & \ddots & \ddots & \ddots & \ddots & \ddots & \ddots & \ddots \ 0 & \cdots & \cdots & 0 & \lambda_2 & 0 & \cdots & 0 & x_{I,2} & y_{I,2} \end{matrix}\right], \quad u^n = \left[\begin{matrix} u(c_{1,1}^n)\ \vdots \ \vdots \ u(c_{I,1}^n)\ u(c_{1,2}^n) \ \vdots \ \vdots \ u(c_{I,2}^n)\end{matrix}\right]$$
This system can in turn be written as
$$
\begin{align}\mathbf{B}^n v^{n+1} = b^n, \quad \quad \mathbf{B}^n = \left(\frac{1}{\Delta} + \rho\right)\mathbf{I} - \mathbf{A}^n, \quad b^n = u^n + \frac{1}{\Delta}v^n \end{align}
$$
This system of linear equations can be solved very efficiently using sparse matrix routines. In Python this is implemented with the function "spsolve()."
Summary of Algorithm
First consider the algorithm for solving the HJB equations. Guess $v^0_{i,j},i=1,...,I,j=1,2$ and for $n=0,1,2,...$ follow
1. Compute $(v^n_{i,j})'$ using the current guess of the value function and the upwind scheme (forward difference when drift is positive, backward difference when drift is negative)
2. Compute $c^n$ from $c_{i,j}^n = (u')^{-1}[(v_{i,j}^n)']$
3. Find $v^{n+1}$ by solving the system of linear equations involving the matrix $\mathbf{A}$ described above (implicit scheme)
4. If $v^{n+1}$ is close enough to $v^n$: stop. Otherwise, go to step 1.
After solving the HJB equations, solving the Kolmogorov Forward equation: simply solve the eigenvalue problem $0=\mathbf{A}^T g$ described above. That is, once the HJB equation is solved, we basically get the Kolmogorov Forward equation "for free."
Overview of Code
Given this overview of the algorithm, we now briefly describe the code. As in the discrete-time version, we define a "household" class. Household objects contain all the data relevant to solving a household's decision problem. The household class contain:
* economic parameters (e.g., w, r)
* utility paramters (e.g., discount factor $\rho$)
* asset and skill level represented on a grid
The household's decision problem is solved by invoking the function solve_bellman() which solves the HJB equation given the relevant parameters saving the value-function as v.
We also include the stationary wealth distribution of households in the household object. This is a natural thing to do since this stationary distribution is computed using the household's decision rule. Hence, after computing the decision problem of households, the stationary distribution can be found by invoking compute_stationary_distribution()
The definition of the household class is given below. | class Household(object):
def __init__(self,
r=0.03, # interest rate
w=1, # wages
rho=0.04, # discount factor
a_min=1e-10, # minimum asset amount
pi=[[-0.1, 0.1], [0.1, -0.1]], # poisson Jumps
z_vals=[0.1, 1.0], # exogenous income states
a_max=40,
a_size=1000, # number of asset grid points
delta=1000.0):
# Initialize values, and set up grids over a and z
self.r, self.w, self.rho = r, w, rho
self.a_min, self.a_max, self.a_size = a_min, a_max, a_size
self.da = (self.a_max-self.a_min)/(self.a_size-1)
self.k = 10
self.pi = np.asarray(pi)
self.z_vals = np.asarray(z_vals)
self.z_size = len(z_vals)
self.a_vals = np.linspace(self.a_min, self.a_max, self.a_size)
self.n = self.a_size * self.z_size
self.delta = delta
# Initial Guess of Value Function
self.v = np.log(np.tile(self.a_vals,(self.z_size,1))*self.r
+self.w*np.tile(self.z_vals,(self.a_size,1)).transpose())/self.rho
# Build skill_transition, the matrix summarizing transitions due to the Poisson income shocks
# This is analogous to the Q matrix in the discrete time version of the QuantEcon Aiyagari model
self.z_transition = sparse.kron(self.pi,sparse.eye(self.a_size))
# Preallocation
self.v_old = np.zeros((self.z_size,self.a_size))
self.g = np.zeros((self.z_size,self.a_size))
self.dv = np.zeros((self.z_size,self.a_size-1))
self.cf = np.zeros((self.z_size,self.a_size-1))
self.c0 = np.zeros((self.z_size,self.a_size))
self.ssf = np.zeros((self.z_size,self.a_size))
self.ssb = np.zeros((self.z_size,self.a_size))
self.is_forward = np.zeros((self.z_size,self.a_size),'bool')
self.is_backward = np.zeros((self.z_size,self.a_size),'bool')
self.diag_helper = np.zeros((self.z_size,self.a_size))
self.A = self.z_transition.copy()
self.B = self.z_transition.copy()
self.AT = self.z_transition.copy()
def set_prices(self, r, w):
"""
Resets prices
Calling the method will resolves the Bellman Equation.
Parameters:
-----------------
r : Interest rate
w : wage
"""
self.r, self.w = r, w
self.solve_bellman()
def reinitialize_v(self):
"""
Reinitializes the value function if the value function
became NaN
"""
self.v = np.log(np.tile(self.a_vals,(self.z_size,1))*self.r
+self.w*np.tile(self.z_vals,(self.a_size,1)).transpose())/self.rho
def solve_bellman(self,maxiter=100,crit=1e-6):
"""
This function solves the decision problem with the given parameters
Parameters:
-----------------
maxiter : maximum number of iteration before haulting value function iteration
crit : convergence metric, stops if value function does not change more than crit
"""
dist=100.0
for i in range(maxiter):
# compute saving and consumption implied by current guess for value function, using upwind method
self.dv = (self.v[:,1:]-self.v[:,:-1])/self.da
self.cf = 1.0/self.dv
self.c0 = np.tile(self.a_vals,(self.z_size,1))*self.r \
+self.w*np.tile(self.z_vals,(self.a_size,1)).transpose()
# computes savings with forward forward difference and backward difference
self.ssf[:,:-1] = self.c0[:,:-1]-self.cf
self.ssb[:,1:] = self.c0[:,1:]-self.cf
# Note that the boundary conditions are handled implicitly as ssf will be zero at a_max and ssb at a_min
self.is_forward = self.ssf>0
self.is_backward = self.ssb<0
# Update consumption based on forward or backward difference based on direction of drift
self.c0[:,:-1] += (self.cf-self.c0[:,:-1])*self.is_forward[:,:-1]
self.c0[:,1:] += (self.cf-self.c0[:,1:])*self.is_backward[:,1:]
self.c0 = np.log(self.c0)
# Build the matrix A that summarizes the evolution of the process for (a,z)
# This is a Poisson transition matrix (aka intensity matrix) with rows adding up to zero
self.A = self.z_transition.copy()
self.diag_helper = (-self.ssf*self.is_forward/self.da \
+ self.ssb*self.is_backward/self.da).reshape(self.n)
self.A += sparse.spdiags(self.diag_helper,0,self.n,self.n)
self.diag_helper = (-self.ssb*self.is_backward/self.da).reshape(self.n)
self.A += sparse.spdiags(self.diag_helper[1:],-1,self.n,self.n)
self.diag_helper = (self.ssf*self.is_forward/self.da).reshape(self.n)
self.A += sparse.spdiags(np.hstack((0,self.diag_helper)),1,self.n,self.n)
# Solve the system of linear equations corresponding to implicit finite difference scheme
self.B = sparse.eye(self.n)*(1/self.delta + self.rho) - self.A
self.b = self.c0.reshape(self.n,1) + self.v.reshape(self.n,1)/self.delta
self.v_old = self.v.copy()
self.v = spsolve(self.B,self.b).reshape(self.z_size,self.a_size)
# Compute convergence metric and stop if it satisfies the convergence criterion
dist = np.amax(np.absolute(self.v_old-self.v).reshape(self.n))
if dist < crit:
break
def compute_stationary_distribution(self):
"""
Solves for the stationary distribution given household decision rules
Output:
Capital level from the stationary distribution
"""
self.AT = self.A.transpose().tocsr()
# The discretized Kolmogorov Forward equation AT*g=0 is an eigenvalue problem
# AT is singular because one of the equation is the distribution adding
# up to 1. Here we solve the eigenvalue problem by setting g(1,1)=0.1
# and the equation is solved relative to that value.
# Alternatively, one could use a routine for solving eigenvalue problems.
b = np.zeros((self.n,1))
b[0] = 0.1
self.AT.data[1:self.AT.indptr[1]] = 0
self.AT.data[0] = 1.0
self.AT.indices[0] = 0
self.AT.eliminate_zeros()
self.g = spsolve(self.AT,b).reshape(self.z_size,self.a_size)
# Since g was solved taking one of g(1,1) as given, g needs to be
# renormalized to add up to 1
self.g = self.g/np.sum(self.g)
return np.sum(self.g*(np.tile(self.a_vals,(self.z_size,1)))) | other/aiyagari_continuous_time.ipynb | supergis/git_notebook | gpl-3.0 |
For example, if interest rate is 0.05 and wage is 1, we can initialize a household, solve it decision problem, and find the stationary distribution by running | am=Household(r=0.05,w=1)
am.solve_bellman()
am.compute_stationary_distribution() | other/aiyagari_continuous_time.ipynb | supergis/git_notebook | gpl-3.0 |
Once, a household object is created, the object can be reused to solve a different problem by changing parameters. For example, if the interest rate were to change to 0.03 and wage to 0.9, the new problem can be solved by setting parameters directly by | am.r=0.03
am.w=0.9 | other/aiyagari_continuous_time.ipynb | supergis/git_notebook | gpl-3.0 |
Given the household class, solving for the steady state becomes really simple. To find the equilibrium, we solve for the capital level that is consistent with household's decisions.
Before solving for the actual steady state, we can visualize the capital demand and capital supply. | A = 2.5
N = 0.05
alpha = 0.33
def r_to_w(r):
return A * (1 - alpha) * (alpha / (1 + r))**(alpha / (1 - alpha))
def rd(K):
return A * alpha * (N / K)**(1 - alpha)
def prices_to_capital_stock(am, r):
"""
Map prices to the induced level of capital stock.
Parameters:
----------
am : Household
An instance of the Household class
r : float
The interest rate
"""
w = r_to_w(r)
# Set new prices and solve the Bellman equation
am.set_prices(r, w)
# Compute the stationary distribution and capital
return am.compute_stationary_distribution() | other/aiyagari_continuous_time.ipynb | supergis/git_notebook | gpl-3.0 |
We make a grid of interest rate points, and plot the resulting capital. | num_points = 20
r_vals = np.linspace(0.0, 0.04, num_points)
# Compute supply of capital
k_vals = np.empty(num_points)
for i, r in enumerate(r_vals):
k_vals[i] = prices_to_capital_stock(am,r)
# Plot supply and demand of capital
fig, ax = plt.subplots(figsize=(11, 8))
ax.plot(k_vals, r_vals, lw=2, alpha=0.6, label='supply of capital')
ax.plot(k_vals, rd(k_vals), lw=2, alpha=0.6, label='demand for capital')
ax.grid()
ax.set_xlabel('capital')
ax.set_ylabel('interest rate')
ax.legend(loc='upper right')
plt.show() | other/aiyagari_continuous_time.ipynb | supergis/git_notebook | gpl-3.0 |
Finally, the equilibrium interest rate can be found by using the bisection method, and we can see the equilibrium distribution of assets. | # Set parameters for bisection method
crit = 1e-6
r_min = 0.02
r_max = 0.04
r = 0.03
# Bisection loop
for i in range(100):
am.set_prices(r,r_to_w(r))
r_new = rd(am.compute_stationary_distribution())
if np.absolute(r_new-r)<crit:
break
elif r_new > r:
r_min = r
r = (r_max+r_min)/2.
else:
r_max = r
r = (r_max+r_min)/2.
# Plot stationary distribution at the equilibrium
fig, ax = plt.subplots(figsize=(11, 8))
n=500 # Determine the max asset level to show in the plot
ax.plot(am.a_vals[0:n], am.g[0,0:n], lw=2, alpha=0.6, label='low income')
ax.plot(am.a_vals[0:n], am.g[1,0:n], lw=2, alpha=0.6, label='high income')
ax.grid()
ax.set_xlabel('asset position')
ax.set_ylabel('distribution')
ax.legend(loc='upper right')
plt.show() | other/aiyagari_continuous_time.ipynb | supergis/git_notebook | gpl-3.0 |
Гистограмма выборки: | plt.hist(sample, normed=True)
plt.ylabel('fraction of samples')
plt.xlabel('$x$') | 1 Mathematics and Python/Lectures notebooks/12 sample distribution evaluation/sample_distribution_evaluation.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Попробуем задавать число карманов гистограммы вручную: | plt.hist(sample, bins=3, normed=True)
plt.ylabel('fraction of samples')
plt.xlabel('$x$')
plt.hist(sample, bins=40, normed=True)
plt.ylabel('fraction of samples')
plt.xlabel('$x$') | 1 Mathematics and Python/Lectures notebooks/12 sample distribution evaluation/sample_distribution_evaluation.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Explore the Data
MNIST
As you're aware, the MNIST dataset contains images of handwritten digits.
You can view the first number of examples by changing show_n_images. | show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
%matplotlib inline
import os
from glob import glob
from matplotlib import pyplot
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')
pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')
mnist_images.shape | udacity-dl/GAN/dlnd_face_generation.ipynb | arasdar/DL | unlicense |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.