markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
One-hot encode Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 t...
def one_hot_encode(x): """ One hot encode a list of sample labels. Return a one-hot encoded vector for each label. : x: List of sample Labels : return: Numpy array of one-hot encoded labels """ # TODO: Implement Function return None """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS...
image-classification/dlnd_image_classification.ipynb
khalido/deep-learning
mit
Build the network For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittest...
import tensorflow as tf def neural_net_image_input(image_shape): """ Return a Tensor for a batch of image input : image_shape: Shape of the images : return: Tensor for image input. """ # TODO: Implement Function return None def neural_net_label_input(n_classes): """ Return a Tenso...
image-classification/dlnd_image_classification.ipynb
khalido/deep-learning
mit
Convolution and Max Pooling Layer Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling: * Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor. * Apply a convolution to x_tensor...
def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides): """ Apply convolution then max pooling to x_tensor :param x_tensor: TensorFlow Tensor :param conv_num_outputs: Number of outputs for the convolutional layer :param conv_ksize: kernal size 2-D Tuple fo...
image-classification/dlnd_image_classification.ipynb
khalido/deep-learning
mit
Flatten Layer Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a ch...
def flatten(x_tensor): """ Flatten x_tensor to (Batch Size, Flattened Image Size) : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions. : return: A tensor of size (Batch Size, Flattened Image Size). """ # TODO: Implement Function return None """ DON'T MODIFY A...
image-classification/dlnd_image_classification.ipynb
khalido/deep-learning
mit
Fully-Connected Layer Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packag...
def fully_conn(x_tensor, num_outputs): """ Apply a fully connected layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_out...
image-classification/dlnd_image_classification.ipynb
khalido/deep-learning
mit
Output Layer Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. Note: Act...
def output(x_tensor, num_outputs): """ Apply a output layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """...
image-classification/dlnd_image_classification.ipynb
khalido/deep-learning
mit
Create Convolutional Model Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model: Apply 1, 2, or 3 Convolution and Max Pool layers Apply a Flatten Layer Apply 1, 2, or 3 Full...
def conv_net(x, keep_prob): """ Create a convolutional neural network model : x: Placeholder tensor that holds image data. : keep_prob: Placeholder tensor that hold dropout keep probability. : return: Tensor that represents logits """ # TODO: Apply 1, 2, or 3 Convolution and Max Pool layers ...
image-classification/dlnd_image_classification.ipynb
khalido/deep-learning
mit
Train the Neural Network Single Optimization Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following: * x for image input * y for labels * keep_prob for keep probability for dropout This function will be cal...
def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch): """ Optimize the session on a batch of images and labels : session: Current TensorFlow session : optimizer: TensorFlow optimizer function : keep_probability: keep probability : feature_batch: Batch of Num...
image-classification/dlnd_image_classification.ipynb
khalido/deep-learning
mit
Show Stats Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy.
def print_stats(session, feature_batch, label_batch, cost, accuracy): """ Print information about loss and validation accuracy : session: Current TensorFlow session : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data : cost: TensorFlow cost function : accuracy...
image-classification/dlnd_image_classification.ipynb
khalido/deep-learning
mit
Hyperparameters Tune the following parameters: * Set epochs to the number of iterations until the network stops learning or start overfitting * Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory: * 64 * 128 * 256 * ... * Set keep_probability to the...
# TODO: Tune Parameters epochs = None batch_size = None keep_probability = None
image-classification/dlnd_image_classification.ipynb
khalido/deep-learning
mit
A univariate example
np.random.seed(12345) # Seed the random number generator for reproducible results
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
We create a bimodal distribution: a mixture of two normal distributions with locations at -1 and 1.
# Location, scale and weight for the two distributions dist1_loc, dist1_scale, weight1 = -1 , .5, .25 dist2_loc, dist2_scale, weight2 = 1 , .5, .75 # Sample from a mixture of distributions obs_dist = mixture_rvs(prob=[weight1, weight2], size=250, dist=[stats.norm, stats.norm], ...
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
The simplest non-parametric technique for density estimation is the histogram.
fig = plt.figure(figsize=(12, 5)) ax = fig.add_subplot(111) # Scatter plot of data samples and histogram ax.scatter(obs_dist, np.abs(np.random.randn(obs_dist.size)), zorder=15, color='red', marker='x', alpha=0.5, label='Samples') lines = ax.hist(obs_dist, bins=20, edgecolor='k', label='Histogram') ax.lege...
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
Fitting with the default arguments The histogram above is discontinuous. To compute a continuous probability density function, we can use kernel density estimation. We initialize a univariate kernel density estimator using KDEUnivariate.
kde = sm.nonparametric.KDEUnivariate(obs_dist) kde.fit() # Estimate the densities
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
We present a figure of the fit, as well as the true distribution.
fig = plt.figure(figsize=(12, 5)) ax = fig.add_subplot(111) # Plot the histrogram ax.hist(obs_dist, bins=20, density=True, label='Histogram from samples', zorder=5, edgecolor='k', alpha=0.5) # Plot the KDE as fitted using the default arguments ax.plot(kde.support, kde.density, lw=3, label='KDE from samples', ...
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
In the code above, default arguments were used. We can also vary the bandwidth of the kernel, as we will now see. Varying the bandwidth using the bw argument The bandwidth of the kernel can be adjusted using the bw argument. In the following example, a bandwidth of bw=0.2 seems to fit the data well.
fig = plt.figure(figsize=(12, 5)) ax = fig.add_subplot(111) # Plot the histrogram ax.hist(obs_dist, bins=25, label='Histogram from samples', zorder=5, edgecolor='k', density=True, alpha=0.5) # Plot the KDE for various bandwidths for bandwidth in [0.1, 0.2, 0.4]: kde.fit(bw=bandwidth) # Estimate the densit...
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
Comparing kernel functions In the example above, a Gaussian kernel was used. Several other kernels are also available.
from statsmodels.nonparametric.kde import kernel_switch list(kernel_switch.keys())
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
The available kernel functions
# Create a figure fig = plt.figure(figsize=(12, 5)) # Enumerate every option for the kernel for i, (ker_name, ker_class) in enumerate(kernel_switch.items()): # Initialize the kernel object kernel = ker_class() # Sample from the domain domain = kernel.domain or [-3, 3] x_vals = np.linspace(*domain...
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
The available kernel functions on three data points We now examine how the kernel density estimate will fit to three equally spaced data points.
# Create three equidistant points data = np.linspace(-1, 1, 3) kde = sm.nonparametric.KDEUnivariate(data) # Create a figure fig = plt.figure(figsize=(12, 5)) # Enumerate every option for the kernel for i, kernel in enumerate(kernel_switch.keys()): # Create a subplot, set the title ax = fig.add_subplot(2, 4, ...
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
A more difficult case The fit is not always perfect. See the example below for a harder case.
obs_dist = mixture_rvs([.25, .75], size=250, dist=[stats.norm, stats.beta], kwargs = (dict(loc=-1, scale=.5), dict(loc=1, scale=1, args=(1, .5)))) kde = sm.nonparametric.KDEUnivariate(obs_dist) kde.fit() fig = plt.figure(figsize=(12, 5)) ax = fig.add_subplot(111) ax.hist(obs_dist, bins=20, density=True, e...
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
The KDE is a distribution Since the KDE is a distribution, we can access attributes and methods such as: entropy evaluate cdf icdf sf cumhazard
obs_dist = mixture_rvs([.25, .75], size=1000, dist=[stats.norm, stats.norm], kwargs = (dict(loc=-1, scale=.5), dict(loc=1, scale=.5))) kde = sm.nonparametric.KDEUnivariate(obs_dist) kde.fit(gridsize=2**10) kde.entropy kde.evaluate(-1)
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
Cumulative distribution, it's inverse, and the survival function
fig = plt.figure(figsize=(12, 5)) ax = fig.add_subplot(111) ax.plot(kde.support, kde.cdf, lw=3, label='CDF') ax.plot(np.linspace(0, 1, num = kde.icdf.size), kde.icdf, lw=3, label='Inverse CDF') ax.plot(kde.support, kde.sf, lw=3, label='Survival function') ax.legend(loc = 'best') ax.grid(True, zorder=-5)
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
The Cumulative Hazard Function
fig = plt.figure(figsize=(12, 5)) ax = fig.add_subplot(111) ax.plot(kde.support, kde.cumhazard, lw=3, label='Cumulative Hazard Function') ax.legend(loc = 'best') ax.grid(True, zorder=-5)
examples/notebooks/kernel_density.ipynb
jseabold/statsmodels
bsd-3-clause
Introduction The Corpus Callosum (CC) is the largest white matter structure in the central nervous system that connects both brain hemispheres and allows the communication between them. The CC has great importance in research studies due to the correlation between shape and volume with some subject's characteristics, s...
#Loading labeled segmentations seg_label = genfromtxt('../dataset/Seg_Watershed/watershed_label.csv', delimiter=',').astype('uint8') list_mask = seg_label[seg_label[:,1] == 0, 0][:20] #Extracting correct segmentations for mean signature list_normal_mask = seg_label[seg_label[:,1] == 0, 0][20:30] #Extracting correct na...
dev/mean-WJGH.ipynb
wilomaku/IA369Z
gpl-3.0
Shape signature for comparison Signature is a shape descriptor that measures the rate of variation along the segmentation contour. As shown in figure, the curvature $k$ in the pivot point $p$, with coordinates ($x_p$,$y_p$), is calculated using the next equation. This curvature depict the angle between the segments $\o...
n_list = len(list_mask) smoothness = 700 #Smoothness degree = 5 #Spline degree fit_res = 0.35 resols = np.arange(0.01,0.5,0.01) #Signature resolutions resols = np.insert(resols,0,fit_res) #Insert resolution for signature fitting points = 500 #Points of Spline reconstruction refer_wat = np.empty((n_list,resols.shape[0]...
dev/mean-WJGH.ipynb
wilomaku/IA369Z
gpl-3.0
In order to get a representative correct signature, mean signature per-resolution is generated using 20 correct signatures. The mean is calculated in each point.
refer_wat_mean = np.mean(refer_wat,axis=0) #Finding mean signature per resolution print "Mean signature size: ", refer_wat_mean.shape plt.figure() #Plotting mean signature plt.plot(refer_wat_mean[res_ex,:]) plt.title("Mean signature for res: %f"%(resols[res_ex])) plt.show()
dev/mean-WJGH.ipynb
wilomaku/IA369Z
gpl-3.0
The RMSE over the 10 correct segmentations was compared with RMSE over the 10 erroneous segmentations. As expected, RMSE for correct segmentations was greater than RMSE for erroneous segmentations along all the resolutions. In general, this is true, but optimal resolution guarantee the maximum difference between both o...
rmse_nacum = np.sqrt(np.sum((refer_wat_mean - refer_wat_n)**2,axis=2)/(refer_wat_mean.shape[1])) rmse_eacum = np.sqrt(np.sum((refer_wat_mean - refer_wat_e)**2,axis=2)/(refer_wat_mean.shape[1])) dif_dis = rmse_eacum - rmse_nacum #Difference between erroneous signatures and correct signatures in_max_res = np.argmax(np....
dev/mean-WJGH.ipynb
wilomaku/IA369Z
gpl-3.0
The greatest difference resulted at resolution 0.1. In this resolution, threshold for separate erroneous and correct segmentations is established as 30% of the distance between the mean RMSE of the correct masks and the mean RMSE of the erroneous masks. Method testing Finally, method test was performed in the 152 subje...
n_resols = [fit_res, opt_res] #Resolutions for fitting and comparison #### Teste dataset (Watershed) #Loading labels seg_label = genfromtxt('../dataset/Seg_Watershed/watershed_label.csv', delimiter=',').astype('uint8') all_seg = np.hstack((seg_label[seg_label[:,1] == 0, 0][30:], seg_label[seg_lab...
dev/mean-WJGH.ipynb
wilomaku/IA369Z
gpl-3.0
CCBB Library Imports
import sys sys.path.append(g_code_location)
notebooks/crispr/Dual CRISPR 2-Constuct Filter.ipynb
ucsd-ccbb/jupyter-genomics
mit
Automated Set-Up
# %load -s describe_var_list /Users/Birmingham/Repositories/ccbb_tickets/20160210_mali_crispr/src/python/ccbbucsd/utilities/analysis_run_prefixes.py def describe_var_list(input_var_name_list): description_list = ["{0}: {1}\n".format(name, eval(name)) for name in input_var_name_list] return "".join(description_...
notebooks/crispr/Dual CRISPR 2-Constuct Filter.ipynb
ucsd-ccbb/jupyter-genomics
mit
Info Logging Pass-Through
from ccbbucsd.utilities.notebook_logging import set_stdout_info_logger set_stdout_info_logger()
notebooks/crispr/Dual CRISPR 2-Constuct Filter.ipynb
ucsd-ccbb/jupyter-genomics
mit
Construct Filtering Functions
import enum # %load -s TrimType,get_trimmed_suffix /Users/Birmingham/Repositories/ccbb_tickets/20160210_mali_crispr/src/python/ccbbucsd/malicrispr/scaffold_trim.py class TrimType(enum.Enum): FIVE = "5" THREE = "3" FIVE_THREE = "53" def get_trimmed_suffix(trimtype): return "_trimmed{0}.fastq".format(tr...
notebooks/crispr/Dual CRISPR 2-Constuct Filter.ipynb
ucsd-ccbb/jupyter-genomics
mit
Let's go over the columns: - asof_date: the timeframe to which this data applies - timestamp: the simulated date upon which this data point is available to a backtest - open: opening price for the day indicated on asof_date - high: high price for the day indicated on asof_date - low: lowest price for the day indicated ...
# Convert it over to a Pandas dataframe for easy charting vix_df = odo(dataset, pd.DataFrame) vix_df.plot(x='asof_date', y='close') plt.xlabel("As of Date (asof_date)") plt.ylabel("Close Price") plt.axis([None, None, 0, 100]) plt.title("VIX") plt.legend().set_visible(False)
notebooks/data/quandl.yahoo_index_vix/notebook.ipynb
quantopian/research_public
apache-2.0
<a id='pipeline'></a> Pipeline Overview Accessing the data in your algorithms & research The only method for accessing partner data within algorithms running on Quantopian is via the pipeline API. Different data sets work differently but in the case of this data, you can add this data to your pipeline as follows: Impor...
# Import necessary Pipeline modules from quantopian.pipeline import Pipeline from quantopian.research import run_pipeline from quantopian.pipeline.factors import AverageDollarVolume # For use in your algorithms # Using the full dataset in your pipeline algo from quantopian.pipeline.data.quandl import yahoo_index_vix
notebooks/data/quandl.yahoo_index_vix/notebook.ipynb
quantopian/research_public
apache-2.0
Now that we've imported the data, let's take a look at which fields are available for each dataset. You'll find the dataset, the available fields, and the datatypes for each of those fields.
print "Here are the list of available fields per dataset:" print "---------------------------------------------------\n" def _print_fields(dataset): print "Dataset: %s\n" % dataset.__name__ print "Fields:" for field in list(dataset.columns): print "%s - %s" % (field.name, field.dtype) print "\n...
notebooks/data/quandl.yahoo_index_vix/notebook.ipynb
quantopian/research_public
apache-2.0
Now that we know what fields we have access to, let's see what this data looks like when we run it through Pipeline. This is constructed the same way as you would in the backtester. For more information on using Pipeline in Research view this thread: https://www.quantopian.com/posts/pipeline-in-research-build-test-and-...
# Let's see what this data looks like when we run it through Pipeline # This is constructed the same way as you would in the backtester. For more information # on using Pipeline in Research view this thread: # https://www.quantopian.com/posts/pipeline-in-research-build-test-and-visualize-your-factors-and-filters pipe =...
notebooks/data/quandl.yahoo_index_vix/notebook.ipynb
quantopian/research_public
apache-2.0
Taking what we've seen from above, let's see how we'd move that into the backtester.
# This section is only importable in the backtester from quantopian.algorithm import attach_pipeline, pipeline_output # General pipeline imports from quantopian.pipeline import Pipeline from quantopian.pipeline.factors import AverageDollarVolume # Import the datasets available # For use in your algorithms # Using the...
notebooks/data/quandl.yahoo_index_vix/notebook.ipynb
quantopian/research_public
apache-2.0
Basic Concepts What is "learning from data"? In general Learning from Data is a scientific discipline that is concerned with the design and development of algorithms that allow computers to infer (from data) a model that allows compact representation (unsupervised learning) and/or good generalization (supervised lear...
# numerical derivative at a point x def f(x): return x**2 def fin_dif(x, f, h = 0.00001): ''' This method returns the derivative of f at x by using the finite difference method ''' return (f(x+h) - f(x))/h x = 2.0 print "{:2.4f}".format(fin_dif(x,f))
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
It can be shown that the “centered difference formula" is better when computing numerical derivatives: $$ \lim_{h \rightarrow 0} \frac{f(x + h) - f(x - h)}{2h} $$ The error in the "finite difference" approximation can be derived from Taylor's theorem and, assuming that $f$ is differentiable, is $O(h)$. In the case of “...
old_min = 0 temp_min = 15 step_size = 0.01 precision = 0.0001 def f(x): return x**2 - 6*x + 5 def f_derivative(x): import math return 2*x -6 mins = [] cost = [] while abs(temp_min - old_min) > precision: old_min = temp_min move = f_derivative(old_min) * step_size temp_min = old_min - mo...
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
Exercise What happens if step_size=1.0?
# your solution
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
An important feature of gradient descent is that there should be a visible improvement over time. In the following example, we simply plotted the change in the value of the minimum against the iteration during which it was calculated. As we can see, the distance gets smaller over time, but barely changes in later iter...
x = np.linspace(-10,20,100) y = x**2 - 6*x + 5 x, y = (zip(*enumerate(cost))) fig, ax = plt.subplots(1, 1) fig.set_facecolor('#EAEAF2') plt.plot(x,y, 'r-', alpha=0.7) plt.ylim([-10,150]) plt.gcf().set_size_inches((10,3)) plt.grid(True) plt.show x = np.linspace(-10,20,100) y = x**2 - 6*x + 5 fig, ax = plt.subplots(1...
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
From derivatives to gradient: $n$-dimensional function minimization. Let's consider a $n$-dimensional function $f: \Re^n \rightarrow \Re$. For example: $$f(\mathbf{x}) = \sum_{n} x_n^2$$ Our objective is to find the argument $\mathbf{x}$ that minimizes this function. The gradient of $f$ is the vector whose components...
def f(x): return sum(x_i**2 for x_i in x) def fin_dif_partial_centered(x, f, i, h=1e-6): w1 = [x_j + (h if j==i else 0) for j, x_j in enumerate(x)] w2 = [x_j - (h if j==i else 0) for j, x_j in enumerate(x)] return (f(w1) - f(w2))/(2*h) def gradient_centered(x, f, h=1e-6): return[round(fin_dif_part...
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
The function we have evaluated, $f({\mathbf x}) = x_1^2+x_2^2+x_3^2$, is $3$ at $(1,1,1)$ and the gradient vector at this point is $(2,2,2)$. Then, we can follow this steps to maximize (or minimize) the function: Start from a random $\mathbf{x}$ vector. Compute the gradient vector. Walk a small step in the opposite d...
def euc_dist(v1,v2): import numpy as np import math v = np.array(v1)-np.array(v2) return math.sqrt(sum(v_i ** 2 for v_i in v))
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
Let's start by choosing a random vector and then walking a step in the opposite direction of the gradient vector. We will stop when the difference (in $\mathbf x$) between the new solution and the old solution is less than a tolerance value.
# choosing a random vector import random import numpy as np x = [random.randint(-10,10) for i in range(3)] x def step(x,grad,alpha): return [x_i - alpha * grad_i for x_i, grad_i in zip(x,grad)] tol = 1e-15 alpha = 0.01 while True: grad = gradient_centered(x,f) next_x = step(x,grad,alpha) if euc_dist...
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
Choosing Alpha The step size, alpha, is a slippy concept: if it is too small we will slowly converge to the solution, if it is too large we can diverge from the solution. There are several policies to follow when selecting the step size: Constant size steps. In this case, the size step determines the precision of the...
step_size = [100, 10, 1, 0.1, 0.01, 0.001, 0.0001, 0.00001]
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
Learning from data In general, we have: A dataset ${(\mathbf{x},y)}$ of $n$ examples. A target function $f_\mathbf{w}$, that we want to minimize, representing the discrepancy between our data and the model we want to fit. The model is represented by a set of parameters $\mathbf{w}$. The gradient of the target functi...
import numpy as np import random # f = 2x x = np.arange(10) y = np.array([2*i for i in x]) # f_target = 1/n Sum (y - wx)**2 def target_f(x,y,w): return np.sum((y - x * w)**2.0) / x.size # gradient_f = 2/n Sum 2wx**2 - 2xy def gradient_f(x,y,w): return 2 * np.sum(2*w*(x**2) - 2*x*y) / x.size def step(w,grad,...
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
Stochastic Gradient Descend The last function evals the whole dataset $(\mathbf{x}_i,y_i)$ at every step. If the dataset is large, this strategy is too costly. In this case we will use a strategy called SGD (Stochastic Gradient Descend). When learning from data, the cost function is additive: it is computed by adding ...
def in_random_order(data): import random indexes = [i for i,_ in enumerate(data)] random.shuffle(indexes) for i in indexes: yield data[i] import numpy as np import random def SGD(target_f, gradient_f, x, y, toler = 1e-6, epochs=100, alpha_0...
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
Example: Stochastic Gradient Descent and Linear Regression The linear regression model assumes a linear relationship between data: $$ y_i = w_1 x_i + w_0 $$ Let's generate a more realistic dataset (with noise), where $w_1 = 2$ and $w_0 = 0$. The bias trick. It is a little cumbersome to keep track separetey of $w_i$, t...
%reset import warnings warnings.filterwarnings('ignore') import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_regression from scipy import stats import random %matplotlib inline # x: input data # y: noisy output data x = np.random.uniform(0,1...
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
Mini-batch Gradient Descent In code, general batch gradient descent looks something like this: python nb_epochs = 100 for i in range(nb_epochs): grad = evaluate_gradient(target_f, data, w) w = w - learning_rate * grad For a pre-defined number of epochs, we first compute the gradient vector of the target functio...
def get_batches(iterable, n = 1): current_batch = [] for item in iterable: current_batch.append(item) if len(current_batch) == n: yield current_batch current_batch = [] if current_batch: yield current_batch %reset import warnings warnings.filterwarnings('igno...
1. Learning from data and optimization.ipynb
DeepLearningUB/EBISS2017
mit
The data goes all the way back to 1947 and is updated monthly. Blaze provides us with the first 10 rows of the data for display. Just to confirm, let's just count the number of rows in the Blaze expression:
fred_unrate.count()
notebooks/data/quandl.fred_unrate/notebook.ipynb
quantopian/research_public
apache-2.0
Let's go plot it for fun. This data set is definitely small enough to just put right into a Pandas DataFrame
unrate_df = odo(fred_unrate, pd.DataFrame) unrate_df.plot(x='asof_date', y='value') plt.xlabel("As Of Date (asof_date)") plt.ylabel("Unemployment Rate") plt.title("United States Unemployment Rate") plt.legend().set_visible(False)
notebooks/data/quandl.fred_unrate/notebook.ipynb
quantopian/research_public
apache-2.0
Next we define a function to produce a rotor given euler angles
def R_euler(phi, theta,psi): Rphi = e**(-phi/2.*e12) Rtheta = e**(-theta/2.*e23) Rpsi = e**(-psi/2.*e12) return Rphi*Rtheta*Rpsi
docs/tutorials/euler-angles.ipynb
arsenovic/clifford
bsd-3-clause
For example, using this to create a rotation similar to that shown in the animation above,
R = R_euler(pi/4, pi/4, pi/4) R
docs/tutorials/euler-angles.ipynb
arsenovic/clifford
bsd-3-clause
Convert to Quaternions A Rotor in 3D space is a unit quaternion, and so we have essentially created a function that converts Euler angles to quaternions. All you need to do is interpret the bivectors as $i,j,$ and $k$'s. See Interfacing Other Mathematical Systems, for more on quaternions. Convert to Rotation Matrix Th...
A = [e1,e2,e3] # initial ortho-normal frame B = [R*a*~R for a in A] # resultant frame after rotation B
docs/tutorials/euler-angles.ipynb
arsenovic/clifford
bsd-3-clause
The components of this frame are the rotation matrix, so we just enter the frame components into a matrix.
from numpy import array M = [float(b|a) for b in B for a in A] # you need float() due to bug in clifford M = array(M).reshape(3,3) M
docs/tutorials/euler-angles.ipynb
arsenovic/clifford
bsd-3-clause
Thats a rotation matrix. Convert a Rotation Matrix to a Rotor In 3 Dimenions, there is a simple formula which can be used to directly transform a rotations matrix into a rotor. For arbitrary dimensions you have to use a different algorithm (see clifford.tools.orthoMat2Versor() (docs)). Anyway, in 3 dimensions there is...
B = [M[0,0]*e1 + M[1,0]*e2 + M[2,0]*e3, M[0,1]*e1 + M[1,1]*e2 + M[2,1]*e3, M[0,2]*e1 + M[1,2]*e2 + M[2,2]*e3] B
docs/tutorials/euler-angles.ipynb
arsenovic/clifford
bsd-3-clause
Then implement the formula
A = [e1,e2,e3] R = 1+sum([A[k]*B[k] for k in range(3)]) R = R/abs(R) R
docs/tutorials/euler-angles.ipynb
arsenovic/clifford
bsd-3-clause
Import data Creates a dataframe (called "data") and fills it with data from a URL.
data = pd.read_csv("http://web_address.com/filename.csv")
templateTable.ipynb
merryjman/astronomy
gpl-3.0
Display part of the data table
data.head(3)
templateTable.ipynb
merryjman/astronomy
gpl-3.0
Make a scatter plot of two column's data
# Set variables for scatter plot # x = data.OneColumnName y = data.AnotherColumnName # make the graph plt.scatter(x,y) plt.title('title') plt.xlabel('label') plt.ylabel('label') # This actually shows the plot plt.show()
templateTable.ipynb
merryjman/astronomy
gpl-3.0
Make a histogram of one column's data
plt.hist(data.ColumnName, bins=10, range=[0,100])
templateTable.ipynb
merryjman/astronomy
gpl-3.0
Import the Fang et al. 2016 data
tab1 = pd.read_fwf('../data/Fang2016/Table_1+4_online.dat', na_values=['-99.00000000', '-9999.0', '99.000, 99.0']) df = tab1.rename(columns={'# Object_name':'Object_name'}) df.head() df.Object_name.values[0:30]
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
Ugh, the naming convention is non-standard in a way that is likely more work than it's worth to try to match to other catalogs. Whyyyyyyyyy. Try full-blown coordinate matching From astropy: http://docs.astropy.org/en/stable/coordinates/matchsep.html
ra1 = df.RAJ2000 dec1 = df.DEJ2000 ra2 = df_abc.RAdeg dec2 = df_abc.DEdeg from astropy.coordinates import SkyCoord from astropy import units as u c = SkyCoord(ra=ra1*u.degree, dec=dec1*u.degree) catalog = SkyCoord(ra=ra2*u.degree, dec=dec2*u.degree) idx, d2d, d3d = c.match_to_catalog_sky(catalog) plt.figure(fi...
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
Ok, we'll accept all matches with better than 0.375 arcsecond separation.
boolean_matches = d2d.to(u.arcsecond).value < 0.375
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
How many matches are there?
boolean_matches.sum()
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
120 matches--- not bad. Only keep the subset of fang sources that also have K2
df['EPIC'] = '' matched_idx = idx[boolean_matches] matched_idx df.shape, df_abc.shape idx.shape df['EPIC'][boolean_matches] = df_abc['EPIC'].iloc[matched_idx].values fang_K2 = pd.merge(df_abc, df, how='left', on='EPIC') fang_K2.columns fang_K2[['Name_adopt', 'Object_name']][fang_K2.Object_name.notnull()].tail(1...
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
Great correspondence! Looks like there are 120 targets in both categories. Let's spot-check if they use similar temperatures:
plt.figure(figsize=(7, 7)) plt.plot(fang_K2.Teff, fang_K2.Tspec, 'o') plt.xlabel(r'$T_{\mathrm{eff}}$ Stauffer et al. 2016') plt.ylabel(r'$T_{\mathrm{spec}}$ Fang et al. 2016') plt.plot([3000, 6300], [3000, 6300], 'k--') plt.ylim(3000, 6300) plt.xlim(3000, 6300);
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
What's the scatter?
delta_Tspec = fang_K2.Teff - fang_K2.Tspec delta_Tspec = delta_Tspec.dropna() RMS_Tspec = np.sqrt((delta_Tspec**2.0).sum()/len(delta_Tspec)) print('{:0.0f}'.format(RMS_Tspec))
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
The authors disagree on temperature by about $\delta T \sim$ 100 K RMS. Let's make the figure we really want to make: K2 Amplitude versus spectroscopically measured filling factor of starspots $f_{spot}$. We expect that the plot will be a little noisy due to differences in temperature assumptions and such, but it is ...
fang_K2['flux_amp'] = 1.0 - 10**(fang_K2.Ampl/-2.5) plt.hist(fang_K2.flux_amp, bins=np.arange(0, 0.15, 0.005)); plt.hist(fang_K2.fs1.dropna(), bins=np.arange(0, 0.8, 0.03)); sns.set_context('talk') plt.figure(figsize=(7, 7)) plt.plot(fang_K2.fs1, fang_K2.flux_amp, '.') plt.plot([0,1], [0,1], 'k--') plt.xlim(0.0,0.2...
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
Awesome! The location of points indicate that starspots have a large longitudinally-symmetric component that evades detection in K2 amplitudes. What effects can cause / mimic this behavior? - Unresolved binarity could cause an errant TiO measurement, biasing the Fang et al. measurement. - Increased rotation (Rossby nu...
fang_K2.columns fang_K2.beat.value_counts()
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
Crosstabs with discreate variables: Legend
plt.figure(figsize=(7, 7)) cross_tab = 'resc' c1 = fang_K2[cross_tab] == 'yes' c2 = fang_K2[cross_tab] == 'no' plt.plot(fang_K2.fs1[c1], fang_K2.flux_amp[c1], 'r.', label='{} = yes'.format(cross_tab)) plt.plot(fang_K2.fs1[c2], fang_K2.flux_amp[c2], 'b.', label='{} = no'.format(cross_tab)) plt.legend(loc='best') plt.p...
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
Crosstabs with continuous variables: Colorbar
plt.figure(figsize=(7, 7)) cross_tab = 'Mass' cm = plt.cm.get_cmap('Blues') sc = plt.scatter(fang_K2.fs1, fang_K2.flux_amp, c=fang_K2[cross_tab], cmap=cm) cb = plt.colorbar(sc) #cb.set_label(r'$T_{spot}$ (K)') plt.plot([0,1], [0,1], 'k--') plt.xlim(-0.01,0.8) plt.ylim(0,0.15) plt.xlabel('LAMOST-measured $f_{spot}$ \n ...
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
What about inclination? $$ V = \frac{d}{t} = \frac{2 \pi R}{P} $$ $$ V \sin{i} = \frac{2 \pi R}{P} \sin{i}$$ $$ V \sin{i} \cdot \frac{P}{2 \pi R} = \sin{i}$$ $$ \arcsin{\lgroup V \sin{i} \cdot \frac{P}{2 \pi R} \rgroup} = i$$
import astropy.units as u sini = fang_K2.vsini * u.km/u.s * fang_K2.Per1* u.day /(2.0*np.pi *u.solRad) vec = sini.values.to(u.dimensionless_unscaled).value sns.distplot(vec[vec == vec], bins=np.arange(0,2, 0.1), kde=False) plt.axvline(1.0, color='k', linestyle='dashed') inclination = np.arcsin(vec)*180.0/np.pi sns...
notebooks/Rebull2016_extra.ipynb
BrownDwarf/ApJdataFrames
mit
K-means clustering Example adapted from here. Load dataset
iris = datasets.load_iris() X,y = iris.data[:,:2], iris.target
lecture6/ML-Anirban_Tutorial6.ipynb
Santara/ML-MOOC-NPTEL
gpl-3.0
Define and train model
num_clusters = 8 model = KMeans(n_clusters=num_clusters) model.fit(X)
lecture6/ML-Anirban_Tutorial6.ipynb
Santara/ML-MOOC-NPTEL
gpl-3.0
Extract the labels and the cluster centers
labels = model.labels_ cluster_centers = model.cluster_centers_ print cluster_centers
lecture6/ML-Anirban_Tutorial6.ipynb
Santara/ML-MOOC-NPTEL
gpl-3.0
Plot the clusters
plt.scatter(X[:,0], X[:,1],c=labels.astype(np.float)) plt.hold(True) plt.scatter(cluster_centers[:,0], cluster_centers[:,1], c = np.arange(num_clusters), marker = '^', s = 150) plt.show() plt.scatter(X[:,0], X[:,1],c=np.choose(y,[0,2,1]).astype(np.float)) plt.show()
lecture6/ML-Anirban_Tutorial6.ipynb
Santara/ML-MOOC-NPTEL
gpl-3.0
Gaussian Mixture Model Example taken from here. Define a visualization function
def make_ellipses(gmm, ax): """ Visualize the gaussians in a GMM as ellipses """ for n, color in enumerate('rgb'): v, w = np.linalg.eigh(gmm._get_covars()[n][:2, :2]) u = w[0] / np.linalg.norm(w[0]) angle = np.arctan2(u[1], u[0]) angle = 180 * angle / np.pi # convert to ...
lecture6/ML-Anirban_Tutorial6.ipynb
Santara/ML-MOOC-NPTEL
gpl-3.0
Load dataset and make training and test splits
iris = datasets.load_iris() # Break up the dataset into non-overlapping training (75%) and testing # (25%) sets. skf = StratifiedKFold(iris.target, n_folds=4) # Only take the first fold. train_index, test_index = next(iter(skf)) X_train = iris.data[train_index] y_train = iris.target[train_index] X_test = iris.data[t...
lecture6/ML-Anirban_Tutorial6.ipynb
Santara/ML-MOOC-NPTEL
gpl-3.0
Train and compare different GMMs
# Try GMMs using different types of covariances. classifiers = dict((covar_type, GMM(n_components=n_classes, covariance_type=covar_type, init_params='wc', n_iter=20)) for covar_type in ['spherical', 'diag', 'tied', 'full']) n_classifiers = len(classifiers) plt.figure(figsize=(2*...
lecture6/ML-Anirban_Tutorial6.ipynb
Santara/ML-MOOC-NPTEL
gpl-3.0
Hierarchical Agglomerative Clustering Example taken from here. Load and pre-process dataset
digits = datasets.load_digits(n_class=10) X = digits.data y = digits.target n_samples, n_features = X.shape np.random.seed(0) def nudge_images(X, y): # Having a larger dataset shows more clearly the behavior of the # methods, but we multiply the size of the dataset only by 2, as the # cost of the hierarch...
lecture6/ML-Anirban_Tutorial6.ipynb
Santara/ML-MOOC-NPTEL
gpl-3.0
Visualize the clustering
def plot_clustering(X_red, X, labels, title=None): x_min, x_max = np.min(X_red, axis=0), np.max(X_red, axis=0) X_red = (X_red - x_min) / (x_max - x_min) plt.figure(figsize=(2*6, 2*4)) for i in range(X_red.shape[0]): plt.text(X_red[i, 0], X_red[i, 1], str(y[i]), color=plt.cm.spe...
lecture6/ML-Anirban_Tutorial6.ipynb
Santara/ML-MOOC-NPTEL
gpl-3.0
Create a 2D embedding of the digits dataset
print("Computing embedding") X_red = manifold.SpectralEmbedding(n_components=2).fit_transform(X) print("Done.")
lecture6/ML-Anirban_Tutorial6.ipynb
Santara/ML-MOOC-NPTEL
gpl-3.0
Train and visualize the clusters Ward minimizes the sum of squared differences within all clusters. It is a variance-minimizing approach and in this sense is similar to the k-means objective function but tackled with an agglomerative hierarchical approach. Maximum or complete linkage minimizes the maximum distance bet...
from sklearn.cluster import AgglomerativeClustering for linkage in ('ward', 'average', 'complete'): clustering = AgglomerativeClustering(linkage=linkage, n_clusters=10) t0 = time() clustering.fit(X_red) print("%s : %.2fs" % (linkage, time() - t0)) plot_clustering(X_red, X, clustering.labels_, "%s ...
lecture6/ML-Anirban_Tutorial6.ipynb
Santara/ML-MOOC-NPTEL
gpl-3.0
These features are: sepal length in cm sepal width in cm petal length in cm petal width in cm Numerical features such as these are pretty straightforward: each sample contains a list of floating-point numbers corresponding to the features Categorical Features What if you have categorical features? For example, imagi...
measurements = [ {'city': 'Dubai', 'temperature': 33.}, {'city': 'London', 'temperature': 12.}, {'city': 'San Francisco', 'temperature': 18.}, ] from sklearn.feature_extraction import DictVectorizer vec = DictVectorizer() vec vec.fit_transform(measurements).toarray() vec.get_feature_names()
notebooks/10.Case_Study-Titanic_Survival.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
Derived Features Another common feature type are derived features, where some pre-processing step is applied to the data to generate features that are somehow more informative. Derived features may be based in feature extraction and dimensionality reduction (such as PCA or manifold learning), may be linear or nonlinea...
import os import pandas as pd titanic = pd.read_csv(os.path.join('datasets', 'titanic3.csv')) print(titanic.columns)
notebooks/10.Case_Study-Titanic_Survival.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
Here is a broad description of the keys and what they mean: pclass Passenger Class (1 = 1st; 2 = 2nd; 3 = 3rd) survival Survival (0 = No; 1 = Yes) name Name sex Sex age Age sibsp Number of Siblings/Spouses Aboard parch ...
titanic.head()
notebooks/10.Case_Study-Titanic_Survival.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
We clearly want to discard the "boat" and "body" columns for any classification into survived vs not survived as they already contain this information. The name is unique to each person (probably) and also non-informative. For a first try, we will use "pclass", "sibsp", "parch", "fare" and "embarked" as our features:
labels = titanic.survived.values features = titanic[['pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked']] features.head()
notebooks/10.Case_Study-Titanic_Survival.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
The data now contains only useful features, but they are not in a format that the machine learning algorithms can understand. We need to transform the strings "male" and "female" into binary variables that indicate the gender, and similarly for "embarked". We can do that using the pandas get_dummies function:
pd.get_dummies(features).head()
notebooks/10.Case_Study-Titanic_Survival.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
This transformation successfully encoded the string columns. However, one might argue that the class is also a categorical variable. We can explicitly list the columns to encode using the columns parameter, and include pclass:
features_dummies = pd.get_dummies(features, columns=['pclass', 'sex', 'embarked']) features_dummies.head(n=16) data = features_dummies.values import numpy as np np.isnan(data).any()
notebooks/10.Case_Study-Titanic_Survival.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
With all of the hard data loading work out of the way, evaluating a classifier on this data becomes straightforward. Setting up the simplest possible model, we want to see what the simplest score can be with DummyClassifier.
from sklearn.model_selection import train_test_split from sklearn.preprocessing import Imputer train_data, test_data, train_labels, test_labels = train_test_split( data, labels, random_state=0) imp = Imputer() imp.fit(train_data) train_data_finite = imp.transform(train_data) test_data_finite = imp.transform(test...
notebooks/10.Case_Study-Titanic_Survival.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
<div class="alert alert-success"> <b>EXERCISE</b>: <ul> <li> Try executing the above classification, using LogisticRegression and RandomForestClassifier instead of DummyClassifier </li> <li> Does selecting a different subset of features help? </li> </ul> </div>
# %load solutions/10_titanic.py
notebooks/10.Case_Study-Titanic_Survival.ipynb
amueller/scipy-2017-sklearn
cc0-1.0
Set all graphics from matplotlib to display inline
#!pip install matplotlib import matplotlib.pyplot as plt %matplotlib inline #This lets your graph show you in your notebook df
07/pandas-homework-hon-june13.ipynb
honjy/foundations-homework
mit
Display the names of the columns in the csv
df['name']
07/pandas-homework-hon-june13.ipynb
honjy/foundations-homework
mit
Display the first 3 animals.
df.head(3)
07/pandas-homework-hon-june13.ipynb
honjy/foundations-homework
mit
Sort the animals to see the 3 longest animals.
df.sort_values('length', ascending=False).head(3)
07/pandas-homework-hon-june13.ipynb
honjy/foundations-homework
mit
What are the counts of the different values of the "animal" column? a.k.a. how many cats and how many dogs.
df['animal'].value_counts()
07/pandas-homework-hon-june13.ipynb
honjy/foundations-homework
mit
Only select the dogs.
dog_df = df['animal'] == 'dog' df[dog_df]
07/pandas-homework-hon-june13.ipynb
honjy/foundations-homework
mit
Display all of the animals that are greater than 40 cm.
long_animals = df['length'] > 40 df[long_animals]
07/pandas-homework-hon-june13.ipynb
honjy/foundations-homework
mit
'length' is the animal's length in cm. Create a new column called inches that is the length in inches. 1 inch = 2.54 cm
df['length_inches'] = df['length'] / 2.54 df
07/pandas-homework-hon-june13.ipynb
honjy/foundations-homework
mit