markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
<a id=groupby></a>
Grouping data
Next up: group data by some variable. As an example, how would we compute the average rating of each movie? If you think for a minute, you might think of these steps:
Group the data by movie: Put all the "Pulp Fiction" ratings in one bin, all the "Shawshank" ratings in another. We... | # group
g = ml[['title', 'rating']].groupby('title')
type(g) | Code/notebooks/bootcamp_pandas-summarize.ipynb | NYUDataBootcamp/Materials | mit |
Now that we have a groupby object, what can we do with it? | # the number in each category
g.count().head(10)
# what type of object have we created?
type(g.count()) | Code/notebooks/bootcamp_pandas-summarize.ipynb | NYUDataBootcamp/Materials | mit |
Comment. Note that the combination of groupby and count created a dataframe with
Its index is the variable we grouped by. If we group by more than one, we get a multi-index.
Its columns are the other variables.
Exercise. Take the code
python
counts = ml.groupby(['title', 'movieId'])
Without running it, what is t... | counts = ml.groupby(['title', 'movieId']).count()
gm = g.mean()
gm.head()
# we can put them together
grouped = g.count()
grouped = grouped.rename(columns={'rating': 'Number'})
grouped['Mean'] = g.mean()
grouped.head(10)
grouped.plot.scatter(x='Number', y='Mean') | Code/notebooks/bootcamp_pandas-summarize.ipynb | NYUDataBootcamp/Materials | mit |
Create a model
We first create a toy model to simulate the groundwater levels in southeastern Austria. We will use this model to illustrate how the different methods for uncertainty quantification can be used. | gwl = pd.read_csv("data_wagna/head_wagna.csv", index_col=0, parse_dates=True,
squeeze=True, skiprows=2).loc["2006":].iloc[0::10]
evap = pd.read_csv("data_wagna/evap_wagna.csv", index_col=0, parse_dates=True,
squeeze=True, skiprows=2)
prec = pd.read_csv("data_wagna/rain_wagna.csv",... | examples/notebooks/16_uncertainty.ipynb | pastas/pasta | mit |
Diagnostic Checks
Before we perform the uncertainty quantification, we should check if the underlying statistical assumptions are met. We refer to the notebook on Diagnostic checking for more details on this. | ml.plots.diagnostics(); | examples/notebooks/16_uncertainty.ipynb | pastas/pasta | mit |
Confidence intervals
After the model is calibrated, a fit attribute is added to the Pastas Model object (ml.fit). This object contains information about the optimizations (e.g., the jacobian matrix) and a number of methods that can be used to quantify uncertainties. | ci = ml.fit.ci_simulation(alpha=0.05, n=1000)
ax = ml.plot(figsize=(10,3));
ax.fill_between(ci.index, ci.iloc[:,0], ci.iloc[:,1], color="lightgray")
ax.legend(["Observations", "Simulation", "95% Confidence interval"], ncol=3, loc=2) | examples/notebooks/16_uncertainty.ipynb | pastas/pasta | mit |
Prediction interval | ci = ml.fit.prediction_interval(n=1000)
ax = ml.plot(figsize=(10,3));
ax.fill_between(ci.index, ci.iloc[:,0], ci.iloc[:,1], color="lightgray")
ax.legend(["Observations", "Simulation", "95% Prediction interval"], ncol=3, loc=2) | examples/notebooks/16_uncertainty.ipynb | pastas/pasta | mit |
Uncertainty of step response | ci = ml.fit.ci_step_response("rch")
ax = ml.plots.step_response(figsize=(6,2))
ax.fill_between(ci.index, ci.iloc[:,0], ci.iloc[:,1], color="lightgray")
ax.legend(["Simulation", "95% Prediction interval"], ncol=3, loc=4) | examples/notebooks/16_uncertainty.ipynb | pastas/pasta | mit |
Uncertainty of block response | ci = ml.fit.ci_block_response("rch")
ax = ml.plots.block_response(figsize=(6,2))
ax.fill_between(ci.index, ci.iloc[:,0], ci.iloc[:,1], color="lightgray")
ax.legend(["Simulation", "95% Prediction interval"], ncol=3, loc=1) | examples/notebooks/16_uncertainty.ipynb | pastas/pasta | mit |
Uncertainty of the contributions | ci = ml.fit.ci_contribution("rch")
r = ml.get_contribution("rch")
ax = r.plot(figsize=(10,3))
ax.fill_between(ci.index, ci.iloc[:,0], ci.iloc[:,1], color="lightgray")
ax.legend(["Simulation", "95% Prediction interval"], ncol=3, loc=1)
plt.tight_layout() | examples/notebooks/16_uncertainty.ipynb | pastas/pasta | mit |
Custom Confidence intervals
It is also possible to compute the confidence intervals manually, for example to estimate the uncertainty in the recharge or statistics (e.g., SGI, NSE). We can call ml.fit.get_parameter_sample to obtain random parameter samples from a multivariate normal distribution using the optimal param... | params = ml.fit.get_parameter_sample(n=1000, name="rch")
data = {}
# Here we run the model n times with different parameter samples
for i, param in enumerate(params):
data[i] = ml.stressmodels["rch"].get_stress(p=param)
df = pd.DataFrame.from_dict(data, orient="columns").loc[tmin:tmax].resample("A").sum()
ci = df... | examples/notebooks/16_uncertainty.ipynb | pastas/pasta | mit |
Uncertainty of the NSE
The code pattern shown above can be used for many types of uncertainty analyses. Another example is provided below, where we compute the uncertainty of the Nash-Sutcliffe efficacy. | params = ml.fit.get_parameter_sample(n=1000)
data = []
# Here we run the model n times with different parameter samples
for i, param in enumerate(params):
sim = ml.simulate(p=param)
data.append(ps.stats.nse(obs=ml.observations(), sim=sim))
fig, ax = plt.subplots(1,1, figsize=(4,3))
plt.hist(data, bins=50, den... | examples/notebooks/16_uncertainty.ipynb | pastas/pasta | mit |
Regular tables
Solid lines are original tables, dashed lines are the new tables. | z = np.linspace(0, 50, 100)
plot_rates(z, ['CloudyData_UVB=HM2012.h5',
'CloudyData_HM2012_highz.h5'],
'Chemistry', ['k24', 'k25', 'k26', 'k29', 'k30'])
pyplot.ylim(1e-29, 1e-11)
z = np.linspace(0, 50, 100)
plot_rates(z, ['CloudyData_UVB=HM2012.h5',
'CloudyData_HM2012_highz.h5']... | physics_data/UVB/grackle_tables/photo.ipynb | aemerick/galaxy_analysis | mit |
Self-shielded tables
Solid lines are original tables, dashed lines are the new tables. | z = np.linspace(0, 50, 100)
plot_rates(z, ['CloudyData_UVB=HM2012_shielded.h5',
'CloudyData_HM2012_highz_shielded.h5'],
'Chemistry', ['k24', 'k25', 'k26', 'k29', 'k30'])
pyplot.ylim(1e-29, 1e-11)
z = np.linspace(0, 50, 100)
plot_rates(z, ['CloudyData_UVB=HM2012_shielded.h5',
'C... | physics_data/UVB/grackle_tables/photo.ipynb | aemerick/galaxy_analysis | mit |
Question 2
Use the matrix-vector multiplication and apply the Map function to this matrix and vector:
| 1 | 2 | 3 | 4 | | 1 |
|---|---|---|---| |---|
| 5 | 6 | 7 | 8 | | 2 |
| 9 | 10 | 11 | 12 | | 3 |
| 13 | 14 | 15 | 16 | | 4 |
Then, identify the key-value pairs that are output of Map. | import numpy as np
import itertools
M = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],])
v = np.array([1, 2, 3, 4])
def mr(M, v):
t = []
mr, mc = M.shape
for i in range(mc):
for j in range(mr):
t.append((i, M[i, j] * ... | Mining massive datasets/MapReduce SVM.ipynb | shngli/Data-Mining-Python | gpl-3.0 |
Question 3
Suppose we have the following relations: | from IPython.display import Image
Image(filename='relations.jpeg') | Mining massive datasets/MapReduce SVM.ipynb | shngli/Data-Mining-Python | gpl-3.0 |
and we take their natural join. Apply the Map function to the tuples of these relations. Then, construct the elements that are input to the Reduce function. Identify these elements. | import numpy as np
import itertools
R = [(0, 1),
(1, 2),
(2, 3)]
S = [(0, 1),
(1, 2),
(2, 3)]
def hash_join(R, S):
h = {}
for a, b in R:
h.setdefault(b, []).append(a)
j = []
for b, c in S:
if not h.has_key(b):
continue
for r in h[b]:
... | Mining massive datasets/MapReduce SVM.ipynb | shngli/Data-Mining-Python | gpl-3.0 |
Question 4
The figure below shows two positive points (purple squares) and two negative points (green circles): | from IPython.display import Image
Image(filename='svm1.jpeg') | Mining massive datasets/MapReduce SVM.ipynb | shngli/Data-Mining-Python | gpl-3.0 |
That is, the training data set consists of:
- (x1,y1) = ((5,4),+1)
- (x2,y2) = ((8,3),+1)
- (x3,y3) = ((7,2),-1)
- (x4,y4) = ((3,3),-1)
Our goal is to find the maximum-margin linear classifier for this data. In easy cases, the shortest line between a positive and negative point has a perpendicular bisector that separat... | import math
import numpy as np
P = [((5, 4), 1),
((8, 3), 1),
((3, 3), -1),
((7, 2), -1)]
def line(pl0, pl1, p):
dx, dy = pl1[0] - pl0[0], pl1[1] - pl0[1]
a = abs((pl1[1] - pl0[1]) * p[0] - (pl1[0] - pl0[0]) * p[1] + pl1[0]*pl0[1] - pl0[0]*pl1[1])
return a / math.sqrt(dx*dx + dy*dy)
def cl... | Mining massive datasets/MapReduce SVM.ipynb | shngli/Data-Mining-Python | gpl-3.0 |
Question 5
Consider the following training set of 16 points. The eight purple squares are positive examples, and the eight green circles are negative examples. | Image(filename='newsvm4.jpeg') | Mining massive datasets/MapReduce SVM.ipynb | shngli/Data-Mining-Python | gpl-3.0 |
We propose to use the diagonal line with slope +1 and intercept +2 as a decision boundary, with positive examples above and negative examples below. However, like any linear boundary for this training set, some examples are misclassified. We can measure the goodness of the boundary by computing all the slack variables ... | import numpy as np
pos = [(5, 10),
(7, 10),
(1, 8),
(3, 8),
(7, 8),
(1, 6),
(3, 6),
(3, 4)]
neg = [(5, 8),
(5, 6),
(7, 6),
(1, 4),
(5, 4),
(7, 4),
(1, 2),
(3, 2)]
C = [(x, 1) for x in pos] + [(x, -1) for x in neg]
w, b... | Mining massive datasets/MapReduce SVM.ipynb | shngli/Data-Mining-Python | gpl-3.0 |
Question 6
Below we see a set of 20 points and a decision tree for classifying the points. | Image(filename='gold.jpeg')
Image(filename='dectree1.jpeg') | Mining massive datasets/MapReduce SVM.ipynb | shngli/Data-Mining-Python | gpl-3.0 |
To be precise, the 20 points represent (Age,Salary) pairs of people who do or do not buy gold jewelry. Age (appreviated A in the decision tree) is the x-axis, and Salary (S in the tree) is the y-axis. Those that do are represented by gold points, and those that do not by green points. The 10 points of gold-jewelry buye... | A = 0
S = 1
pos = [(28,145),
(38,115),
(43,83),
(50,130),
(50,90),
(50,60),
(50,30),
(55,118),
(63,88),
(65,140)]
neg = [(23,40),
(25,125),
(29,97),
(33,22),
(35,63),
(42,57),
(44, 105),
(55,63),
(55... | Mining massive datasets/MapReduce SVM.ipynb | shngli/Data-Mining-Python | gpl-3.0 |
Defining a custom Dataset
The dataset's in this library consists of iterators which yield batches of the corresponding data. For the provided tasks, these dataset have 4 splits of data rather than the traditional 3. We have "train" which is data used by the task to train a model, "inner_valid" which contains validation... | import numpy as np
def data_iterator():
bs = 3
while True:
batch = {"data": np.zeros([bs, 5])}
yield batch
@datasets_base.dataset_lru_cache
def get_datasets():
return datasets_base.Datasets(
train=data_iterator(),
inner_valid=data_iterator(),
outer_valid=data_iterator(),
test=d... | docs/notebooks/Part2_CustomTasks.ipynb | google/learned_optimization | apache-2.0 |
Defining a custom Task
To define a custom class, one simply needs to write a base class of Task. Let's look at a simple task consisting of a quadratic task with noisy targets. | # First we construct data iterators.
def noise_datasets():
def _fn():
while True:
yield np.random.normal(size=[4, 2]).astype(dtype=np.float32)
return datasets_base.Datasets(
train=_fn(), inner_valid=_fn(), outer_valid=_fn(), test=_fn())
class MyTask(tasks_base.Task):
datasets = noise_datasets(... | docs/notebooks/Part2_CustomTasks.ipynb | google/learned_optimization | apache-2.0 |
Meta-training on multiple tasks: TaskFamily
What we have shown previously was meta-training on a single task instance.
While sometimes this is sufficient for a given situation, in many situations we seek to meta-train a meta-learning algorithm such as a learned optimizer on a mixture of different tasks.
One path to do ... | PRNGKey = jnp.ndarray
TaskParams = jnp.ndarray
class FixedDimQuadraticFamily(tasks_base.TaskFamily):
"""A simple TaskFamily with a fixed dimensionality but sampled target."""
def __init__(self, dim: int):
super().__init__()
self._dim = dim
self.datasets = None
def sample(self, key: PRNGKey) -> Tas... | docs/notebooks/Part2_CustomTasks.ipynb | google/learned_optimization | apache-2.0 |
With this task family defined, we can create instances by sampling a configuration and creating a task. This task acts like any other task in that it has an init and a loss function. | task_family = FixedDimQuadraticFamily(10)
key = jax.random.PRNGKey(0)
task_cfg = task_family.sample(key)
task = task_family.task_fn(task_cfg)
key1, key = jax.random.split(key)
params = task.init(key)
batch = None
task.loss(params, key, batch) | docs/notebooks/Part2_CustomTasks.ipynb | google/learned_optimization | apache-2.0 |
To achive speedups, we can now leverage jax.vmap to train multiple task instances in parallel! Depending on the task, this can be considerably faster than serially executing them. | def train_task(cfg, key):
task = task_family.task_fn(cfg)
key1, key = jax.random.split(key)
params = task.init(key1)
opt = opt_base.Adam()
opt_state = opt.init(params)
for i in range(4):
params = opt.get_params(opt_state)
loss, grad = jax.value_and_grad(task.loss)(params, key, None)
opt_state ... | docs/notebooks/Part2_CustomTasks.ipynb | google/learned_optimization | apache-2.0 |
Because of this ability to apply vmap over task families, this is the main building block for a number of the high level libraries in this package. Single tasks can always be converted to a task family with: | single_task = image_mlp.ImageMLP_FashionMnist8_Relu32()
task_family = tasks_base.single_task_to_family(single_task) | docs/notebooks/Part2_CustomTasks.ipynb | google/learned_optimization | apache-2.0 |
This wrapper task family has no configuable value and always returns the base task. | cfg = task_family.sample(key)
print("config only contains a dummy value:", cfg)
task = task_family.task_fn(cfg)
# Tasks are the same
assert task == single_task | docs/notebooks/Part2_CustomTasks.ipynb | google/learned_optimization | apache-2.0 |
The MNIST data that TensorFlow pre-loads comes as 28x28x1 images.
However, the LeNet architecture only accepts 32x32xC images, where C is the number of color channels.
In order to reformat the MNIST data into a shape that LeNet will accept, we pad the data with two rows of zeros on the top and bottom, and two columns o... | import numpy as np
# Pad images with 0s
X_train = np.pad(X_train, ((0,0),(2,2),(2,2),(0,0)), 'constant')
X_validation = np.pad(X_validation, ((0,0),(2,2),(2,2),(0,0)), 'constant')
X_test = np.pad(X_test, ((0,0),(2,2),(2,2),(0,0)), 'constant')
print("Updated Image Shape: {}".format(X_train[0].shape)) | CarND-LeNet-Lab/LeNet-Lab.ipynb | rajeshb/SelfDrivingCar | mit |
Visualize Data
View a sample from the dataset.
You do not need to modify this section. | import random
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
index = random.randint(0, len(X_train))
image = X_train[index].squeeze()
plt.figure(figsize=(1,1))
plt.imshow(image, cmap="gray")
print(y_train[index]) | CarND-LeNet-Lab/LeNet-Lab.ipynb | rajeshb/SelfDrivingCar | mit |
Preprocess Data
Shuffle the training data.
You do not need to modify this section. | from sklearn.utils import shuffle
X_train, y_train = shuffle(X_train, y_train) | CarND-LeNet-Lab/LeNet-Lab.ipynb | rajeshb/SelfDrivingCar | mit |
Setup TensorFlow
The EPOCH and BATCH_SIZE values affect the training speed and model accuracy.
You do not need to modify this section. | import tensorflow as tf
EPOCHS = 10
BATCH_SIZE = 128 | CarND-LeNet-Lab/LeNet-Lab.ipynb | rajeshb/SelfDrivingCar | mit |
TODO: Implement LeNet-5
Implement the LeNet-5 neural network architecture.
This is the only cell you need to edit.
Input
The LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since MNIST images are grayscale, C is 1 in this case.
Architecture
Layer 1: Convolutional. The outpu... | from tensorflow.contrib.layers import flatten
def LeNet(x):
# Hyperparameters
mu = 0
sigma = 0.1
dropout = 0.75
# TODO: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
weights = {
'wc1': tf.Variable(tf.random_normal([5,5,1,6])),
'wc2': tf.Variable(tf.... | CarND-LeNet-Lab/LeNet-Lab.ipynb | rajeshb/SelfDrivingCar | mit |
Features and Labels
Train LeNet to classify MNIST data.
x is a placeholder for a batch of input images.
y is a placeholder for a batch of output labels.
You do not need to modify this section. | x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, 10) | CarND-LeNet-Lab/LeNet-Lab.ipynb | rajeshb/SelfDrivingCar | mit |
Training Pipeline
Create a training pipeline that uses the model to classify MNIST data.
You do not need to modify this section. | rate = 0.001
logits = LeNet(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation) | CarND-LeNet-Lab/LeNet-Lab.ipynb | rajeshb/SelfDrivingCar | mit |
Model Evaluation
Evaluate how well the loss and accuracy of the model for a given dataset.
You do not need to modify this section. | correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
sess = tf.get_default_session()
for offset in ra... | CarND-LeNet-Lab/LeNet-Lab.ipynb | rajeshb/SelfDrivingCar | mit |
Train the Model
Run the training data through the training pipeline to train the model.
Before each epoch, shuffle the training set.
After each epoch, measure the loss and accuracy of the validation set.
Save the model after training.
You do not need to modify this section. | with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
num_examples = len(X_train)
print("Training...")
print()
for i in range(EPOCHS):
X_train, y_train = shuffle(X_train, y_train)
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH... | CarND-LeNet-Lab/LeNet-Lab.ipynb | rajeshb/SelfDrivingCar | mit |
Evaluate the Model
Once you are completely satisfied with your model, evaluate the performance of the model on the test set.
Be sure to only do this once!
If you were to measure the performance of your trained model on the test set, then improve your model, and then measure the performance of your model on the test set... | with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('.'))
test_accuracy = evaluate(X_test, y_test)
print("Test Accuracy = {:.3f}".format(test_accuracy)) | CarND-LeNet-Lab/LeNet-Lab.ipynb | rajeshb/SelfDrivingCar | mit |
ENDF: Resonance Covariance Data
Let's download the ENDF/B-VII.1 evaluation for $^{157}$Gd and load it in: | # Download ENDF file
url = 'https://t2.lanl.gov/nis/data/data/ENDFB-VII.1-neutron/Gd/157'
filename, headers = urllib.request.urlretrieve(url, 'gd157.endf')
# Load into memory
gd157_endf = openmc.data.IncidentNeutron.from_endf(filename, covariance=True)
gd157_endf | examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
We can access the parameters contained within File 32 in a similar manner to the File 2 parameters from before. | gd157_endf.resonance_covariance.ranges[0].parameters[:5] | examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
The newly created object will contain multiple resonance regions within gd157_endf.resonance_covariance.ranges. We can access the full covariance matrix from File 32 for a given range by: | covariance = gd157_endf.resonance_covariance.ranges[0].covariance | examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
This covariance matrix currently only stores the upper triangular portion as covariance matrices are symmetric. Plotting the covariance matrix: | plt.imshow(covariance, cmap='seismic',vmin=-0.008, vmax=0.008)
plt.colorbar() | examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
The correlation matrix can be constructed using the covariance matrix and also give some insight into the relations among the parameters. | corr = np.zeros([len(covariance),len(covariance)])
for i in range(len(covariance)):
for j in range(len(covariance)):
corr[i, j]=covariance[i, j]/covariance[i, i]**(0.5)/covariance[j, j]**(0.5)
plt.imshow(corr, cmap='seismic',vmin=-1.0, vmax=1.0)
plt.colorbar()
| examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
Sampling and Reconstruction
The covariance module also has the ability to sample a new set of parameters using the covariance matrix. Currently the sampling uses numpy.multivariate_normal(). Because parameters are assumed to have a multivariate normal distribution this method doesn't not currently guarantee that sample... | rm_resonance = gd157_endf.resonances.ranges[0]
n_samples = 5
samples = gd157_endf.resonance_covariance.ranges[0].sample(n_samples)
type(samples[0])
| examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
The sampling routine requires the incorporation of the openmc.data.ResonanceRange for the same resonance range object. This allows each sample itself to be its own openmc.data.ResonanceRange with a new set of parameters. Looking at some of the sampled parameters below: | print('Sample 1')
samples[0].parameters[:5]
print('Sample 2')
samples[1].parameters[:5] | examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
We can reconstruct the cross section from the sampled parameters using the reconstruct method of openmc.data.ResonanceRange. For more on reconstruction see the Nuclear Data example notebook. | gd157_endf.resonances.ranges
energy_range = [rm_resonance.energy_min, rm_resonance.energy_max]
energies = np.logspace(np.log10(energy_range[0]),
np.log10(energy_range[1]), 10000)
for sample in samples:
xs = sample.reconstruct(energies)
elastic_xs = xs[2]
plt.loglog(energies, elastic_... | examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
Subset Selection
Another capability of the covariance module is selecting a subset of the resonance parameters and the corresponding subset of the covariance matrix. We can do this by specifying the value we want to discriminate and the bounds within one energy region. Selecting only resonances with J=2: | lower_bound = 2; # inclusive
upper_bound = 2; # inclusive
rm_res_cov_sub = gd157_endf.resonance_covariance.ranges[0].subset('J',[lower_bound,upper_bound])
rm_res_cov_sub.file2res.parameters[:5] | examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
The subset method will also store the corresponding subset of the covariance matrix | rm_res_cov_sub.covariance
gd157_endf.resonance_covariance.ranges[0].covariance.shape
| examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
Checking the size of the new covariance matrix to be sure it was sampled properly: | old_n_parameters = gd157_endf.resonance_covariance.ranges[0].parameters.shape[0]
old_shape = gd157_endf.resonance_covariance.ranges[0].covariance.shape
new_n_parameters = rm_res_cov_sub.file2res.parameters.shape[0]
new_shape = rm_res_cov_sub.covariance.shape
print('Number of parameters\nOriginal: '+str(old_n_parameters... | examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
And finally, we can sample from the subset as well | samples_sub = rm_res_cov_sub.sample(n_samples)
samples_sub[0].parameters[:5] | examples/jupyter/nuclear-data-resonance-covariance.ipynb | mit-crpg/openmc | mit |
Controlling for Random Negatve vs Sans Random in Imbalanced Techniques using K acytelation.
Training data is from CUCKOO group and benchmarks are from dbptm. | par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
for i in par:
print("y", i)
y = Predictor()
y.load_data(file="Data/Training/k_acetylation.csv")
y.process_data(vector_function="sequence", amino_acid="K", imbalance_function=i, random_data=0)
y.supervised_training("svc")... | .ipynb_checkpoints/Lysine Acetylation -svc-checkpoint.ipynb | vzg100/Post-Translational-Modification-Prediction | mit |
Chemical Vector | par = ["pass", "ADASYN", "SMOTEENN", "random_under_sample", "ncl", "near_miss"]
for i in par:
print("y", i)
y = Predictor()
y.load_data(file="Data/Training/k_acetylation.csv")
y.process_data(vector_function="chemical", amino_acid="K", imbalance_function=i, random_data=0)
y.supervised_training("svc")... | .ipynb_checkpoints/Lysine Acetylation -svc-checkpoint.ipynb | vzg100/Post-Translational-Modification-Prediction | mit |
Simple TFX Pipeline for Vertex Pipelines
<div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/tfx/tutorials/tfx/gcp/vertex_pipelines_simple">
<img src="https://www.tensorflow.org/images/tf_logo_32px.png"/>View on TensorFlow.org</a><... | # Use the latest version of pip.
!pip install --upgrade pip
!pip install --upgrade "tfx[kfp]<2" | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
Did you restart the runtime?
If you are using Google Colab, the first time that you run
the cell above, you must restart the runtime by clicking
above "RESTART RUNTIME" button or using "Runtime > Restart
runtime ..." menu. This is because of the way that Colab
loads packages.
If you are not on Colab, you can restart ru... | # docs_infra: no_execute
import sys
if not 'google.colab' in sys.modules:
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True) | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
Login in to Google for this notebook
If you are running this notebook on Colab, authenticate with your user account: | import sys
if 'google.colab' in sys.modules:
from google.colab import auth
auth.authenticate_user() | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
If you are on AI Platform Notebooks, authenticate with Google Cloud before
running the next section, by running
sh
gcloud auth login
in the Terminal window (which you can open via File > New in the
menu). You only need to do this once per notebook instance.
Check the package versions. | import tensorflow as tf
print('TensorFlow version: {}'.format(tf.__version__))
from tfx import v1 as tfx
print('TFX version: {}'.format(tfx.__version__))
import kfp
print('KFP version: {}'.format(kfp.__version__)) | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
Set up variables
We will set up some variables used to customize the pipelines below. Following
information is required:
GCP Project id. See
Identifying your project id.
GCP Region to run pipelines. For more information about the regions that
Vertex Pipelines is available in, see the
Vertex AI locations guide.
Google ... | GOOGLE_CLOUD_PROJECT = '' # <--- ENTER THIS
GOOGLE_CLOUD_REGION = '' # <--- ENTER THIS
GCS_BUCKET_NAME = '' # <--- ENTER THIS
if not (GOOGLE_CLOUD_PROJECT and GOOGLE_CLOUD_REGION and GCS_BUCKET_NAME):
from absl import logging
logging.error('Please set all required parameters.') | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
Set gcloud to use your project. | !gcloud config set project {GOOGLE_CLOUD_PROJECT}
PIPELINE_NAME = 'penguin-vertex-pipelines'
# Path to various pipeline artifact.
PIPELINE_ROOT = 'gs://{}/pipeline_root/{}'.format(
GCS_BUCKET_NAME, PIPELINE_NAME)
# Paths for users' Python module.
MODULE_ROOT = 'gs://{}/pipeline_module/{}'.format(
GCS_BUCKET_... | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
Prepare example data
We will use the same
Palmer Penguins dataset
as
Simple TFX Pipeline Tutorial.
There are four numeric features in this dataset which were already normalized
to have range [0,1]. We will build a classification model which predicts the
species of penguins.
We need to make our own copy of the dataset. ... | !gsutil cp gs://download.tensorflow.org/data/palmer_penguins/penguins_processed.csv {DATA_ROOT}/ | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
Take a quick look at the CSV file. | !gsutil cat {DATA_ROOT}/penguins_processed.csv | head | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
Create a pipeline
TFX pipelines are defined using Python APIs. We will define a pipeline which
consists of three components, CsvExampleGen, Trainer and Pusher. The pipeline
and model definition is almost the same as
Simple TFX Pipeline Tutorial.
The only difference is that we don't need to set metadata_connection_confi... | _trainer_module_file = 'penguin_trainer.py'
%%writefile {_trainer_module_file}
# Copied from https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple
from typing import List
from absl import logging
import tensorflow as tf
from tensorflow import keras
from tensorflow_transform.tf_metadata import schema_utils
fr... | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
Copy the module file to GCS which can be accessed from the pipeline components.
Because model training happens on GCP, we need to upload this model definition.
Otherwise, you might want to build a container image including the module file
and use the image to run the pipeline. | !gsutil cp {_trainer_module_file} {MODULE_ROOT}/ | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
Write a pipeline definition
We will define a function to create a TFX pipeline. | # Copied from https://www.tensorflow.org/tfx/tutorials/tfx/penguin_simple and
# slightly modified because we don't need `metadata_path` argument.
def _create_pipeline(pipeline_name: str, pipeline_root: str, data_root: str,
module_file: str, serving_model_dir: str,
) -> tfx.dsl... | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
Run the pipeline on Vertex Pipelines.
We used LocalDagRunner which runs on local environment in
Simple TFX Pipeline Tutorial.
TFX provides multiple orchestrators to run your pipeline. In this tutorial we
will use the Vertex Pipelines together with the Kubeflow V2 dag runner.
We need to define a runner to actually run t... | # docs_infra: no_execute
import os
PIPELINE_DEFINITION_FILE = PIPELINE_NAME + '_pipeline.json'
runner = tfx.orchestration.experimental.KubeflowV2DagRunner(
config=tfx.orchestration.experimental.KubeflowV2DagRunnerConfig(),
output_filename=PIPELINE_DEFINITION_FILE)
# Following function will write the pipeline ... | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
The generated definition file can be submitted using kfp client. | # docs_infra: no_execute
from google.cloud import aiplatform
from google.cloud.aiplatform import pipeline_jobs
import logging
logging.getLogger().setLevel(logging.INFO)
aiplatform.init(project=GOOGLE_CLOUD_PROJECT, location=GOOGLE_CLOUD_REGION)
job = pipeline_jobs.PipelineJob(template_path=PIPELINE_DEFINITION_FILE,
... | docs/tutorials/tfx/gcp/vertex_pipelines_simple.ipynb | tensorflow/tfx | apache-2.0 |
Logramos una precisión del 100 %, increíble, este modelo no se equivoca! deberíamos utilizarlo para jugar a la lotería y ver si ganamos algunos millones; o tal vez, no?. Veamos como se comporta con los datos de evaluación. | # precisión del modelo en datos de evaluación.
print("precisión evaluación: {0: .2f}".format(
arbol.score(x_eval, y_eval))) | content/notebooks/MachineLearningOverfitting.ipynb | relopezbriega/mi-python-blog | gpl-2.0 |
Ah, ahora nuestro modelo ya no se muestra tan preciso, esto se debe a que seguramente esta sobreajustado, ya que dejamos crecer el árbol hasta que cada hoja estuviera pura (es decir que solo contenga datos de una sola de las clases a predecir). Una alternativa para reducir el sobreajuste y ver si podemos lograr que gen... | # profundidad del arbol de decisión.
arbol.tree_.max_depth | content/notebooks/MachineLearningOverfitting.ipynb | relopezbriega/mi-python-blog | gpl-2.0 |
Este caso nuestro modelo tiene una profundidad de 22 nodos; veamos si reduciendo esa cantidad podemos mejorar la precisión en los datos de evaluación. Por ejemplo, pongamos un máximo de profundidad de tan solo 5 nodos. | # modelo dos, con control de profundiad de 5 nodos
arbol2 = DecisionTreeClassifier(criterion='entropy', max_depth=5)
# Ajustando el modelo
arbol2.fit(x_train, y_train)
# precisión del modelo en datos de entrenamiento.
print("precisión entranamiento: {0: .2f}".format(
arbol2.score(x_train, y_train))) | content/notebooks/MachineLearningOverfitting.ipynb | relopezbriega/mi-python-blog | gpl-2.0 |
Ahora podemos ver que ya no tenemos un modelo con 100% de precisión en los datos de entrenamiento, sino que la precisión es bastante inferior, 92%, sin embargo si ahora medimos la precisión con los datos de evaluación vemos que la precisión es del 90%, 3 puntos por arriba de lo que habíamos conseguido con el primer mod... | # precisión del modelo en datos de evaluación.
print("precisión evaluación: {0: .2f}".format(
arbol2.score(x_eval, y_eval))) | content/notebooks/MachineLearningOverfitting.ipynb | relopezbriega/mi-python-blog | gpl-2.0 |
Esta diferencia se debe a que reducimos la complejidad del modelo para intentar ganar en generalización. También debemos tener en cuenta que si seguimos reduciendo la complejidad, podemos crear un modelo demasiado simple que en vez de estar sobreajustado puede tener un desempeño muy por debajo del que podría tener; pod... | # Grafico de ajuste del árbol de decisión
train_prec = []
eval_prec = []
max_deep_list = list(range(3, 23))
for deep in max_deep_list:
arbol3 = DecisionTreeClassifier(criterion='entropy', max_depth=deep)
arbol3.fit(x_train, y_train)
train_prec.append(arbol3.score(x_train, y_train))
eval_prec.append(ar... | content/notebooks/MachineLearningOverfitting.ipynb | relopezbriega/mi-python-blog | gpl-2.0 |
El gráfico que acabamos de construir se llama gráfico de ajuste y muestra la precisión del modelo en función de su complejidad. En nuestro ejemplo, podemos ver que el punto con mayor precisión, en los datos de evaluación, lo obtenemos con un nivel de profundidad de aproximadamente 5 nodos; a partir de allí el modelo pi... | # utilizando validation curve de sklearn
from sklearn.learning_curve import validation_curve
train_prec, eval_prec = validation_curve(estimator=arbol, X=x_train,
y=y_train, param_name='max_depth',
param_range=max_deep_list, cv=5)
train_me... | content/notebooks/MachineLearningOverfitting.ipynb | relopezbriega/mi-python-blog | gpl-2.0 |
En este gráfico, también podemos ver que nuestro modelo tiene bastante varianza, representada por el área esfumada.
Métodos para reducir el Sobreajuste
Algunas de las técnicas que podemos utilizar para reducir el Sobreajuste, son:
Utilizar validación cruzada.
Recolectar más datos.
Introducir una penalización a la comp... | # Ejemplo cross-validation
from sklearn import cross_validation
# creando pliegues
kpliegues = cross_validation.StratifiedKFold(y=y_train, n_folds=10,
random_state=2016)
# iterando entre los plieges
precision = []
for k, (train, test) in enumerate(kpliegues):
arbol2.fit(x_tr... | content/notebooks/MachineLearningOverfitting.ipynb | relopezbriega/mi-python-blog | gpl-2.0 |
En este ejemplo, utilizamos el <a href="https://es.wikipedia.org/wiki/Iterador_(patr%C3%B3n_de_dise%C3%B1o)">iterador</a> StratifiedKFold que nos proporciona Scikit-learn. Este <a href="https://es.wikipedia.org/wiki/Iterador_(patr%C3%B3n_de_dise%C3%B1o)">iterador</a> es una versión mejorada de la validación cruzada, ya... | # Ejemplo con cross_val_score
precision = cross_validation.cross_val_score(estimator=arbol2,
X=x_train, y=y_train,
cv=10, n_jobs=-1)
print('precisiones: {}'.format(precision))
print('Precision promedio: {0: .3f} +/- {1: .3f}'.forma... | content/notebooks/MachineLearningOverfitting.ipynb | relopezbriega/mi-python-blog | gpl-2.0 |
Más datos y curvas de aprendizaje
Muchas veces, reducir el Sobreajuste es tan fácil como conseguir más datos, dame más datos y te predeciré el futuro!. Aunque en la vida real nunca es una tarea tan sencilla conseguir más datos. Otra herramienta analítica que nos ayuda a entender como reducimos el Sobreajuste con la ayu... | # Ejemplo Curvas de aprendizaje
from sklearn.learning_curve import learning_curve
train_sizes, train_scores, test_scores = learning_curve(estimator=arbol2,
X=x_train, y=y_train,
train_sizes=np.linspace(0.1, 1.0, 10), cv=10,
n_jobs=-1)
train_mean... | content/notebooks/MachineLearningOverfitting.ipynb | relopezbriega/mi-python-blog | gpl-2.0 |
En este gráfico podemos ver claramente como con pocos datos la precisión entre los datos de entrenamiento y los de evaluación son muy distintas y luego a medida que la cantidad de datos va aumentando, el modelo puede generalizar mucho mejor y las precisiones se comienzan a emparejar. Este gráfico también puede ser impo... | # Ejemplo de grid search con SVM.
from sklearn.grid_search import GridSearchCV
# creación del modelo
svm = SVC(random_state=1982)
# rango de parametros
rango_C = np.logspace(-2, 10, 10)
rango_gamma = np.logspace(-9, 3, 10)
param_grid = dict(gamma=rango_gamma, C=rango_C)
# crear grid search
gs = GridSearchCV(estimato... | content/notebooks/MachineLearningOverfitting.ipynb | relopezbriega/mi-python-blog | gpl-2.0 |
We see that $\alpha$ shifts the function on the x axis. $\beta$ alters the steepness of the function. As already mention $\gamma$ and $\delta$ determine the floor and the ceiling of the function.
Next let's perform the analysis. We first load the data. | from urllib import urlopen
f=urlopen('http://journal.sjdm.org/12/12817/data.csv')
D=np.loadtxt(f,skiprows=3,delimiter=',')[:,7:]
f.close()
D.shape
# predictors
vfair=np.array(([range(1,8)]*6)).flatten() # in cents
vmale=np.ones(42,dtype=int); vmale[21:]=0
vface=np.int32(np.concatenate([np.zeros(7),np.ones(7),np.ones(7... | _ipynb/No Way Anova - Logistic Regression truimphs Anova.ipynb | simkovic/simkovic.github.io | mit |
It is good to do some manual fitting to see just how the logistic curve behaves but also to assure ourselves that the we can get a shape similar the pattern of our data. | D[D==2]=np.nan
R=np.zeros((3,7))
for i in np.unique(vface).tolist():
for j in np.unique(vfair).tolist():
sel=np.logical_and(i==vface,j==vfair)
R[i,j-1]=np.nansum(D[:,sel])/(~np.isnan(D[:,sel])).sum()
for i in range(3):
y=1/(1+exp(4.5-1.2*np.arange(1,8)))*0.5+[0.4,0.44,0.47][i]
plt.plot(range... | _ipynb/No Way Anova - Logistic Regression truimphs Anova.ipynb | simkovic/simkovic.github.io | mit |
Above I fitted the logistic curve to the data. I got the parameter values by several iterations of trial-and-error. We want to obtain precise estimates and also we wish to get an idea about the uncertainty of the estimate. We implement the model in STAN. | import pystan
model = """
data {
int<lower=0> N;
int<lower=0,upper=1> coop[N]; // acceptance
int<lower=0,upper=8> fair[N]; // fairness
int<lower=1,upper=3> face[N]; // face expression
}
parameters {
real<lower=-20,upper=20> alpha[3];
real<lower=0,upper=10> beta[3];
simplex[3] gamm[3];
}
tr... | _ipynb/No Way Anova - Logistic Regression truimphs Anova.ipynb | simkovic/simkovic.github.io | mit |
Run it! | dat = {'N': coop.size,'coop':np.int32(coop),'fair':fair,'face':face+1,'sid':sid}
seed=np.random.randint(2**16)
fit=sm.sampling(data=dat,iter=6000,chains=4,thin=5,warmup=2000,n_jobs=4,seed=seed)
print pystan.misc._print_stanfit(fit,pars=['alpha','beta','gamm'],digits_summary=2)
w= fit.extract()
np.save('alpha',w['alpha'... | _ipynb/No Way Anova - Logistic Regression truimphs Anova.ipynb | simkovic/simkovic.github.io | mit |
Here are the results. | #w=fit.summary(pars=['alpha','beta','gamm'])
#np.save('logregSummary.fit',w)
#w=np.load('logregSummary.fit.npy')
#w=w.tolist()
a=np.load('m1alpha.npy')
b=np.load('m1beta.npy')
g=np.load('m1gamm.npy')[:,:,0]
d=np.load('m1gamm.npy')[:,:,1]
#D[D==2]=np.nan
for i in range(3):
x=np.linspace(1,7,101)
y=1/(1+exp(-np.m... | _ipynb/No Way Anova - Logistic Regression truimphs Anova.ipynb | simkovic/simkovic.github.io | mit |
The model fits quite well. We now look at the estimated values for different face conditions. | D=np.concatenate([a,b,g,1-d,1-g-d],1)
print D.shape
for n in range(D.shape[1]):
plt.subplot(2,3,[1,2,4,5,6][n/3])
k=n%3
plt.plot([k,k],[sap(D[:,n],2.5),sap(D[:,n],97.5)],color=clr)
plt.plot([k,k],[sap(D[:,n],25),sap(D[:,n],75)],color=clr,lw=3,solid_capstyle='round')
plt.plot([k],[np.median(D[:,n])],... | _ipynb/No Way Anova - Logistic Regression truimphs Anova.ipynb | simkovic/simkovic.github.io | mit |
The estimates show what we already more-or-less inferred from the graph. The 95% interval for $\alpha$ and $\beta$ coefficients are overlapping and we should consider model with the same horizontal shift and steepness for each of the face conditions. We see that the $\gamma$ and $\delta$ vary between the conditions. To... | import pystan
model = """
data {
int<lower=0> N;
int<lower=0,upper=1> coop[N]; // acceptance
int<lower=0,upper=8> fair[N]; // fairness
int<lower=1,upper=3> face[N]; // face expression
}
parameters {
real<lower=-20,upper=20> alpha;
real<lower=0,upper=10> beta;
real<lower=0,upper=1> gamm[3];
... | _ipynb/No Way Anova - Logistic Regression truimphs Anova.ipynb | simkovic/simkovic.github.io | mit |
Furthermore, we are concerned about the fact the the comparison across conditions is done within-subject and that the observed values are not independent. We extend the model by fitting separate logistic model to each subject. In particular, we estimate a separate $\gamma$ parameter for each subject i.e. $\gamma_{i,\ma... | import pystan
model = """
data {
int<lower=0> N;
int<lower=0> M; // number of subjects
int sid[N]; // subject identifier
int<lower=0,upper=1> coop[N]; // acceptance
int<lower=0,upper=8> fair[N]; // fairness
int<lower=1,upper=3> face[N]; // face expression
}
parameters {
real<lower=-20,... | _ipynb/No Way Anova - Logistic Regression truimphs Anova.ipynb | simkovic/simkovic.github.io | mit |
An M-estimator minimizes the function
$$Q(e_i, \rho) = \sum_i~\rho \left (\frac{e_i}{s}\right )$$
where $\rho$ is a symmetric function of the residuals
The effect of $\rho$ is to reduce the influence of outliers
$s$ is an estimate of scale.
The robust estimates $\hat{\beta}$ are computed by the iteratively re-wei... | norms = sm.robust.norms
def plot_weights(support, weights_func, xlabels, xticks):
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111)
ax.plot(support, weights_func(support))
ax.set_xticks(xticks)
ax.set_xticklabels(xlabels, fontsize=16)
ax.set_ylim(-0.1, 1.1)
return ax | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Andrew's Wave | help(norms.AndrewWave.weights)
a = 1.339
support = np.linspace(-np.pi * a, np.pi * a, 100)
andrew = norms.AndrewWave(a=a)
plot_weights(
support, andrew.weights, ["$-\pi*a$", "0", "$\pi*a$"], [-np.pi * a, 0, np.pi * a]
) | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Hampel's 17A | help(norms.Hampel.weights)
c = 8
support = np.linspace(-3 * c, 3 * c, 1000)
hampel = norms.Hampel(a=2.0, b=4.0, c=c)
plot_weights(support, hampel.weights, ["3*c", "0", "3*c"], [-3 * c, 0, 3 * c]) | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Huber's t | help(norms.HuberT.weights)
t = 1.345
support = np.linspace(-3 * t, 3 * t, 1000)
huber = norms.HuberT(t=t)
plot_weights(support, huber.weights, ["-3*t", "0", "3*t"], [-3 * t, 0, 3 * t]) | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Least Squares | help(norms.LeastSquares.weights)
support = np.linspace(-3, 3, 1000)
lst_sq = norms.LeastSquares()
plot_weights(support, lst_sq.weights, ["-3", "0", "3"], [-3, 0, 3]) | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Ramsay's Ea | help(norms.RamsayE.weights)
a = 0.3
support = np.linspace(-3 * a, 3 * a, 1000)
ramsay = norms.RamsayE(a=a)
plot_weights(support, ramsay.weights, ["-3*a", "0", "3*a"], [-3 * a, 0, 3 * a]) | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Trimmed Mean | help(norms.TrimmedMean.weights)
c = 2
support = np.linspace(-3 * c, 3 * c, 1000)
trimmed = norms.TrimmedMean(c=c)
plot_weights(support, trimmed.weights, ["-3*c", "0", "3*c"], [-3 * c, 0, 3 * c]) | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Tukey's Biweight | help(norms.TukeyBiweight.weights)
c = 4.685
support = np.linspace(-3 * c, 3 * c, 1000)
tukey = norms.TukeyBiweight(c=c)
plot_weights(support, tukey.weights, ["-3*c", "0", "3*c"], [-3 * c, 0, 3 * c]) | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Scale Estimators
Robust estimates of the location | x = np.array([1, 2, 3, 4, 500]) | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
The mean is not a robust estimator of location | x.mean() | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
The median, on the other hand, is a robust estimator with a breakdown point of 50% | np.median(x) | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Analogously for the scale
The standard deviation is not robust | x.std() | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Median Absolute Deviation
$$ median_i |X_i - median_j(X_j)|) $$
Standardized Median Absolute Deviation is a consistent estimator for $\hat{\sigma}$
$$\hat{\sigma}=K \cdot MAD$$
where $K$ depends on the distribution. For the normal distribution for example,
$$K = \Phi^{-1}(.75)$$ | stats.norm.ppf(0.75)
print(x)
sm.robust.scale.mad(x)
np.array([1, 2, 3, 4, 5.0]).std() | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
Another robust estimator of scale is the Interquartile Range (IQR)
$$\left(\hat{X}{0.75} - \hat{X}{0.25}\right),$$
where $\hat{X}_{p}$ is the sample p-th quantile and $K$ depends on the distribution.
The standardized IQR, given by $K \cdot \text{IQR}$ for
$$K = \frac{1}{\Phi^{-1}(.75) - \Phi^{-1}(.25)} \approx 0.74,$$... | sm.robust.scale.iqr(x) | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.github.io | bsd-3-clause |
The IQR is less robust than the MAD in the sense that it has a lower breakdown point: it can withstand 25\% outlying observations before being completely ruined, whereas the MAD can withstand 50\% outlying observations. However, the IQR is better suited for asymmetric distributions.
Yet another robust estimator of scal... | sm.robust.scale.qn_scale(x) | v0.13.1/examples/notebooks/generated/robust_models_1.ipynb | statsmodels/statsmodels.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.