markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
SAPCAR Entry Header | f0._sapcar.files0[0].canvas_dump() | docs/fileformats/SAPCAR.ipynb | CoreSecurity/pysap | gpl-2.0 |
SAPCAR Data Block | f0._sapcar.files0[0].blocks[0].canvas_dump() | docs/fileformats/SAPCAR.ipynb | CoreSecurity/pysap | gpl-2.0 |
SAPCAR Compressed Data | f0._sapcar.files0[0].blocks[0].compressed.canvas_dump() | docs/fileformats/SAPCAR.ipynb | CoreSecurity/pysap | gpl-2.0 |
SAPCAR Archive version 2.01 | f1 = SAPCARArchive("archive_file.car", mode="wb", version=SAPCAR_VERSION_201)
f1.add_file("some_file") | docs/fileformats/SAPCAR.ipynb | CoreSecurity/pysap | gpl-2.0 |
The file is comprised of the following main structures:
SAPCAR Archive Header | f1._sapcar.canvas_dump() | docs/fileformats/SAPCAR.ipynb | CoreSecurity/pysap | gpl-2.0 |
SAPCAR Entry Header | f1._sapcar.files1[0].canvas_dump() | docs/fileformats/SAPCAR.ipynb | CoreSecurity/pysap | gpl-2.0 |
SAPCAR Data Block | f1._sapcar.files1[0].blocks[0].canvas_dump() | docs/fileformats/SAPCAR.ipynb | CoreSecurity/pysap | gpl-2.0 |
SAPCAR Compressed data | f1._sapcar.files1[0].blocks[0].compressed.canvas_dump()
from os import remove
remove("some_file")
remove("archive_file.car") | docs/fileformats/SAPCAR.ipynb | CoreSecurity/pysap | gpl-2.0 |
Boilerplate for graph visualization | # This is for graph visualization.
from IPython.display import clear_output, Image, display, HTML
def strip_consts(graph_def, max_const_size=32):
"""Strip large constant values from graph_def."""
strip_def = tf.GraphDef()
for n0 in graph_def.node:
n = strip_def.node.add()
n.MergeFrom(n0)
... | archive/zurich/solutions/02_quickdraw_solution.ipynb | random-forests/tensorflow-workshop | apache-2.0 |
Load the data
Run 00_download_data.ipynb if you haven't already | DATA_DIR = '../data/'
data_filename = os.path.join(DATA_DIR, "zoo.npz")
data = np.load(open(data_filename))
train_data = data['arr_0']
train_labels = data['arr_1']
test_data = data['arr_2']
test_labels = data['arr_3']
del data
print("Data shapes: ", test_data.shape, test_labels.shape, train_data.shape, train_labels.sh... | archive/zurich/solutions/02_quickdraw_solution.ipynb | random-forests/tensorflow-workshop | apache-2.0 |
Create a simple classifier with low-level TF Ops | tf.reset_default_graph()
input_dimension = train_data.shape[1] # 784 = 28*28 pixels
output_dimension = train_labels.shape[1] # 10 classes
batch_size = 32
hidden1_units = 128
data_batch = tf.placeholder("float", shape=[None, input_dimension], name="data")
label_batch = tf.placeholder("float", shape=[None, output_... | archive/zurich/solutions/02_quickdraw_solution.ipynb | random-forests/tensorflow-workshop | apache-2.0 |
We can run this graph by feeding in batches of examples using a feed_dict. The keys of the feed_dict are placeholders we've defined previously.
The first argument of session.run is the tensor that we're computing. Only parts of the graph required to produce this value will be executed. | with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
random_indices = np.random.permutation(train_data.shape[0])
for i in range(1000):
batch_start_idx = (i % (train_data.shape[0] // batch_size)) * batch_size
batch_indices = random_indices[batch_start_idx:... | archive/zurich/solutions/02_quickdraw_solution.ipynb | random-forests/tensorflow-workshop | apache-2.0 |
No learning yet but we get the losses per batch.
We need to add an optimizer to the graph. | # Task: Replace GradientDescentOptimizer with AdagradOptimizer and a 0.1 learning rate.
# learning_rate = 0.005
# updates = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss)
# SOLUTION: Replace GradientDescentOptimizer
learning_rate = 0.1
updates = tf.train.AdagradOptimizer(learning_rate).minimize(loss)
... | archive/zurich/solutions/02_quickdraw_solution.ipynb | random-forests/tensorflow-workshop | apache-2.0 |
Loss going down, Accuracy going up! \o/
Notice how batch loss differs between batches.
Model wrapped in a custom estimator
In TensorFlow, we can make it easier to experiment with different models when we separately define a model_fn and an input_fn. | tf.reset_default_graph()
# Model parameters.
batch_size = 32
hidden1_units = 128
learning_rate = 0.005
input_dimension = train_data.shape[1] # 784 = 28*28 pixels
output_dimension = train_labels.shape[1] # 6 classes
n_epochs = 10 # how often do to go through the training data
def input_fn(data, labels):
input... | archive/zurich/solutions/02_quickdraw_solution.ipynb | random-forests/tensorflow-workshop | apache-2.0 |
Custom model, simplified with tf.layers
Instead of doing the matrix multiplications and everything ourselves, we can use tf.layers to simplify the definition. | tf.reset_default_graph()
# Model parameters.
batch_size = 32
hidden1_units = 128
learning_rate = 0.005
input_dimension = train_data.shape[1] # 784 = 28*28 pixels
output_dimension = train_labels.shape[1] # 6 classes
def layers_custom_model_fn(features, targets, mode, params):
# 1. Configure the model via Tensor... | archive/zurich/solutions/02_quickdraw_solution.ipynb | random-forests/tensorflow-workshop | apache-2.0 |
Model using canned estimators
Instead of defining our own DNN classifier, TensorFlow supplies a number of canned estimators that can save a lot of work. | tf.reset_default_graph()
# Model parameters.
hidden1_units = 128
learning_rate = 0.005
input_dimension = train_data.shape[1] # 784 = 28*28 pixels
output_dimension = train_labels.shape[1] # 6 classes
# Our model can be defined using just three simple lines...
optimizer = tf.train.GradientDescentOptimizer(learning_r... | archive/zurich/solutions/02_quickdraw_solution.ipynb | random-forests/tensorflow-workshop | apache-2.0 |
Using Convolutions | import tensorflow as tf
tf.reset_default_graph()
input_dimension = train_data.shape[1] # 784 = 28*28 pixels
output_dimension = train_labels.shape[1] # 6 classes
batch_size = 32
data_batch = tf.placeholder("float", shape=[None, input_dimension])
label_batch = tf.placeholder("float", shape=[None, output_dimension])... | archive/zurich/solutions/02_quickdraw_solution.ipynb | random-forests/tensorflow-workshop | apache-2.0 |
Model Building Process | Image("images/model-pipeline.png") | 02-logisitc-regression-intro.ipynb | sampathweb/movie-sentiment-analysis | mit |
Dataset | centers = np.array([[0, 0]] * 100 + [[1, 1]] * 100)
np.random.seed(42)
X = np.random.normal(0, 0.2, (200, 2)) + centers
y = np.array([0] * 100 + [1] * 100)
plt.scatter(X[:,0], X[:,1], c=y, cmap=plt.cm.RdYlBu)
plt.colorbar();
X[:5]
y[:5], y[-5:] | 02-logisitc-regression-intro.ipynb | sampathweb/movie-sentiment-analysis | mit |
Logistic Regression - Model
Take a weighted sum of the features and add a bias term to get the logit.
Sqash this weighted sum to arange between 0-1 via a Sigmoid function.
Sigmoid Function
<img src="images/sigmoid.png",width=500>
$$f(x) = \frac{e^x}{1+e^x}$$ | Image("images/logistic-regression.png")
## Build the Model
from sklearn.linear_model import LogisticRegression
## Step 1 - Instantiate the Model with Hyper Parameters (We don't have any here)
model = LogisticRegression()
## Step 2 - Fit the Model
model.fit(X, y)
## Step 3 - Evaluate the Model
model.score(X, y)
de... | 02-logisitc-regression-intro.ipynb | sampathweb/movie-sentiment-analysis | mit |
Dataset - Take 2 | centers = np.array([[0, 0]] * 100 + [[1, 1]] * 100)
np.random.seed(42)
X = np.random.normal(0, 0.5, (200, 2)) + centers
y = np.array([0] * 100 + [1] * 100)
plt.scatter(X[:,0], X[:,1], c=y, cmap=plt.cm.RdYlBu)
plt.colorbar();
# Instantiate, Fit, Evalaute
model = LogisticRegression()
model.fit(X, y)
print(model.score(X... | 02-logisitc-regression-intro.ipynb | sampathweb/movie-sentiment-analysis | mit |
Other Evaluation Methods
Confusion Matrix | from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y, y_pred)
cm
pd.crosstab(y, y_pred, rownames=['Actual'], colnames=['Predicted'], margins=True) | 02-logisitc-regression-intro.ipynb | sampathweb/movie-sentiment-analysis | mit |
Let's define an ES index mapping for the data that will be uploaded to the ES server | MAPPING_GIT = {
"mappings": {
"item": {
"properties": {
"date": {
"type": "date",
"format" : "E MMM d HH:mm:ss yyyy Z",
"locale" : "US"
},
"commit": {"type": "keyword"},
"a... | Light Git index generator.ipynb | jsmanrique/grimoirelab-personal-utils | mit |
Let's give a name to the index to be created, and create it.
Note: utils.create_ES_index() removes any existing index with the given name before creating it | index_name = 'git'
utils.create_ES_index(es, index_name, MAPPING_GIT) | Light Git index generator.ipynb | jsmanrique/grimoirelab-personal-utils | mit |
Let's import the git backend from Perceval | from perceval.backends.core.git import Git | Light Git index generator.ipynb | jsmanrique/grimoirelab-personal-utils | mit |
For each repository in the settings file, let's get its data, create a summary object with the desired information and upload data to the ES server using ES bulk API. | for repo_url in settings['git']:
repo_name = repo_url.split('/')[-1]
repo = Git(uri=repo_url, gitpath='/tmp/'+repo_name)
utils.logging.info('Go for {}'.format(repo_name))
items = []
bulk_size = 10000
for commit in repo.fetch():
author_name = commit['data']['A... | Light Git index generator.ipynb | jsmanrique/grimoirelab-personal-utils | mit |
Load data from exported CSV from Ted Full Grade Center. Some sanitization is performed to remove non-ascii characters and cruft | def load_data(filename):
d = read_csv(filename)
d.columns = [remove_non_ascii(c) for c in d.columns]
d.columns = [c.split("[")[0].strip().strip("\"") for c in d.columns]
d["Weighted Total"] = [float(i.strip("%")) for i in d["Weighted Total"]]
print(d.columns)
return d
d = load_data("gc_CENG114_... | grades/statsw2016.ipynb | materialsvirtuallab/ceng114 | bsd-2-clause |
Overall grade
Overall points and assign overall grade. | cutoffs = bar_plot(d, "Weighted Total", offset=-2)
print cutoffs
def assign_grade(pts):
for g, c in cutoffs.items():
if c[0] < pts <= c[1]:
return g
#d = load_data("gc_CENG114_WI16_Ong_fullgc_2016-03-21-15-47-06.csv") #use revised gc
d["Final_Assigned_Egrade"] = map(assign_grade, d["... | grades/statsw2016.ipynb | materialsvirtuallab/ceng114 | bsd-2-clause |
1. Data preprocessing
1.1. The dataset.
A key component of any data processing method or any machine learning algorithm is the dataset, i.e., the set of data that will be the input to the method or algorithm.
The dataset collects information extracted from a population (of objects, entities, individuals,...). For inst... | from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=300, centers=4, random_state=0, cluster_std=0.60)
X = X @ np.array([[30, 4], [-8, 1]]) + np.array([90, 10])
plt.figure(figsize=(12, 3))
plt.scatter(X[:, 0], X[:, 1], s=50);
plt.axis('equal')
plt.xlabel('$x_0$')
plt.ylabel('$x_1$')
plt.show() | P5.Data preprocessing/Intro5_DataNormalization_professor.ipynb | ML4DS/ML4all | mit |
We can see that the first data feature ($x_0$) has a much large range of variation than the second ($x_1$). In practice, this may be problematic: the convergence properties of some machine learning algorithms may depend critically on the feature distributions and, in general, features sets ranging over similar scales u... | # Compute the sample mean
# m = <FILL IN>
m = np.mean(X, axis=0) # Compute the sample mean
print(f'The sample mean is m = {m}')
# Compute the standard deviation of each feature
# s = <FILL IN>
s = np.std(X, axis=0) # Compute the standard deviation of each feature
# Normalize de data matrix
# T = <FILL IN>
T ... | P5.Data preprocessing/Intro5_DataNormalization_professor.ipynb | ML4DS/ML4all | mit |
We can test if the transformed features have zero-mean and unit variance: | # Testing mean
print(f"- The mean of the transformed features are: {np.mean(T, axis=0)}")
print(f"- The standard deviation of the transformed features are: {np.std(T, axis=0)}") | P5.Data preprocessing/Intro5_DataNormalization_professor.ipynb | ML4DS/ML4all | mit |
(note that the results can deviate from 0 or 1 due to finite precision errors) | # Now you can verify if your solution satisfies
plt.figure(figsize=(4, 4))
plt.scatter(T[:, 0], T[:, 1], s=50);
plt.axis('equal')
plt.xlabel('$x_0$')
plt.ylabel('$x_1$')
plt.show() | P5.Data preprocessing/Intro5_DataNormalization_professor.ipynb | ML4DS/ML4all | mit |
2.1.1. Implementation in sklearn
The sklearn package contains a method to perform the standard scaling over a given data matrix. | from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X)
print(f'The sample mean is m = {scaler.mean_}')
T2 = scaler.transform(X)
plt.figure(figsize=(4, 4))
plt.scatter(T2[:, 0], T2[:, 1], s=50);
plt.axis('equal')
plt.xlabel('$x_0$')
plt.ylabel('$x_1$')
plt.show() | P5.Data preprocessing/Intro5_DataNormalization_professor.ipynb | ML4DS/ML4all | mit |
Note that, once we have defined the scaler object in Python, you can apply the scaling transformation to other datasets. This will be useful in further topics, when the dataset may be split in several matrices and we may be interested in defining the transformation using some matrix, and apply it to others
2.2. Other n... | # Write your solution here
# <SOL>
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(2, 4))
scaler.fit(X)
T24 = scaler.transform(X)
# </SOL>
# We can visually check that the transformed data features lie in the selected range.
plt.figure(figsize=(4, 4))
plt.scatter(T24[:, 0], T24[:, 1... | P5.Data preprocessing/Intro5_DataNormalization_professor.ipynb | ML4DS/ML4all | mit |
Introduction to Visualization:
Density Estimation and Data Exploration
Version 0.1
There are many flavors of data analysis that fall under the "visualization" umbrella in astronomy. Today, by way of example, we will focus on 2 basic problems.
By AA Miller
16 September 2017
Problem 1) Density Estimation
Starting with ... | from sklearn.datasets import load_linnerud
linnerud = load_linnerud()
chinups = linnerud.data[:,0] | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 1a
Plot the histogram for the number of chinups using the default settings in pyplot. | plt.hist( # complete | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Already with this simple plot we see a problem - the choice of bin centers and number of bins suggest that there is a 0% probability that middle aged men can do 10 chinups. Intuitively this seems incorrect, so lets examine how the histogram changes if we change the number of bins or the bin centers.
Problem 1b
Using t... | plt.hist( # complete
# complete | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
These small changes significantly change the output PDF. With fewer bins we get something closer to a continuous distribution, while shifting the bin centers reduces the probability to zero at 9 chinups.
What if we instead allow the bin width to vary and require the same number of points in each bin? You can determine... | # complete
plt.hist(# complete | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Ending the lie
Earlier I stated that histograms lie. One simple way to combat this lie: show all the data. Displaying the original data points allows viewers to somewhat intuit the effects of the particular bin choices that have been made (though this can also be cumbersome for very large data sets, which these days i... | plt.hist(chinups, histtype = 'step')
# this is the code for the rug plot
plt.plot(chinups, np.zeros_like(chinups), '|', color='k', ms = 25, mew = 4) | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Of course, even rug plots are not a perfect solution. Many of the chinup measurements are repeated, and those instances cannot be easily isolated above. One (slightly) better solution is to vary the transparency of the rug "whiskers" using alpha = 0.3 in the whiskers plot call. But this too is far from perfect.
To rec... | # execute this cell
from sklearn.neighbors import KernelDensity
def kde_sklearn(data, grid, bandwidth = 1.0, **kwargs):
kde_skl = KernelDensity(bandwidth = bandwidth, **kwargs)
kde_skl.fit(data[:, np.newaxis])
log_pdf = kde_skl.score_samples(grid[:, np.newaxis]) # sklearn returns log(density)
return np... | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Problem 1e
Plot the KDE of the PDF for the number of chinups middle aged men can do using a bandwidth of 0.1 and a tophat kernel.
Hint - as a general rule, the grid should be smaller than the bandwidth when plotting the PDF. | grid = # complete
PDFtophat = kde_sklearn( # complete
plt.plot( # complete | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
In this representation, each "block" has a height of 0.25. The bandwidth is too narrow to provide any overlap between the blocks. This choice of kernel and bandwidth produces an estimate that is essentially a histogram with a large number of bins. It gives no sense of continuity for the distribution. Now, we examine th... | PDFtophat1 = # complete
# complete
# complete
# complete | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
It turns out blocks are not an ideal representation for continuous data (see discussion on histograms above). Now we will explore the resulting PDF from other kernels.
Problem 1g Plot the KDE of the PDF for the number of chinups middle aged men can do using a gaussian and Epanechnikov kernel. How do the results differ... | PDFgaussian = # complete
PDFepanechnikov = # complete | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
So, what is the optimal choice of bandwidth and kernel? Unfortunately, there is no hard and fast rule, as every problem will likely have a different optimization. Typically, the choice of bandwidth is far more important than the choice of kernel. In the case where the PDF is likely to be gaussian (or close to gaussian)... | x = np.arange(0, 6*np.pi, 0.1)
y = np.cos(x)
plt.plot(x,y, lw = 2)
plt.xlabel('X')
plt.ylabel('Y')
plt.xlim(0, 6*np.pi) | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Seaborn
Seaborn is a plotting package that enables many useful features for exploration. In fact, a lot of the functionality that we developed above can readily be handled with seaborn.
To begin, we will make the same plot that we created in matplotlib. | import seaborn as sns
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y, lw = 2)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_xlim(0, 6*np.pi) | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
These plots look identical, but it is possible to change the style with seaborn.
seaborn has 5 style presets: darkgrid, whitegrid, dark, white, and ticks. You can change the preset using the following:
sns.set_style("whitegrid")
which will change the output for all subsequent plots. Note - if you want to change the ... | sns.set_style( # complete
# complete | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
The folks behind seaborn have thought a lot about color palettes, which is a good thing. Remember - the choice of color for plots is one of the most essential aspects of visualization. A poor choice of colors can easily mask interesting patterns or suggest structure that is not real. To learn more about what is availab... | # default color palette
current_palette = sns.color_palette()
sns.palplot(current_palette) | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
which we will now change to colorblind, which is clearer to those that are colorblind. | # set palette to colorblind
sns.set_palette("colorblind")
current_palette = sns.color_palette()
sns.palplot(current_palette) | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Now that we have covered the basics of seaborn (and the above examples truly only scratch the surface of what is possible), we will explore the power of seaborn for higher dimension data sets. We will load the famous Iris data set, which measures 4 different features of 3 different types of Iris flowers. There are 150 ... | iris = sns.load_dataset("iris")
iris | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Now that we have a sense of the data structure, it is useful to examine the distribution of features. Above, we went to great pains to produce histograms, KDEs, and rug plots. seaborn handles all of that effortlessly with the distplot function.
Problem 3b
Plot the distribution of petal lengths for the Iris data set. | # note - hist, kde, and rug all set to True, set to False to turn them off
with sns.axes_style("dark"):
sns.distplot(iris['petal_length'], bins=20, hist=True, kde=True, rug=True) | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Of course, this data set lives in a 4D space, so plotting more than univariate distributions is important (and as we will see tomorrow this is particularly useful for visualizing classification results). Fortunately, seaborn makes it very easy to produce handy summary plots.
At this point, we are familiar with basic s... | plt.scatter( # complete | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Of course, when there are many many data points, scatter plots become difficult to interpret. As in the example below: | with sns.axes_style("darkgrid"):
xexample = np.random.normal(loc = 0.2, scale = 1.1, size = 10000)
yexample = np.random.normal(loc = -0.1, scale = 0.9, size = 10000)
plt.scatter(xexample, yexample) | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Here, we see that there are many points, clustered about the origin, but we have no sense of the underlying density of the distribution. 2D histograms, such as plt.hist2d(), can alleviate this problem. I prefer to use plt.hexbin() which is a little easier on the eyes (though note - these histograms are just as subject ... | # hexbin w/ bins = "log" returns the log of counts/bin
# mincnt = 1 displays only hexpix with at least 1 source present
with sns.axes_style("darkgrid"):
plt.hexbin(xexample, yexample, bins = "log", cmap = "viridis", mincnt = 1)
plt.colorbar() | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
While the above plot provides a significant improvement over the scatter plot by providing a better sense of the density near the center of the distribution, the binedge effects are clearly present. An even better solution, like before, is a density estimate, which is easily built into seaborn via the kdeplot function. | with sns.axes_style("darkgrid"):
sns.kdeplot(xexample, yexample,shade=False) | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
This plot is much more appealing (and informative) than the previous two. For the first time we can clearly see that the distribution is not actually centered on the origin. Now we will move back to the Iris data set.
Suppose we want to see univariate distributions in addition to the scatter plot? This is certainly po... | sns.jointplot(x=iris['petal_length'], y=iris['petal_width']) | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
But! Histograms and scatter plots can be problematic as we have discussed many times before.
Problem 3d
Re-create the plot above but set kind='kde' to produce density estimates of the distributions. | sns.jointplot( # complete | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
That is much nicer than what was presented above. However - we still have a problem in that our data live in 4D, but we are (mostly) limited to 2D projections of that data. One way around this is via the seaborn version of a pairplot, which plots the distribution of every variable in the data set against each other. (H... | sns.pairplot(iris[["sepal_length", "sepal_width", "petal_length", "petal_width"]]) | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
For data sets where we have classification labels, we can even color the various points using the hue option, and produce KDEs along the diagonal with diag_type = 'kde'. | sns.pairplot(iris, vars = ["sepal_length", "sepal_width", "petal_length", "petal_width"],
hue = "species", diag_kind = 'kde') | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
Even better - there is an option to create a PairGrid which allows fine tuned control of the data as displayed above, below, and along the diagonal. In this way it becomes possible to avoid having symmetric redundancy, which is not all that informative. In the example below, we will show scatter plots and contour plots... | g = sns.PairGrid(iris, vars = ["sepal_length", "sepal_width", "petal_length", "petal_width"],
hue = "species", diag_sharey=False)
g.map_lower(sns.kdeplot)
g.map_upper(plt.scatter, edgecolor='white')
g.map_diag(sns.kdeplot, lw=3) | Sessions/Session10/Day0/TooBriefVisualization.ipynb | LSSTC-DSFP/LSSTC-DSFP-Sessions | mit |
With this many layers, it's going to take a lot of iterations for this network to learn. By the time you're done training these 800 batches, your final test and validation accuracies probably won't be much better than 10%. (It will be different each time, but will most likely be less than 15%.)
Using batch normalizatio... | def fully_connected(prev_layer, num_units, is_training):
"""
Create a fully connectd layer with the given layer as input and the given number of neurons.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param num_units: int
The size of the layer. That is, the... | batch-norm/Batch_Normalization_Exercises.ipynb | nwhidden/ND101-Deep-Learning | mit |
TODO: Modify conv_layer to add batch normalization to the convolutional layers it creates. Feel free to change the function's parameters if it helps. | def conv_layer(prev_layer, layer_depth, is_training):
"""
Create a convolutional layer with the given layer as input.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param layer_depth: int
We'll set the strides and number of feature maps based on the layer's... | batch-norm/Batch_Normalization_Exercises.ipynb | nwhidden/ND101-Deep-Learning | mit |
TODO: Edit the train function to support batch normalization. You'll need to make sure the network knows whether or not it is training, and you'll need to make sure it updates and uses its population statistics correctly. | def train(num_batches, batch_size, learning_rate):
# Build placeholders for the input samples and labels
inputs = tf.placeholder(tf.float32, [None, 28, 28, 1])
labels = tf.placeholder(tf.float32, [None, 10])
# training boolean
is_training = tf.placeholder(tf.bool)
# Feed the inputs in... | batch-norm/Batch_Normalization_Exercises.ipynb | nwhidden/ND101-Deep-Learning | mit |
With batch normalization, you should now get an accuracy over 90%. Notice also the last line of the output: Accuracy on 100 samples. If this value is low while everything else looks good, that means you did not implement batch normalization correctly. Specifically, it means you either did not calculate the population m... | def fully_connected(prev_layer, num_units):
"""
Create a fully connectd layer with the given layer as input and the given number of neurons.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param num_units: int
The size of the layer. That is, the number of un... | batch-norm/Batch_Normalization_Exercises.ipynb | nwhidden/ND101-Deep-Learning | mit |
TODO: Modify conv_layer to add batch normalization to the fully connected layers it creates. Feel free to change the function's parameters if it helps.
Note: Unlike in the previous example that used tf.layers, adding batch normalization to these convolutional layers does require some slight differences to what you did ... | def conv_layer(prev_layer, layer_depth):
"""
Create a convolutional layer with the given layer as input.
:param prev_layer: Tensor
The Tensor that acts as input into this layer
:param layer_depth: int
We'll set the strides and number of feature maps based on the layer's depth in the... | batch-norm/Batch_Normalization_Exercises.ipynb | nwhidden/ND101-Deep-Learning | mit |
TODO: Edit the train function to support batch normalization. You'll need to make sure the network knows whether or not it is training. | def train(num_batches, batch_size, learning_rate):
# Build placeholders for the input samples and labels
inputs = tf.placeholder(tf.float32, [None, 28, 28, 1])
labels = tf.placeholder(tf.float32, [None, 10])
# Feed the inputs into a series of 20 convolutional layers
layer = inputs
for lay... | batch-norm/Batch_Normalization_Exercises.ipynb | nwhidden/ND101-Deep-Learning | mit |
Classifiers and Regressors
Pulsar stars | col_names = ["Mean of the integrated profile","Standard deviation of the integrated profile",
"Excess kurtosis of the integrated profile",
"Skewness of the integrated profile",
"Mean of the DM-SNR curve",
"Standard deviation of the DM-SNR curve",
"Excess kurtosis of the DM-SNR curve",
"Skewness of the DM-SNR curve",
"C... | pulsar_stars.ipynb | searchs/bigdatabox | mit |
Mean of the integrated profile.
Standard deviation of the integrated profile.
Excess kurtosis of the integrated profile.
Skewness of the integrated profile.
Mean of the DM-SNR curve.
Standard deviation of the DM-SNR curve.
Excess kurtosis of the DM-SNR curve.
Skewness of the DM-SNR curve.
Class | df.head(3)
# df.info()
len(df)
from sklearn.linear_model import LogisticRegression
X = df.iloc[:, 0:8]
y = df.iloc[:,8]
def clf_model(model):
clf = model
scores = cross_val_score(clf, X, y)
print(f"Scores: {scores}")
print(f"Mean Score: {scores.mean()}")
clf_model(LogisticRegression())
from s... | pulsar_stars.ipynb | searchs/bigdatabox | mit |
Customer Churn | churnDF = pd.read_csv("CHURN.csv")
churnDF.Churn.head(3)
churnDF['Churn'] = churnDF['Churn']. \
replace(to_replace=['No', 'Yes'], value=[0,1])
churnDF.Churn.head()
len(churnDF.columns)
X = churnDF.iloc[:, 0:20]
y = churnDF.iloc[:,20]
X = pd.get_dummies(X)
def clf_models(model, cv=3):
clf = model
sco... | pulsar_stars.ipynb | searchs/bigdatabox | mit |
Conv2DTranspose
[convolutional.Conv2DTranspose.0] 4 3x3 filters on 4x4x2 input, strides=(1,1), padding='valid', data_format='channels_last', activation='linear', use_bias=False | data_in_shape = (4, 4, 2)
conv = Conv2DTranspose(4, (3,3), strides=(1,1),
padding='valid', data_format='channels_last',
activation='linear', use_bias=False)
layer_0 = Input(shape=data_in_shape)
layer_1 = conv(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set ... | notebooks/layers/convolutional/Conv2DTranspose.ipynb | transcranial/keras-js | mit |
[convolutional.Conv2DTranspose.1] 4 3x3 filters on 4x4x2 input, strides=(1,1), padding='valid', data_format='channels_last', activation='linear', use_bias=True | data_in_shape = (4, 4, 2)
conv = Conv2DTranspose(4, (3,3), strides=(1,1),
padding='valid', data_format='channels_last',
activation='linear', use_bias=True)
layer_0 = Input(shape=data_in_shape)
layer_1 = conv(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set w... | notebooks/layers/convolutional/Conv2DTranspose.ipynb | transcranial/keras-js | mit |
[convolutional.Conv2DTranspose.2] 4 3x3 filters on 4x4x2 input, strides=(2,2), padding='valid', data_format='channels_last', activation='relu', use_bias=True | data_in_shape = (4, 4, 2)
conv = Conv2DTranspose(4, (3,3), strides=(2,2),
padding='valid', data_format='channels_last',
activation='relu', use_bias=True)
layer_0 = Input(shape=data_in_shape)
layer_1 = conv(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set wei... | notebooks/layers/convolutional/Conv2DTranspose.ipynb | transcranial/keras-js | mit |
[convolutional.Conv2DTranspose.3] 4 3x3 filters on 4x4x2 input, strides=(1,1), padding='same', data_format='channels_last', activation='relu', use_bias=True | data_in_shape = (4, 4, 2)
conv = Conv2DTranspose(4, (3,3), strides=(1,1),
padding='same', data_format='channels_last',
activation='relu', use_bias=True)
layer_0 = Input(shape=data_in_shape)
layer_1 = conv(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weig... | notebooks/layers/convolutional/Conv2DTranspose.ipynb | transcranial/keras-js | mit |
[convolutional.Conv2DTranspose.4] 5 3x3 filters on 4x4x2 input, strides=(2,2), padding='same', data_format='channels_last', activation='relu', use_bias=True | data_in_shape = (4, 4, 2)
conv = Conv2DTranspose(5, (3,3), strides=(2,2),
padding='same', data_format='channels_last',
activation='relu', use_bias=True)
layer_0 = Input(shape=data_in_shape)
layer_1 = conv(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weig... | notebooks/layers/convolutional/Conv2DTranspose.ipynb | transcranial/keras-js | mit |
[convolutional.Conv2DTranspose.5] 3 2x3 filters on 4x4x2 input, strides=(1,1), padding='same', data_format='channels_last', activation='relu', use_bias=True | data_in_shape = (4, 4, 2)
conv = Conv2DTranspose(3, (2,3), strides=(1,1),
padding='same', data_format='channels_last',
activation='relu', use_bias=True)
layer_0 = Input(shape=data_in_shape)
layer_1 = conv(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weig... | notebooks/layers/convolutional/Conv2DTranspose.ipynb | transcranial/keras-js | mit |
export for Keras.js tests | import os
filename = '../../../test/data/layers/convolutional/Conv2DTranspose.json'
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
with open(filename, 'w') as f:
json.dump(DATA, f)
print(json.dumps(DATA)) | notebooks/layers/convolutional/Conv2DTranspose.ipynb | transcranial/keras-js | mit |
The dataset contains, for each applicant:
- income (in the Income column),
- the number of children (in the Num_Children column),
- whether the applicant owns a car (in the Own_Car column, the value is 1 if the applicant owns a car, and is else 0), and
- whether the applicant owns a home (in the Own_Housing column, the... | from sklearn import tree
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt
# Train a model and make predictions
model_baseline = tree.DecisionTreeClassifier(random_state=0, max_depth=3)
model_baseline.fit(X_train, y_train)
preds_baseline = model_baseline.predict(X_tes... | notebooks/ethics/raw/ex4.ipynb | Kaggle/learntools | apache-2.0 |
The confusion matrices above show how the model performs on some test data. We also print additional information (calculated from the confusion matrices) to assess fairness of the model. For instance,
- The model approved 38246 people for a credit card. Of these individuals, 8028 belonged to Group A, and 30218 belonged... | # Check your answer (Run this code cell to get credit!)
q_1.check() | notebooks/ethics/raw/ex4.ipynb | Kaggle/learntools | apache-2.0 |
Run the next code cell without changes to visualize the model. | def visualize_model(model, feature_names, class_names=["Deny", "Approve"], impurity=False):
plot_list = tree.plot_tree(model, feature_names=feature_names, class_names=class_names, impurity=impurity)
[process_plot_item(item) for item in plot_list]
def process_plot_item(item):
split_string = item.get_text().... | notebooks/ethics/raw/ex4.ipynb | Kaggle/learntools | apache-2.0 |
The flowchart shows how the model makes decisions:
- Group <= 0.5 checks what group the applicant belongs to: if the applicant belongs to Group A, then Group <= 0.5 is true.
- Entries like Income <= 80210.5 check the applicant's income.
To follow the flow chart, we start at the top and trace a path depending o... | # Check your answer (Run this code cell to get credit!)
q_2.check() | notebooks/ethics/raw/ex4.ipynb | Kaggle/learntools | apache-2.0 |
Next, you decide to remove group membership from the training data and train a new model. Do you think this will make the model treat the groups more equally?
Run the next code cell to see how this new group unaware model performs. | # Create new dataset with gender removed
X_train_unaware = X_train.drop(["Group"],axis=1)
X_test_unaware = X_test.drop(["Group"],axis=1)
# Train new model on new dataset
model_unaware = tree.DecisionTreeClassifier(random_state=0, max_depth=3)
model_unaware.fit(X_train_unaware, y_train)
# Evaluate the model
preds_unaw... | notebooks/ethics/raw/ex4.ipynb | Kaggle/learntools | apache-2.0 |
3) Varieties of fairness, part 2
How does this model compare to the first model you trained, when you consider demographic parity, equal accuracy, and equal opportunity? Once you have an answer, run the next code cell. | # Check your answer (Run this code cell to get credit!)
q_3.check() | notebooks/ethics/raw/ex4.ipynb | Kaggle/learntools | apache-2.0 |
You decide to train a third potential model, this time with the goal of having each group have even representation in the group of approved applicants. (This is an implementation of group thresholds, which you can optionally read more about here.)
Run the next code cell without changes to evaluate this new model. | # Change the value of zero_threshold to hit the objective
zero_threshold = 0.11
one_threshold = 0.99
# Evaluate the model
test_probs = model_unaware.predict_proba(X_test_unaware)[:,1]
preds_approval = (((test_probs>zero_threshold)*1)*[X_test["Group"]==0] + ((test_probs>one_threshold)*1)*[X_test["Group"]==1])[0]
get_st... | notebooks/ethics/raw/ex4.ipynb | Kaggle/learntools | apache-2.0 |
4) Varieties of fairness, part 3
How does this final model compare to the previous models, when you consider demographic parity, equal accuracy, and equal opportunity? | # Check your answer (Run this code cell to get credit!)
q_4.check() | notebooks/ethics/raw/ex4.ipynb | Kaggle/learntools | apache-2.0 |
<H1>Polynomial fit</H1> | # generate some data
np.random.seed(2)
xdata = np.random.normal(3.0, 1.0, 100)
ydata = np.random.normal(50.0, 30.0, 100) / xdata
plt.plot(xdata, ydata, 'ko',ms=2);
# lets fit to a polynomial function of degree 8
# and plot all together
f = np.poly1d( np.polyfit(xdata, ydata, 8) )
x = np.linspace(np.min(xdata), np.ma... | Optimization/Polynomial regression.ipynb | JoseGuzman/myIPythonNotebooks | gpl-2.0 |
The r2_score is not very good and the large degree of the polynomial suggest an overfitting. The r2_score alone
cannot not say which fitting is the best. | # find the best polynomial
mypoly = dict()
for n in range(1, 10):
f = np.poly1d( np.polyfit(xdata, ydata, n) )
mypoly[n] = r2_score(ydata, f(xdata))
print 'Pol. deg %d -> %f' %(n, mypoly[n]) | Optimization/Polynomial regression.ipynb | JoseGuzman/myIPythonNotebooks | gpl-2.0 |
<H2>Trial and test method</H2>
To avoid overfitting, we'll split the data in two - 80% of it will be used for "training" our model, and the other 20% for testing it. | #we'll select 80% of the data to train
xtrain = xdata[:80]
ytrain = ydata[:80]
xtest = xdata[80:]
ytest = ydata[80:]
print(len(xtrain), len(xtest))
plt.plot(xtrain, ytrain, 'ro', ms=2)
plt.xlim(0,7), plt.ylim(0,200)
plt.title('Train');
plt.plot(xtest, ytest, 'bo', ms=2)
plt.xlim(0,7), plt.ylim(0,200)
plt.title('Test'... | Optimization/Polynomial regression.ipynb | JoseGuzman/myIPythonNotebooks | gpl-2.0 |
the r2_score value of the test value is telling us that this fit is not very good | # let's compute train and test for all polynomial
# find the best polynomial
r2_test, r2_train = list(), list()
polydeg = range(1,15)
for n in polydeg:
f = np.poly1d( np.polyfit(xtrain, ytrain, n) )
r2train = r2_score(ytrain, f(xtrain))
r2_train.append(r2train)
r2test = r2_score(ytest, f(xtest))
r2... | Optimization/Polynomial regression.ipynb | JoseGuzman/myIPythonNotebooks | gpl-2.0 |
Looking at the r2_scores of the test value, we can resolve that a fitting with a polynomial degree of six is the best | plt.plot(polydeg, r2_train, color='gray')
plt.bar(polydeg, r2_test, color='red', alpha=.4)
plt.xlim(1, 15);
# the best is to fit with a polynomial of degree 6
f = np.poly1d(np.polyfit(xdata,ydata,6))
plt.plot(xdata,ydata, 'ko', ms=2)
plt.plot(x,f(x),'red'); | Optimization/Polynomial regression.ipynb | JoseGuzman/myIPythonNotebooks | gpl-2.0 |
Prepare Data | def generate_sequence(seq_len):
xs = np.random.random(seq_len)
ys = np.array([0 if x < 2.5 else 1 for x in np.cumsum(xs).tolist()])
return xs, ys
X, Y = generate_sequence(SEQ_LENGTH)
print(X)
print(Y)
def generate_data(seq_len, num_seqs):
xseq, yseq = [], []
for i in range(num_seqs):
X, Y ... | src/pytorch/10-cumsum-prediction.ipynb | sujitpal/polydlot | apache-2.0 |
Define Network
The sequence length for the input and output sequences are the same size. Our network follows the model built (using Keras) in the book. Unlike the typical encoder-decoder LSTM architecture that is used for most seq2seq problems, here we have a single LSTM followed by a FCN layer at each timestep of its ... | class CumSumPredictor(nn.Module):
def __init__(self, seq_len, input_dim, hidden_dim, output_dim):
super(CumSumPredictor, self).__init__()
self.seq_len = seq_len
self.hidden_dim = hidden_dim
self.output_dim = output_dim
# network layers
self.enc_lstm = nn.LSTM(inp... | src/pytorch/10-cumsum-prediction.ipynb | sujitpal/polydlot | apache-2.0 |
Train Network | def compute_accuracy(pred_var, true_var):
if torch.cuda.is_available():
ypred = pred_var.cpu().data.numpy()
ytrue = true_var.cpu().data.numpy()
else:
ypred = pred_var.data.numpy()
ytrue = true_var.data.numpy()
pred_nums, true_nums = [], []
for i in range(pred_var.size(0))... | src/pytorch/10-cumsum-prediction.ipynb | sujitpal/polydlot | apache-2.0 |
Evaluate Network | saved_model = CumSumPredictor(SEQ_LENGTH, EMBED_SIZE, 50, 2)
saved_model.load_state_dict(torch.load(MODEL_FILE.format(NUM_EPOCHS)))
if torch.cuda.is_available():
saved_model.cuda()
ylabels, ypreds = [], []
num_test_batches = Xtest.shape[0] // BATCH_SIZE
for bid in range(num_test_batches):
Xbatch_data = Xtest[b... | src/pytorch/10-cumsum-prediction.ipynb | sujitpal/polydlot | apache-2.0 |
Effect of the Bottom-SCC optimisation on semi-deterministic automata
The orange states below form deterministic bottom SCCs. After processing by Seminator, they are both in the 1st (violet) and 2nd (green) component. Simplifications cannot merge these duplicates as one is accepting and one is not. In fact, we do not ne... | def example(**opts):
in_a = spot.translate("(FGp2 R !p2) | GFp1")
in_a.highlight_states([3,4], 2).set_name("input")
# Note: the pure=True option disables all optimizations that are usually on by default.
out_a = seminator(in_a, pure=True, postprocess=False, highlight=True, **opts)
out_a.set_name("ou... | notebooks/bSCC.ipynb | mklokocka/seminator | gpl-3.0 |
Enabling the bottom-SCC optimization simplifies the output automata as follows: | example(bscc_avoid=True) | notebooks/bSCC.ipynb | mklokocka/seminator | gpl-3.0 |
Cut-deterministic automata
The same idea can be applied to cut-deterministic automata. Removing the states 3 and 4 from the fist part of the cut-deterministic automaton would remove state ${3}$ and would merge the states ${1,3,4}$ and ${1,3}$. | example(cut_det=True)
example(cut_det=True, bscc_avoid=True) | notebooks/bSCC.ipynb | mklokocka/seminator | gpl-3.0 |
Exension to semi-deterministic SCCs
We can avoid more than bottom SCC. In fact, we can avoid all SCCs that are already good for semi-deterministic automata (semi-deterministic SCC). SCC $C$ is semi-deterministic if $C$ and all successors of $C$ are deterministic. This is ilustrated on the following example and states 1... | def example2(**opts):
in_a = spot.translate('G((((a & b) | (!a & !b)) & (GF!b U !c)) | (((!a & b) | (a & !b)) & (FGb R c)))')
spot.highlight_nondet_states(in_a, 1)
in_a.set_name("input")
options = { "cut_det": True, "highlight": True, "jobs": ViaTGBA, "skip_levels": True, "pure": True, **opts}
out_a... | notebooks/bSCC.ipynb | mklokocka/seminator | gpl-3.0 |
Reusing the semi-deterministic components with TGBA acceptance
In the previous example we have saved several states by not including the semi-deterministic components in the 1st part of the result. However, we still got 6 (and 5 after postprocessing) states out of the 3 deterministic states $1, 5$, and $6$. This can be... | example2(powerset_on_cut=True, reuse_deterministic=True) | notebooks/bSCC.ipynb | mklokocka/seminator | gpl-3.0 |
1. Connect girder client and set parameters | APIURL = 'http://candygram.neurology.emory.edu:8080/api/v1/'
SOURCE_SLIDE_ID = '5d5d6910bd4404c6b1f3d893'
POST_SLIDE_ID = '5d586d76bd4404c6b1f286ae'
gc = girder_client.GirderClient(apiUrl=APIURL)
# gc.authenticate(interactive=True)
gc.authenticate(apiKey='kri19nTIGOkWH01TbzRqfohaaDWb6kPecRqGmemb')
# get and parse sli... | docs/examples/polygon_merger_using_rtree.ipynb | DigitalSlideArchive/HistomicsTK | apache-2.0 |
2. Polygon merger
The Polygon_merger_v2() is the top level function for performing the merging. | print(Polygon_merger_v2.__doc__)
print(Polygon_merger_v2.__init__.__doc__) | docs/examples/polygon_merger_using_rtree.ipynb | DigitalSlideArchive/HistomicsTK | apache-2.0 |
Required arguments for initialization
The only required argument is a dataframe of contours merge. | contours_df.head() | docs/examples/polygon_merger_using_rtree.ipynb | DigitalSlideArchive/HistomicsTK | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.