markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Optimization | def ncc(fixed, transformed, nonzero=False):
if nonzero:
idx = np.where(transformed)
a = fixed[idx]
b = transformed[idx]
else:
a = fixed
b = transformed
return np.sum((a-a.mean())*(b-b.mean())/((a.size-1)*a.std()*b.std()))
def ssd(fixed, transformed):
return np.me... | _____no_output_____ | MIT | notebooks/coarse_registration.ipynb | chunglabmit/phathom |
Contour | import matplotlib.pyplot as plt
plt.hist(fixed_downsample.ravel(), bins=100)
plt.xlim([0, 1000])
plt.ylim([0, 100000])
plt.show()
plt.hist(moving_downsample.ravel(), bins=100)
plt.xlim([0, 1000])
plt.ylim([0, 100000])
plt.show()
threshold = 150
fixed_mask = fixed_downsample > threshold
moving_mask = moving_downsampl... | _____no_output_____ | MIT | notebooks/coarse_registration.ipynb | chunglabmit/phathom |
Convex hull | from skimage.morphology import convex_hull_image
import tqdm
fixed_hull = np.zeros_like(fixed_mask)
for i, f in enumerate(tqdm.tqdm(fixed_mask)):
if not np.all(f == 0):
fixed_hull[i] = convex_hull_image(f)
moving_hull = np.zeros_like(moving_mask)
for i, m in enumerate(tqdm.tqdm(moving_mask)):
... | basinhopping step 0: f 0.126898
basinhopping step 1: f 0.130302 trial_f 0.130302 accepted 1 lowest_f 0.126898
[ 0.02877251 -1.75668613 -1.94956175 0.32351345 0.0456788 0.01215395]
basinhopping step 2: f 0.131835 trial_f 0.131835 accepted 1 lowest_f 0.126898
[-0.39748378 -1.37928118 -1.67215733 0.32702666 0.0295... | MIT | notebooks/coarse_registration.ipynb | chunglabmit/phathom |
Sum of squared differences seems to provide slightly better registration than Normalized cross-correlation in the case of distance transformed convex hulls. This might be because NCC is indifferent to intensity difference and only considers correlations in the intensities, whereas SSD will penalize for any difference i... | registered = rigid_warp(moving_downsample,
t_star,
theta_star,
fixed_com,
moving_downsample.shape)
plot_both(fixed_downsample, registered, viewer) | _____no_output_____ | MIT | notebooks/coarse_registration.ipynb | chunglabmit/phathom |
We need to convert the downsampled transformation into an approprate transformation for the original resolution image. The rotation matrix is scale invariant, but we need to make sure the center of rotation and translation are upsampled by the same amount that we downsampled | print('Converged rigid transformation for downsampled image')
print('Rotation (deg):', theta_star*180/np.pi)
print('Center (px):', fixed_com)
print('Translation (px):', t_star)
fixed_fullres_path = os.path.join(working_dir, 'fixed/zarr_stack/8_8_8')
fixed_fullres_store = zarr.NestedDirectoryStore(fixed_fullres_path)
fi... | _____no_output_____ | MIT | notebooks/coarse_registration.ipynb | chunglabmit/phathom |
Save the transformation | from phathom.utils import pickle_save
transformation_dict = {'t': t,
'center': center,
'theta': theta}
pickle_save(os.path.join(working_dir, 'rigid_transformation.pkl'),
transformation_dict)
from phathom.utils import pickle_load
transformation_dict = pickle... | _____no_output_____ | MIT | notebooks/coarse_registration.ipynb | chunglabmit/phathom |
get data & transform 'name' column into 'id' column | address = './datasets/staandelamp_realistic_huge.json'
df_data = pd.read_json(address)
df_data = df_data.sort_values(by=['time'])
df_data['id'] = df_data['name']
df_data = df_data.drop(columns=['name'])
print(df_data.shape)
df_data.head() | (175000, 3)
| MIT | DBSCAN - class.ipynb | WyTho/MachineLearning |
Validate Dataframe | validator = DataFrameValidator()
dataframe_is_valid = validator.validate(df_data)
if dataframe_is_valid:
print('Valid!')
else:
print('WARNING! Dataframe validation failed!')
if dataframe_is_valid:
BDASCAN = BinaryDataAnalysis()
result = BDASCAN.analyze(df_data)
print(result[:5]) | [{'item_ids': ['Staande_Lamp_1', 'Staande_Lamp_3'], 'is_predicted_group_percentage': 95.0, 'is_relevant_group_percentage': 93.27}, {'item_ids': ['Staande_Lamp_3', 'Staande_Lamp_4'], 'is_predicted_group_percentage': 95.0, 'is_relevant_group_percentage': 91.43}, {'item_ids': ['Staande_Lamp_2', 'Staande_Lamp_3'], 'is_pred... | MIT | DBSCAN - class.ipynb | WyTho/MachineLearning |
Quantum tomography for n-qubitInit state: general GHZTarget state: 1 layerHere is the case for n-qubit with $n>1$.The state that need to reconstruct is GHZ state:$|G H Z\rangle=\frac{1}{\sqrt{2}}(|0 \ldots 0\rangle+|1 \ldots 1\rangle)=\frac{1}{\sqrt{2}}\left[\begin{array}{c}1 \\0 \\\ldots \\1\end{array}\right]$$|G H Z... | import qiskit
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.insert(1, '../')
import qtm.base, qtm.constant, qtm.ansatz
num_qubits = 3
thetas = np.zeros((2*num_qubits*3))
theta = np.random.uniform(0, 2*np.pi)
# Init quantum tomography n qubit
qc = qiskit.QuantumCircuit(num_qubits, num_qubits)
# ... | _____no_output_____ | MIT | codes/create_circuit/GHZinitstate.ipynb | vutuanhai237/QuantumTomographyProject |
sort order of columnscols = list(prob_matrix.columns)cols = [cols[-1]] + cols[:-1]prob_matrix = prob_matrix[cols] | prob_matrix
# Average number of steps during journey
# counting every stage (including ideling customers)
(df_journey.shape[0]-1)/df_journey['customer_unique'].nunique()
df_journey['customer_unique'].nunique()
len(set(df_journey['customer_unique'].values))
# counting every different stage
df.shape[0]/df_journey['custom... | _____no_output_____ | MIT | customer_journey_05.ipynb | quosi/doodl |
_______________________________ | class Customer(object):
def __init__(self, transition_prob):
"""
Initialize the MarkovChain instance.
Parameters
----------
transition_prob: dict
A dict object representing the transition
probabilities in Markov Chain.
Should be of the form... | _____no_output_____ | MIT | customer_journey_05.ipynb | quosi/doodl |
namespacedir(list) | markow = Customer(prob_dict)
markow.generate_states()
markov.transition_prob | _____no_output_____ | MIT | customer_journey_05.ipynb | quosi/doodl |
In this tutorial we are going to make a simple model of a human (or humaniod robot) that is capable of balancing on its own. We will make several assumptions:- The human's motion is limited to a 2D plane (i.e. leaning backwards and forwards).- We only have three degrees of freedom: rotation at the ankle, knee, and hip.... | from IPython.display import Image
Image('figures/human_balance_diagram.png') | _____no_output_____ | CC-BY-4.0 | notebooks/n02_problem_introduction.ipynb | pydy/pydy-tutorial-human-standing |
Ch `04`: Concept `03` Logistic regression in higher dimensions Set up the imports and hyper-parameters | %matplotlib inline
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
learning_rate = 0.1
training_epochs = 2000 | _____no_output_____ | MIT | ch04_classification/Concept03_logistic2d.ipynb | superizer/TensorFlow-Book |
Define positive and negative to classify 2D data points: | x1_label1 = np.random.normal(3, 1, 1000)
x2_label1 = np.random.normal(2, 1, 1000)
x1_label2 = np.random.normal(7, 1, 1000)
x2_label2 = np.random.normal(6, 1, 1000)
x1s = np.append(x1_label1, x1_label2)
x2s = np.append(x2_label1, x2_label2)
ys = np.asarray([0.] * len(x1_label1) + [1.] * len(x1_label2)) | _____no_output_____ | MIT | ch04_classification/Concept03_logistic2d.ipynb | superizer/TensorFlow-Book |
Define placeholders, variables, model, and the training op: | X1 = tf.placeholder(tf.float32, shape=(None,), name="x1")
X2 = tf.placeholder(tf.float32, shape=(None,), name="x2")
Y = tf.placeholder(tf.float32, shape=(None,), name="y")
w = tf.Variable([0., 0., 0.], name="w", trainable=True)
y_model = tf.sigmoid(-(w[2] * X2 + w[1] * X1 + w[0]))
cost = tf.reduce_mean(-tf.log(y_model... | _____no_output_____ | MIT | ch04_classification/Concept03_logistic2d.ipynb | superizer/TensorFlow-Book |
Train the model on the data in a session: | with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
prev_err = 0
for epoch in range(training_epochs):
err, _ = sess.run([cost, train_op], {X1: x1s, X2: x2s, Y: ys})
if epoch % 100 == 0:
print(epoch, err)
if abs(prev_err - err) < 0.0001:
brea... | 0 0.6931461
100 0.36477563
200 0.26468396
300 0.20803659
400 0.17227423
500 0.14782287
600 0.13008825
700 0.11664067
| MIT | ch04_classification/Concept03_logistic2d.ipynb | superizer/TensorFlow-Book |
Here's one hacky, but simple, way to figure out the decision boundary of the classifier: | x1_boundary, x2_boundary = [], []
with tf.Session() as sess:
for x1_test in np.linspace(0, 10, 20):
for x2_test in np.linspace(0, 10, 20):
z = sess.run(tf.sigmoid(-x2_test*w_val[2] - x1_test*w_val[1] - w_val[0]))
if abs(z - 0.5) < 0.05:
x1_boundary.append(x1_test)
... | _____no_output_____ | MIT | ch04_classification/Concept03_logistic2d.ipynb | superizer/TensorFlow-Book |
Ok, enough code. Let's see some a pretty plot: | plt.scatter(x1_boundary, x2_boundary, c='b', marker='o', s=20)
plt.scatter(x1_label1, x2_label1, c='r', marker='x', s=20)
plt.scatter(x1_label2, x2_label2, c='g', marker='1', s=20)
plt.show() | _____no_output_____ | MIT | ch04_classification/Concept03_logistic2d.ipynb | superizer/TensorFlow-Book |
Chapter 2 - Small Worlds vs Large Wolrds[Recorded Classes 2019 Chap2 by Richard McElreath](https://www.youtube.com/watch?v=XoVtOAN0htU&list=PLDcUM9US4XdNM4Edgs7weiyIguLSToZRI&index=2)The **Small World** represents the scientific model itself, and the **Large World**represents the broader context in which one deploys a... | import numpy as np
from scipy import stats
import random
import matplotlib.pyplot as plt
%matplotlib inline
np.set_printoptions(suppress=True) | _____no_output_____ | Apache-2.0 | Chapter2_Small_vs_Large_Worlds.ipynb | JoseJuan98/Statistical_Rethinking_Exercices |
*2.1.1- How to calculate this plausibilities of the example 2.1 in Python?* | Ways=np.array([0,3,8,9,0])
# Prior plausibility of p is 1 (it didn't change). So,
Ways/Ways.sum() | _____no_output_____ | Apache-2.0 | Chapter2_Small_vs_Large_Worlds.ipynb | JoseJuan98/Statistical_Rethinking_Exercices |
2.1 Building a modelBy working with probabilities instead of raw counts, Bayesian inference is made mucheasier, but it looks much harder.To get the logic moving, we need to make assumptions, and these assumptions constitutethe model. Designing a simple Bayesian model benefits from a design loop with three steps.1. Dat... | stats.binom.pmf(k=6, n=9, p=0.5) | _____no_output_____ | Apache-2.0 | Chapter2_Small_vs_Large_Worlds.ipynb | JoseJuan98/Statistical_Rethinking_Exercices |
That number is the relative number of ways to get 6 water (in our globe-tossing model, holding $p$ at 0.5 and $N = W + L$ at nine. With all the above work, we can now summarize out model. The observed variables $W$ and $L$ are given relative counts through the binomial distribution. So, we can write, as a shortcut: \be... | def grid_approximation(k, n, points, prior, showDesc=False):
#k=#success, n=#samples, points=#of point to aprroximate
#Define grid
grid = np.linspace(0, 1, points)
#Define prior. For uniform=1, bc we assume all values are equally probable when N=0
if type(prior) is int or type(prior) is float:
... | _____no_output_____ | Apache-2.0 | Chapter2_Small_vs_Large_Worlds.ipynb | JoseJuan98/Statistical_Rethinking_Exercices |
> After a certain amount of points the difference between approximation is minimal. More points means more precision, but at certain amount of points there won’t be much change in inference, in this case after the first 100. Example 2.5Let's try the prior where we assume a 0% chance of the true proportion of water bei... | points = 100
k, n = 6, 9
prior = (np.linspace(0, 1, points) >= .5).astype(int)
plot_likelihood(k, n, points, 'Proportion of Earth is Water','Posterior Probability', prior, showPrevious=True) | _____no_output_____ | Apache-2.0 | Chapter2_Small_vs_Large_Worlds.ipynb | JoseJuan98/Statistical_Rethinking_Exercices |
Self-Driving Car Engineer Nanodegree Deep Learning Project: Build a Traffic Sign Recognition ClassifierIn this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the noteb... | # Load pickled data
import pickle
# TODO: Fill this in based on where you saved the training and testing data
training_file = './traffic-signs-data/train.p'
validation_file = './traffic-signs-data/valid.p'
testing_file = './traffic-signs-data/test.p'
with open(training_file, mode='rb') as f:
train = pickle.... | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
--- Step 1: Dataset Summary & ExplorationThe pickled data is a dictionary with 4 key/value pairs:- `'features'` is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).- `'labels'` is a 1D array containing the label/class id of the traffic sign. The file `signnames.cs... | ### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = X_train.shape[0] # shape is a tuple: (num_samples, width, height, channel)
# TODO: Number of validation examples
n_validation = X_valid.... | Number of training examples = 34799
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43
| MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
Include an exploratory visualization of the dataset Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc. The [Matplotlib](http://matplotlib.org/) [examples](http://matplotlib.org/examples/index... | ### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
import numpy as np
import random
# Visualizations will be shown in the notebook.
%matplotlib inline
ROW = 4
COL = 6
def plot_data(data, label, channel=None, row=ROW, col=COL):
fig... | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
---- Step 2: Design and Test a Model ArchitectureDesign and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the [German Traffic Sign Dataset](http://benchmark.ini.rub.de/?section=gtsrb&subsection=dataset).The LeNet-5 implementation shown in the [classroom](https://cl... | ### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
# shuffle dataset
def unison_shuffle(x, y, seed=101):
"""
In-place unison shuffling
"""
rand_state = np.rando... | Training data shape before preprocessing: (34799, 32, 32, 3)
Training data mean before preprocessing: 82.677589037
Training data shape after preprocessing: (34799, 32, 32, 1)
Training data mean after preprocessing: -0.354081335648
| MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
Labeling | import tensorflow as tf
import csv
NUM_CHANNEL = 1
with open( './signnames.csv', 'rt') as f:
reader = csv.reader(f)
label_name = list(reader)
x = tf.placeholder(tf.float32, (None, 32, 32, NUM_CHANNEL))
y = tf.placeholder(tf.int32, (None))
keep_prob = tf.placeholder(tf.float32)
one_hot_y = tf.one_hot(y, n_clas... | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
Model Architecture | from tensorflow.contrib.layers import flatten
def LeNet(x, mu=0, sigma= 0.1):
# Layer 1: Convolutional. Input = 32x32x3. Output = 28x28x6.
conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, NUM_CHANNEL, 6), mean = mu, stddev = sigma))
conv1_b = tf.Variable(tf.zeros(6))
conv1 = tf.nn.conv2d(x, ... | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
Train, Validate and Test the Model A validation set can be used to assess how well the model is performing. A low accuracy on the training and validationsets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting. Setting up Pipeline | LR = 0.001
EPOCHS = 50
BATCH_SIZE = 128
KEEP_PROB = 0.5
# Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
MU = 0
SIGMA = 0.1
# Saving output graphs in local directory
GRAPH_FILENAME = './img/curr_training_curve.png'
logits = LeNet(x, MU, SIGMA)
cross_entrop... | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
Validating | 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 i... | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
Training | class Plot(object):
def __init__(self):
self.train_accuracy_over_epoch = []
self.valid_accuracy_over_epoch = []
def plot_graph(self):
assert len(self.train_accuracy_over_epoch) == len(self.valid_accuracy_over_epoch)
x = range(len(self.valid_accuracy_over_epoch))
... | Training...
EPOCH 0 : Training Accuray 25.3%, Validation Accuracy 56.8%
EPOCH 1 : Training Accuray 58.7%, Validation Accuracy 78.5%
EPOCH 2 : Training Accuray 72.5%, Validation Accuracy 84.8%
EPOCH 3 : Training Accuray 78.7%, Validation Accuracy 87.8%
EPOCH 4 : Training Accuray 82.1%, Validation Accuracy 89.6%
EPOCH 5... | MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
Log:1. 5/18/2018 - Training accuracy 99.4%, Validation Accuracy 92.3% - preprocessing: simple normalization: (pixel - 128)/128 - lr: 0.001, batch: 128, epoch: 50, mu: 0, sigma: 0.1 - Seems to be overfitting2. 5/18/2018 - Training accuracy 89.9%, Validation Accuracy 91.1% - added drop out at the fully conne... | with tf.Session() as sess:
saver = tf.train.import_meta_graph('./lenet.meta')
saver.restore(sess, tf.train.latest_checkpoint('.'))
test_accuracy = evaluate(X_test, y_test)
print("Test Set Accuracy {:.1f}%".format(100*test_accuracy)) | Test Set Accuracy 94.2%
| MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
Test ResultThe accuracy of the model on the test set is **94.2%**. Comparing to the training accuracy of 97.6% and validation accuracy of 96.9%, the model seems to be overfitting. This can be due to the fact that the data set has unequal distribution across all 43 traffic signs. We can improve by generating more image... | ### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import matplotlib.image as mpimg
import cv2
downloaded_img_names = ['30kph','children-crossing','keep-right','road-work','stop']
X_download = []
for name in downloaded_img_names:
filepath = './downloaded_img/' + name + '.jpg... | _____no_output_____ | MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
Predict the Sign Type for Each Image | ### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
X_download = preprocess(np.array(X_download))
y_download = np.array([1, 28, 38, 25, ... | Image 1 - correct label: ['1', 'Speed limit (30km/h)']
100.00% Speed limit (30km/h)
0.00% Speed limit (20km/h)
0.00% Speed limit (70km/h)
0.00% Stop
0.00% End of all speed and passing limits
Image 2 - correct label: ['28', 'Children crossing']
83.90% Dangerous curve to the right
... | MIT | Traffic_Sign_Classifier.ipynb | JohnGee96/CarND-Traffic-Sign-Classifier |
Example 1: How to Generate Synthetic Data (MarginalSynthesizer)In this notebook we show you how to create a simple synthetic dataset. Environment Library Imports | import numpy as np
import pandas as pd
from pathlib import Path
import os
import sys | _____no_output_____ | MIT | examples/tutorials/example 1 - how to generate synthetic data.ipynb | bcebere/synthetic_data_generation |
Jupyter-specific Imports and Settings | # set printing options
np.set_printoptions(threshold=sys.maxsize)
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
pd.set_option('display.expand_frame_repr', False)
# Display all cell outputs
from IPython.core.interactiveshell import InteractiveShell... | _____no_output_____ | MIT | examples/tutorials/example 1 - how to generate synthetic data.ipynb | bcebere/synthetic_data_generation |
Import SynthesizerFor this example we use the MarginalSynthesizer algorithm. As the name suggests, this algorithm generates data via the marginal distributions of each column in the input dataset. In other words, the output synthetic data will have similar counts for each column but the statistical patterns between co... | from synthesis.synthesizers import MarginalSynthesizer | _____no_output_____ | MIT | examples/tutorials/example 1 - how to generate synthetic data.ipynb | bcebere/synthetic_data_generation |
Synthetic Data GenerationLet's load a dataset to see how the generation process works.In this case, we will use the adult dataset - source: https://archive.ics.uci.edu/ml/datasets/adult | df_original = pd.read_csv('../data/original/adult.csv')
df_original.head() | _____no_output_____ | MIT | examples/tutorials/example 1 - how to generate synthetic data.ipynb | bcebere/synthetic_data_generation |
We will now import our synthesizer and fit it on the input data. Additionally we can specify the 'epsilon' value, which according to the definition of differential privacy is used to quantify the privacy risk posed by releasing statistics computed on sensitive data. More on that here: https://www.cis.upenn.edu/~aaroth/... | epsilon = 1 # set to float(np.inf) if you'd like to compute without differential privacy.
synthesizer = MarginalSynthesizer(epsilon=epsilon)
synthesizer.fit(df_original) | Marginal fitted: age
Marginal fitted: workclass
Marginal fitted: fnlwgt
Marginal fitted: education
Marginal fitted: education-num
Marginal fitted: marital-status
Marginal fitted: occupation
Marginal fitted: relationship
Marginal fitted: race
Marginal fitted: sex
Marginal fitted: capital-gain
Marginal fitted: capital-lo... | MIT | examples/tutorials/example 1 - how to generate synthetic data.ipynb | bcebere/synthetic_data_generation |
After our synthesizer has fitted the structure of the original data source, we can now use it to generate a new dataset. | # we can specify the number of records by sample(n_records=...),
# default it generates the same number of records as the input data
df_synthetic = synthesizer.sample() | Column sampled: age
Column sampled: workclass
Column sampled: fnlwgt
Column sampled: education
Column sampled: education-num
Column sampled: marital-status
Column sampled: occupation
Column sampled: relationship
Column sampled: race
Column sampled: sex
Column sampled: capital-gain
Column sampled: capital-loss
Column sa... | MIT | examples/tutorials/example 1 - how to generate synthetic data.ipynb | bcebere/synthetic_data_generation |
We now obtained a new dataset which looks very similar to the original one. | df_synthetic.head() | _____no_output_____ | MIT | examples/tutorials/example 1 - how to generate synthetic data.ipynb | bcebere/synthetic_data_generation |
EvaluationWe can see that the synthetic data has a similar structure the original. We can also evaluate whether it has retained the statistical distributions of the original data. We use the SyntheticDataEvaluator class to compare the synthetic data to the original by applying various metrics.Note: for more elaborate ... | from synthesis.evaluation import SyntheticDataEvaluator
evaluator = SyntheticDataEvaluator()
evaluator.fit(df_original, df_synthetic)
evaluator.score()
evaluator.plot() | _____no_output_____ | MIT | examples/tutorials/example 1 - how to generate synthetic data.ipynb | bcebere/synthetic_data_generation |
Mapping QTL in BXD mice using R/qtl2[Karl Broman](https://kbroman.org)[](https://orcid.org/0000-0002-4914-6671),[Department of Biostatistics & Medical Informatics](https://www.biostat.wisc.edu), [University of Wisconsin–Madison](https://www.wisc.edu)Our aim in this tutorial is to demonstrate how to map quantitat... | library(GNapi) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
The [R/GNapi](https://github.com/kbroman/GNapi) has a variety of functions. For an overview, see [its vignette](http://kbroman.org/GNapi/GNapi.html). Here we will just do one thing: use the function `get_pheno()` to grab BXD phenotype data. You provide a data set and a phenotype. Phenotype 10038 concerns "habituation",... | phe <- get_pheno("BXD", "10038")
head(phe) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
We will use just the column "value", but we need to include the strain names so that R/qtl2 can line up these phenotypes with the genotypes. | pheno <- setNames(phe$value, phe$sample_name)
head(pheno) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
Acquiring genotype data with R/qtl2We now want to get genotype data for the BXD panel. We first need to install the [R/qtl2](https://kbroman.org/qtl2) package. As with R/GNapi, it is not available on CRAN, but rather is distributed via a private repository.```rinstall.packages("qtl2", repos="http://rqtl.org/qtl2cran")... | library(qtl2) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
R/qtl2 uses a special file format for QTL data ([described here](https://kbroman.org/qtl2/assets/vignettes/input_files.html)). There are a variety of sample datasets [on Github](https://github.com/rqtl/qtl2data), including genotypes for the [mouse BXD lines](https://github.com/rqtl/qtl2data/tree/master/BXD), taken from... | bxd_file <- "https://raw.githubusercontent.com/rqtl/qtl2data/master/BXD/bxd.zip"
bxd <- read_cross2(bxd_file) | Warning message in recode_geno(sheet, genotypes):
“117497 genotypes treated as missing: "H"” | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
We get a warning message about heterozygous genotypes being omitted. A number of the newer BXD lines have considerable heterozygosity. But these lines weren't among those phenotyped in the data we downloaded above, and so we don't need to worry about it here.The data are read into the object `bxd`, which has class `"cr... | print( summary(bxd) ) | Object of class cross2 (crosstype "risib")
Total individuals 198
No. genotyped individuals 198
No. phenotyped individuals 198
No. with both geno & pheno 198
No. phenotypes 5806
No. covariates 0
No. phenotype covariates 1
No. chromosomes 20
To... | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
QTL mapping in R/qtl2The first step in QTL analysis is to calculate genotype probabilities at putative QTL positions across the genome, conditional on the observed marker data. This allows us that consider positions between the genotyped markers and to allow for the presence of genotyping errors.First, we need to defi... | gmap <- insert_pseudomarkers(bxd$gmap, step=0.2, stepwidth="max") | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
We will be interested in results with respect to the physical map (in Mbp), and so we need to create a corresponding map that includes the pseudomarker positions. We do this with the function `interp_map()`, which uses linear interpolation to get estimated positions for the inserted pseudomarkers. | pmap <- interp_map(gmap, bxd$gmap, bxd$pmap) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
We can now proceed with calculating genotype probabilities for all BXD strains at all markers and pseudomarkers, conditional on the observed marker genotypes and assuming a 0.2% genotyping error rate. We use the [Carter-Falconer](https://doi.org/10.1007/BF02996226) map function to convert between cM and recombination f... | pr <- calc_genoprob(bxd, gmap, error_prob=0.002, map_function="c-f") | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
In the QTL analysis, we will fit a linear mixed model to account for polygenic background effects. We will use the "leave one chromosome out" (LOCO) method for this. When we scan a chromosome for a QTL, we include a polygenic term with a kinship matrix derived from all other chromosomes. We first need to calculate this... | k <- calc_kinship(pr, "loco") | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
Now, finally, we're ready to perform the genome scan, which we do with the function `scan1()`. It takes the genotype probabilities and a set of phenotypes (here, just one phenotype). If kinship matrices are provided (here, as `k`), the scan is performed using a linear mixed model. To make the calculations faster, the r... | out <- scan1(pr, pheno, k) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
The output of `scan1()` is a matrix of LOD scores; the rows are marker/pseudomarker positions and the columns are phenotypes. We can plot the results using `plot.scan1()`, and we can just use `plot()` because it uses the class of its input to determine what plot to make.Here I'm using the package [repr](https://cran.r-... | library(repr)
options(repr.plot.height=4, repr.plot.width=8)
par(mar=c(5.1, 4.1, 0.6, 0.6))
plot(out, pmap) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
There's a clear QTL on chromosome 8. We can make a plot of just that chromosome with the argument `chr=15`. | par(mar=c(5.1, 4.1, 0.6, 0.6))
plot(out, pmap, chr=15) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
Let's create a plot of the phenotype vs the genotype at the inferred QTL. We first need to identify the QTL location, which we can do using `max()`. We then use `maxmarg()` to get inferred genotypes at the inferred QTL. | mx <- max(out, pmap)
g_imp <- maxmarg(pr, pmap, chr=mx$chr, pos=mx$pos, return_char=TRUE) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
We can use `plot_pxg()` to plot the phenotype as a function of QTL genotype. We use `swap_axes=TRUE` to have the phenotype on the x-axis and the genotype on the y-axis, rather than the other way around. Here we see that the BB and DD genotypes are completely separated, phenotypically. | par(mar=c(5.1, 4.1, 0.6, 0.6))
plot_pxg(g_imp, pheno, swap_axes=TRUE, xlab="Habituation phenotype") | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
Browsing genome scan results with the Genetics Genome BrowserThe [Genetics Genome Browser](https://github.com/chfi/purescript-genome-browser) is a fast, lightweight, [purescript]-based genome browser developed for browsing GWAS or QTL analysis results. We'll use the R package [R/qtl2browse](https://github.com/rqtl/qtl... | library(qtl2browse)
browse(out, pmap) | _____no_output_____ | CC0-1.0 | CTC2019_tutorial.ipynb | kbroman/Teaching_CTC2019tutorial |
Kovariance Vzorec Pearsonova korelačního koeficientuPrůměrná hodnota vektoru:$$E(X) = \frac{\sum_{i=1}^{n} x_i}{n}$$$$\rho_{X,Y}=\frac{cov(X,Y)}{\sigma_X\sigma_Y}$$Kovarianci převedeme na:$$\rho_{X,Y} = \frac{E((X-\mu_X)(Y-\mu_Y))}{\sigma_X\sigma_Y}$$Protože $\mu_X=E(X)$ tak:$$\sigma^2_X = E(X^2) - E^2(X)$$Po úpravě:... | def E(a):
s = 0
for i in a:
s += i
return s / len(a)
assert E([1, 2]) == 1.5
def mul(a, b):
assert len(a) == len(b)
r = []
for i in range(len(a)):
r.append(a[i] * b[i])
return r
assert mul([2,2], [2,3]) == [4,6]
def reduce(a, b):
assert len(a) == len(b)
r = []
... | _____no_output_____ | MIT | notebooks/Untitled.ipynb | Reusek/Fast-Correlation |
Simplifying CodebasesParam's just a Python library, and so anything you can do with Param you can do "manually". So, why use Param?The most immediate benefit to using Param is that it allows you to greatly simplify your codebases, making them much more clear, readable, and maintainable, while simultaneously providing ... | class OrdinaryClass(object):
def __init__(self, a=2, b=3, title="sum"):
self.a = a
self.b = b
self.title = title
def __call__(self):
return self.title + ": " + str(self.a + self.b) | _____no_output_____ | BSD-3-Clause | examples/user_guide/Simplifying_Codebases.ipynb | ektar/param |
As this is just standard Python, we can of course instantiate this class, modify its variables, and call it: | o1 = OrdinaryClass(b=4, title="Sum")
o1.a=4
o1() | _____no_output_____ | BSD-3-Clause | examples/user_guide/Simplifying_Codebases.ipynb | ektar/param |
The same code written using Param would look like: | import param
class ParamClass(param.Parameterized):
a = param.Integer(2, bounds=(0,1000), doc="First addend")
b = param.Integer(3, bounds=(0,1000), doc="Second addend")
title = param.String(default="sum", doc="Title for the result")
def __call__(self):
return self.title + ": " + st... | _____no_output_____ | BSD-3-Clause | examples/user_guide/Simplifying_Codebases.ipynb | ektar/param |
As you can see, the Parameters here are used precisely like normal attributes once they are defined, so the code for `__call__` and for invoking the constructor are the same in both cases. It's thus generally quite straightforward to migrate an existing class into Param. So, why do that?Well, with fewer lines of code t... | with param.exceptions_summarized():
o3 = ParamClass()
o3.b = -5 | _____no_output_____ | BSD-3-Clause | examples/user_guide/Simplifying_Codebases.ipynb | ektar/param |
Of course, you could always add more code to an ordinary Python class to check for errors like that, but it quickly gets unwieldy: | class OrdinaryClass2(object):
def __init__(self, a=2, b=3, title="sum"):
if type(a) is not int:
raise ValueError("'a' must be an integer")
if type(b) is not int:
raise ValueError("'b' must be an integer")
if a<0:
raise ValueError("'a' must be at least `0`"... | _____no_output_____ | BSD-3-Clause | examples/user_guide/Simplifying_Codebases.ipynb | ektar/param |
Unfortunately, catching errors in the constructor like that won't help if someone modifies the attribute directly, which won't be detected as an error: | o4 = OrdinaryClass2()
o4.a = "four" | _____no_output_____ | BSD-3-Clause | examples/user_guide/Simplifying_Codebases.ipynb | ektar/param |
Python will happily accept this incorrect value and will continue processing. It may only be much later, in a very different part of your code, that you see a mysterious error message that's then very difficult to relate back to the actual problem you need to fix: | with param.exceptions_summarized():
o4() | _____no_output_____ | BSD-3-Clause | examples/user_guide/Simplifying_Codebases.ipynb | ektar/param |
Here there's no problem with the code in the cell above; `o4()` is fully valid Python; the real problem is in the preceding cell, which could have been in a completely different file or library. The error message is also obscure and confusing at this level, because the user of `o4` may have no idea why strings and inte... | class OrdinaryClass3(object):
def __init__(self, a=2, b=3, title="sum"):
self.a = a
self.b = b
self.title = title
def __call__(self):
if type(self.a) is not int:
raise ValueError("'a' must be an integer")
if type(self.b) is not int:
ra... | _____no_output_____ | BSD-3-Clause | examples/user_guide/Simplifying_Codebases.ipynb | ektar/param |
But you'd now have to check for errors in _every_ _single_ _method_ that might use those parameters. Worse, you still only detect the problem very late, far from where it was first introduced. Any distance between the error and the error report makes it much more difficult to address, as the user then has to track down... | class OrdinaryClass4(object):
def __init__(self, a=2, b=3, title="sum"):
self.a = a
self.b = b
self.title = title
@property
def a(self): return self.__a
@a.setter
def a(self, a):
if type(a) is not int:
raise ValueError("'a' must be an integer")
... | _____no_output_____ | BSD-3-Clause | examples/user_guide/Simplifying_Codebases.ipynb | ektar/param |
TokenizationBefore we can classify any posts, we'll need to clean and tokenize the text data. Use what you remember from the last lesson on NLP to implement the function `tokenize`. This function should perform the following steps on the string, `text`, using nltk:1. Identify any urls in `text`, and replace each one w... | # download necessary NLTK data
import nltk
nltk.download(['punkt', 'wordnet'])
# import statements
import pandas as pd
import re
from nltk.tokenize import word_tokenize
from nltk.stem.wordnet import WordNetLemmatizer
def load_data():
df = pd.read_csv('corporate_messaging.csv', encoding='latin-1')
df = df[(df["... | _____no_output_____ | MIT | lessons/ML Pipelines/clean_tokenize.ipynb | ZacksAmber/Udacity-Data-Scientist |
For step 1, the regular expression to detect a url is given below | url_regex = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
def tokenize(text):
# replace each url in text string with placeholder
url_pattern = re.compile(url_regex)
text = url_pattern.sub('urlplaceholder', text)
# tokenize text
tokens = word_tokenize(text)
... | Barclays CEO stresses the importance of regulatory and cultural reform in financial services at Brussels conference http://t.co/Ge9Lp7hpyG
['barclays', 'ceo', 'stress', 'the', 'importance', 'of', 'regulatory', 'and', 'cultural', 'reform', 'in', 'financial', 'service', 'at', 'brussels', 'conference', 'urlplaceholder'] ... | MIT | lessons/ML Pipelines/clean_tokenize.ipynb | ZacksAmber/Udacity-Data-Scientist |
Deep Learning Models -- A collection of various deep learning architectures, models, and tips for TensorFlow and PyTorch in Jupyter Notebooks.- Author: Sebastian Raschka- GitHub Repository: https://github.com/rasbt/deeplearning-models | !pip install -q IPython
!pip install -q ipykernel
!pip install -q watermark
!pip install -q matplotlib
!pip install -q sklearn
!pip install -q pandas
!pip install -q pydot
!pip install -q hiddenlayer
!pip install -q graphviz
%load_ext watermark
%watermark -a 'Sebastian Raschka' -v -p torch | Sebastian Raschka
CPython 3.6.9
IPython 5.5.0
torch 1.5.1+cu101
| MIT | pytorch_ipynb/cnn/cnn-vgg19.ipynb | DeepSE/deeplearning-models |
- Runs on CPU (not recommended here) or GPU (if available) Model Zoo -- Convolutional Neural Network (VGG19 Architecture) Implementation of the VGG-19 architecture on Cifar10. Reference for VGG-19: - Simonyan, K., & Zisserman, A. (2014). Very deep convolutional networks for large-scale image recognition. arXiv pre... | import numpy as np
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import datasets
from torchvision import transforms
from torch.utils.data import DataLoader | _____no_output_____ | MIT | pytorch_ipynb/cnn/cnn-vgg19.ipynb | DeepSE/deeplearning-models |
Settings and Dataset | ##########################
### SETTINGS
##########################
# Device
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print('Device:', DEVICE)
# Hyperparameters
random_seed = 1
learning_rate = 0.001
num_epochs = 20
batch_size = 128
# Architecture
num_features = 784
num_classes = 10
####... | Device: cuda
Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to data/cifar-10-python.tar.gz
| MIT | pytorch_ipynb/cnn/cnn-vgg19.ipynb | DeepSE/deeplearning-models |
Model | ##########################
### MODEL
##########################
class VGG16(torch.nn.Module):
def __init__(self, num_features, num_classes):
super(VGG16, self).__init__()
# calculate same padding:
# (w - k + 2*p)/s + 1 = o
# => p = (s(o-1) - w + k)/2
self... | _____no_output_____ | MIT | pytorch_ipynb/cnn/cnn-vgg19.ipynb | DeepSE/deeplearning-models |
Training | def compute_accuracy(model, data_loader):
model.eval()
correct_pred, num_examples = 0, 0
for i, (features, targets) in enumerate(data_loader):
features = features.to(DEVICE)
targets = targets.to(DEVICE)
logits, probas = model(features)
_, predicted_labels = torc... | Epoch: 001/020 | Batch 0000/0391 | Cost: 1061.4154
Epoch: 001/020 | Batch 0050/0391 | Cost: 2.3029
Epoch: 001/020 | Batch 0100/0391 | Cost: 1.9784
Epoch: 001/020 | Batch 0150/0391 | Cost: 1.9533
Epoch: 001/020 | Batch 0200/0391 | Cost: 1.8397
Epoch: 001/020 | Batch 0250/0391 | Cost: 1.7760
Epoch: 001/020 | Batch 0300/0... | MIT | pytorch_ipynb/cnn/cnn-vgg19.ipynb | DeepSE/deeplearning-models |
Evaluation | with torch.set_grad_enabled(False): # save memory during inference
print('Test accuracy: %.2f%%' % (compute_accuracy(model, test_loader)))
%watermark -iv | numpy 1.18.5
torch 1.5.1+cu101
| MIT | pytorch_ipynb/cnn/cnn-vgg19.ipynb | DeepSE/deeplearning-models |
Changing the input current when solving PyBaMM modelsThis notebook shows you how to change the input current when solving PyBaMM models. It also explains how to load in current data from a file, and how to add a user-defined current function. For more examples of different drive cycles see [here](https://github.com/py... | %pip install pybamm -q # install PyBaMM if it is not installed
import pybamm
import numpy as np
import os
os.chdir(pybamm.__path__[0]+'/..')
# create the model
model = pybamm.lithium_ion.DFN()
# set the default model parameters
param = model.default_parameter_values
# change the current function to be an input pa... | Note: you may need to restart the kernel to use updated packages.
| BSD-3-Clause | examples/notebooks/change-input-current.ipynb | anandmy/PyBaMM |
We can set up a simulation in the usual way, making sure we pass in our updated parameters. We choose to solve with a 1.6A current. In order to do this we must pass a dictionary of inputs whose keys are the parameter names and values are the values we want to use for that call to solve | # set up simlation
simulation = pybamm.Simulation(model, parameter_values=param)
# solve the model at the given time points, passing the current as an input
t_eval = np.linspace(0, 600, 300)
simulation.solve(t_eval, inputs={"Current function [A]": 1.6})
# plot
simulation.plot() | _____no_output_____ | BSD-3-Clause | examples/notebooks/change-input-current.ipynb | anandmy/PyBaMM |
PyBaMM can also simulate rest behaviour by setting the current function to zero: | # solve the model at the given time points
simulation.solve(t_eval, inputs={"Current function [A]": 0})
# plot
simulation.plot() | _____no_output_____ | BSD-3-Clause | examples/notebooks/change-input-current.ipynb | anandmy/PyBaMM |
Loading in current data To run drive cycles from data we can create an interpolant and pass it as the current function. | import pandas as pd # needed to read the csv data file
model = pybamm.lithium_ion.DFN()
# import drive cycle from file
drive_cycle = pd.read_csv("pybamm/input/drive_cycles/US06.csv", comment="#", header=None).to_numpy()
# load parameter values
param = model.default_parameter_values
# create interpolant - must be... | _____no_output_____ | BSD-3-Clause | examples/notebooks/change-input-current.ipynb | anandmy/PyBaMM |
Note that when simulating drive cycles there is no need to pass a list of times at which to return the solution, the results are automatically returned at the time points in the data. If you would like the solution returned at times different to those in the data then you can pass an array of times `t_eval` to `solve` ... | # simulate US06 drive cycle (duration 600 seconds)
simulation.solve()
# plot
simulation.plot() | _____no_output_____ | BSD-3-Clause | examples/notebooks/change-input-current.ipynb | anandmy/PyBaMM |
Note that some solvers try to evaluate the model equations at a very large value of `t` during the first step. This may raise a warning if the time requested by the solver is outside of the range of the data provided. However, this does not affect the solve since this large timestep is rejected by the solver, and a sui... | # create user-defined function
def my_fun(A, omega):
def current(t):
return A * pybamm.sin(2 * np.pi * omega * t)
return current | _____no_output_____ | BSD-3-Clause | examples/notebooks/change-input-current.ipynb | anandmy/PyBaMM |
Note that the function returns a function which takes the input time.Then the model may be loaded and the "Current function" parameter updated to `my_fun` called with a specific value of `A` and `omega` | model = pybamm.lithium_ion.SPM()
# load default parameter values
param = model.default_parameter_values
# set user defined current function
A = model.param.I_typ
omega = 0.1
param["Current function [A]"] = my_fun(A,omega)
| _____no_output_____ | BSD-3-Clause | examples/notebooks/change-input-current.ipynb | anandmy/PyBaMM |
Note that when `my_fun` is evaluated with `A` and `omega`, this creates a new function `current(t)` which can then be used in the expression tree. The model may then be solved in the usual way | # set up simulation
simulation = pybamm.Simulation(model, parameter_values=param)
# Example: simulate for 30 seconds
simulation_time = 30 # end time in seconds
npts = int(50 * simulation_time * omega) # need enough timesteps to resolve output
t_eval = np.linspace(0, simulation_time, npts)
solution = simulation.solve... | _____no_output_____ | BSD-3-Clause | examples/notebooks/change-input-current.ipynb | anandmy/PyBaMM |
DiscretisationDiscretisation is the process of transforming continuous variables into discrete variables by creating a set of contiguous intervals that span the range of the variable's values. Discretisation is also called **binning**, where bin is an alternative name for interval. Discretisation helps handle outliers... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import KBinsDiscretizer
from feature_engine.discretisers import EqualFrequencyDiscretiser
# load the numerical variables of the Titanic Dataset
data = pd.read_csv('... | _____no_output_____ | BSD-3-Clause | Section-08-Discretisation/08.02-Equal-frequency-discretisation.ipynb | cym3509/FeatureEngineering |
The variables Age and Fare contain missing data, that I will fill by extracting a random sample of the variable. | def impute_na(data, variable):
# function to fill NA with a random sample
df = data.copy()
# random sampling
df[variable+'_random'] = df[variable]
# extract the random sample to fill the na
random_sample = X_train[variable].dropna().sample(
df[variable].isnull().sum(), random_state=0)... | _____no_output_____ | BSD-3-Clause | Section-08-Discretisation/08.02-Equal-frequency-discretisation.ipynb | cym3509/FeatureEngineering |
Equal frequency discretisation with pandas and NumPyThe interval limits are the quantile limits. We can find those out with pandas qcut. | # let's use pandas qcut (quantile cut) and I indicate that
# we want 10 bins.
# retbins = True indicates that I want to capture the limits
# of each interval (so I can then use them to cut the test set)
Age_disccretised, intervals = pd.qcut(
X_train['age'], 10, labels=None, retbins=True, precision=3, duplicates='... | _____no_output_____ | BSD-3-Clause | Section-08-Discretisation/08.02-Equal-frequency-discretisation.ipynb | cym3509/FeatureEngineering |
We can see in the above output how by discretising using quantiles, we placed each Age observation within one interval. For example, age 29 was placed in the 26-30 interval, whereas age 63 was placed into the 49-80 interval. Note how the interval widths are different.We can visualise the interval cut points below: | intervals | _____no_output_____ | BSD-3-Clause | Section-08-Discretisation/08.02-Equal-frequency-discretisation.ipynb | cym3509/FeatureEngineering |
And because we generated the bins using the quantile cut method, we should have roughly the same amount of observations per bin. See below. | # roughly the same number of passengers per interval
Age_disccretised.value_counts()
# we can also add labels instead of having the interval boundaries, to the bins, as follows:
labels = ['Q'+str(i) for i in range(1,11)]
labels
Age_disccretised, intervals = pd.qcut(X_train['age'], 10, labels=labels,
... | _____no_output_____ | BSD-3-Clause | Section-08-Discretisation/08.02-Equal-frequency-discretisation.ipynb | cym3509/FeatureEngineering |
We can see that the top intervals have less observations. This may happen with skewed distributions if we try to divide in a high number of intervals. To make the value spread more homogeneous, we should discretise in less intervals. Equal frequency discretisation with Feature-Engine | # Let's separate into train and test set
X_train, X_test, y_train, y_test = train_test_split(
data[['age', 'fare']],
data['survived'],
test_size=0.3,
random_state=0)
X_train.shape, X_test.shape
# replace NA in both train and test sets
X_train['age'] = impute_na(data, 'age')
X_test['age'] = impute_na... | _____no_output_____ | BSD-3-Clause | Section-08-Discretisation/08.02-Equal-frequency-discretisation.ipynb | cym3509/FeatureEngineering |
Note how equal frequency discretisation obtains a better value spread across the different intervals. Equal frequency discretisation with Scikit-learn | # Let's separate into train and test set
X_train, X_test, y_train, y_test = train_test_split(
data[['age', 'fare']],
data['survived'],
test_size=0.3,
random_state=0)
X_train.shape, X_test.shape
# replace NA in both train and test sets
X_train['age'] = impute_na(data, 'age')
X_test['age'] = impute_na... | _____no_output_____ | BSD-3-Clause | Section-08-Discretisation/08.02-Equal-frequency-discretisation.ipynb | cym3509/FeatureEngineering |
This baseline has reached Top %11 with rank of 457/4540 Teams at Private Leader Board (missed Bronze with only 2 places) | import numpy as np
import pandas as pd
import sys
import gc
from scipy.signal import hilbert
from scipy.signal import hann
from scipy.signal import convolve
pd.options.display.precision = 15
train_set = pd.read_csv('../input/train.csv', dtype={'acoustic_data': np.int16, 'time_to_failure': np.float32})
segments = int... | _____no_output_____ | MIT | Simple baseline with XGBoost.ipynb | inzva/earthquake-prediction-kaggle |
Exercise 4 - Optimizing Model TrainingIn [the previous exercise](./03%20-%20Compute%20Contexts.ipynb), you created cloud-based compute and used it when running a model training experiment. The benefit of cloud compute is that it offers a cost-effective way to scale out your experiment workflow and try different algori... | !pip install --upgrade azureml-sdk[notebooks,automl,explain]
import azureml.core
print("Ready to use Azure ML", azureml.core.VERSION) | _____no_output_____ | MIT | examples/AzureML-Primers/04 - Optimizing Model Training.ipynb | kunZooberg/MLOps |
Now you're ready to connect to your workspace. When you created it in the previous exercise, you saved its configuration; so now you can simply load the workspace from its configuration file.> **Note**: If the authenticated session with your Azure subscription has expired since you completed the previous exercise, you'... | from azureml.core import Workspace
# Load the workspace from the saved config file
ws = Workspace.from_config()
print('Ready to work with', ws.name) | _____no_output_____ | MIT | examples/AzureML-Primers/04 - Optimizing Model Training.ipynb | kunZooberg/MLOps |
Now let's get the Azure ML compute resource you created previously (or recreate it if you deleted it!) | from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
# Choose a name for your CPU cluster
cpu_cluster_name = "cpu-cluster"
# Verify that cluster does not exist already
try:
cpu_cluster = ComputeTarget(workspace=ws, name=cpu_cluster_name)
pri... | _____no_output_____ | MIT | examples/AzureML-Primers/04 - Optimizing Model Training.ipynb | kunZooberg/MLOps |
Task 2: Use *Hyperdrive* to Determine Optimal Parameter ValuesThe remote compute you created is a four-node cluster, and you can take advantage of this to execute multiple experiment runs in parallel. One key reason to do this is to try training a model with a range of different hyperparameter values.Azure ML includes... | import os
from azureml.core import Experiment
# Create an experiment
experiment_name = 'diabetes_training'
experiment = Experiment(workspace = ws, name = experiment_name)
# Create a folder for the experiment files
experiment_folder = './' + experiment_name
os.makedirs(experiment_folder, exist_ok=True)
print("Experim... | _____no_output_____ | MIT | examples/AzureML-Primers/04 - Optimizing Model Training.ipynb | kunZooberg/MLOps |
Now we'll create the Python script our experiment will run in order to train a model. | %%writefile $experiment_folder/diabetes_training.py
# Import libraries
import argparse
import joblib
from azureml.core import Workspace, Dataset, Experiment, Run
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import L... | _____no_output_____ | MIT | examples/AzureML-Primers/04 - Optimizing Model Training.ipynb | kunZooberg/MLOps |
Now, we'll use the *Hyperdrive* feature of Azure ML to run multiple experiments in parallel, using different values for the **regularization** parameter to find the optimal value for our data. | from azureml.train.hyperdrive import GridParameterSampling, BanditPolicy, HyperDriveConfig, PrimaryMetricGoal
from azureml.train.hyperdrive import choice
from azureml.widgets import RunDetails
from azureml.train.sklearn import SKLearn
# Sample a range of parameter values
params = GridParameterSampling(
{
#... | _____no_output_____ | MIT | examples/AzureML-Primers/04 - Optimizing Model Training.ipynb | kunZooberg/MLOps |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.