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
The above output for `constructed_list` may seem odd. Referring to the documentation, we see that the argument to the type constructor is an _iterable_, which according to the documentation is "An object capable of returning its members one at a time." In our construtor statement above``` Using the type constructorcons...
constructed_list_int = list(123) constructed_list_str = list('123') constructed_list_str
_____no_output_____
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
Lists in Python are:* mutable - the list and list items can be changed* ordered - list items keep the same "place" in the list_Ordered_ here does not mean sorted. The list below is printed with the numbers in the order we added them to the list, not in numeric order:
ordered = [3, 2, 7, 1, 19, 0] ordered # There is a 'sort' method for sorting list items as needed: ordered.sort() ordered
_____no_output_____
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
Info on additional list methods is available at Because lists are ordered, it is possible to access list items by referencing their positions. Note that the position of the first item in a list is 0 (zero), not 1!
string_list = ['apples', 'oranges', 'pears', 'grapes', 'pineapples'] string_list[0] # We can use positions to 'slice' or select sections of a list: string_list[3:] # start at index '3' and continue to the end string_list[:3] # start at index '0' and go up to, but don't include index '3' string_list...
_____no_output_____
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
Bayesian Optimization[Bayesian optimization](https://en.wikipedia.org/wiki/Bayesian_optimization) is a powerful strategy for minimizing (or maximizing) objective functions that are costly to evaluate. It is an important component of [automated machine learning](https://en.wikipedia.org/wiki/Automated_machine_learning...
import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import torch import torch.autograd as autograd import torch.optim as optim from torch.distributions import constraints, transform_to import pyro import pyro.contrib.gp as gp assert pyro.__version__.startswith('1.5.2') pyro.set_rng_seed(1)
_____no_output_____
Apache-2.0
tutorial/source/bo.ipynb
FlorianWilhelm/pyro
Define an objective functionFor the purposes of demonstration, the objective function we are going to consider is the [Forrester et al. (2008) function](https://www.sfu.ca/~ssurjano/forretal08.html):$$f(x) = (6x-2)^2 \sin(12x-4), \quad x\in [0, 1].$$This function has both a local minimum and a global minimum. The glob...
def f(x): return (6 * x - 2)**2 * torch.sin(12 * x - 4)
_____no_output_____
Apache-2.0
tutorial/source/bo.ipynb
FlorianWilhelm/pyro
Let's begin by plotting $f$.
x = torch.linspace(0, 1) plt.figure(figsize=(8, 4)) plt.plot(x.numpy(), f(x).numpy()) plt.show()
_____no_output_____
Apache-2.0
tutorial/source/bo.ipynb
FlorianWilhelm/pyro
Setting a Gaussian Process prior [Gaussian processes](https://en.wikipedia.org/wiki/Gaussian_process) are a popular choice for a function priors due to their power and flexibility. The core of a Gaussian Process is its covariance function $k$, which governs the similarity of $f(x)$ for pairs of input points. Here we w...
# initialize the model with four input points: 0.0, 0.33, 0.66, 1.0 X = torch.tensor([0.0, 0.33, 0.66, 1.0]) y = f(X) gpmodel = gp.models.GPRegression(X, y, gp.kernels.Matern52(input_dim=1), noise=torch.tensor(0.1), jitter=1.0e-4)
_____no_output_____
Apache-2.0
tutorial/source/bo.ipynb
FlorianWilhelm/pyro
The following helper function `update_posterior` will take care of updating our `gpmodel` each time we evaluate $f$ at a new value $x$.
def update_posterior(x_new): y = f(x_new) # evaluate f at new point. X = torch.cat([gpmodel.X, x_new]) # incorporate new evaluation y = torch.cat([gpmodel.y, y]) gpmodel.set_data(X, y) # optimize the GP hyperparameters using Adam with lr=0.001 optimizer = torch.optim.Adam(gpmodel.parameter...
_____no_output_____
Apache-2.0
tutorial/source/bo.ipynb
FlorianWilhelm/pyro
Define an acquisition function There are many reasonable options for the acquisition function (see references [1] and [2] for a list of popular choices and a discussion of their properties). Here we will use one that is 'simple to implement and interpret,' namely the 'Lower Confidence Bound' acquisition function. It i...
def lower_confidence_bound(x, kappa=2): mu, variance = gpmodel(x, full_cov=False, noiseless=False) sigma = variance.sqrt() return mu - kappa * sigma
_____no_output_____
Apache-2.0
tutorial/source/bo.ipynb
FlorianWilhelm/pyro
The final component we need is a way to find (approximate) minimizing points $x_{\rm min}$ of the acquisition function. There are several ways to proceed, including gradient-based and non-gradient-based techniques. Here we will follow the gradient-based approach. One of the possible drawbacks of gradient descent method...
def find_a_candidate(x_init, lower_bound=0, upper_bound=1): # transform x to an unconstrained domain constraint = constraints.interval(lower_bound, upper_bound) unconstrained_x_init = transform_to(constraint).inv(x_init) unconstrained_x = unconstrained_x_init.clone().detach().requires_grad_(True) mi...
_____no_output_____
Apache-2.0
tutorial/source/bo.ipynb
FlorianWilhelm/pyro
The inner loop of Bayesian OptimizationWith the various helper functions defined above, we can now encapsulate the main logic of a single step of Bayesian Optimization in the function `next_x`:
def next_x(lower_bound=0, upper_bound=1, num_candidates=5): candidates = [] values = [] x_init = gpmodel.X[-1:] for i in range(num_candidates): x = find_a_candidate(x_init, lower_bound, upper_bound) y = lower_confidence_bound(x) candidates.append(x) values.append(y) ...
_____no_output_____
Apache-2.0
tutorial/source/bo.ipynb
FlorianWilhelm/pyro
Running the algorithm To illustrate how Bayesian Optimization works, we make a convenient plotting function that will help us visualize our algorithm's progress.
def plot(gs, xmin, xlabel=None, with_title=True): xlabel = "xmin" if xlabel is None else "x{}".format(xlabel) Xnew = torch.linspace(-0.1, 1.1) ax1 = plt.subplot(gs[0]) ax1.plot(gpmodel.X.numpy(), gpmodel.y.numpy(), "kx") # plot all observed data with torch.no_grad(): loc, var = gpmodel(Xnew...
_____no_output_____
Apache-2.0
tutorial/source/bo.ipynb
FlorianWilhelm/pyro
Our surrogate model `gpmodel` already has 4 function evaluations at its disposal; however, we have yet to optimize the GP hyperparameters. So we do that first. Then in a loop we call the `next_x` and `update_posterior` functions repeatedly. The following plot illustrates how Gaussian Process posteriors and the correspo...
plt.figure(figsize=(12, 30)) outer_gs = gridspec.GridSpec(5, 2) optimizer = torch.optim.Adam(gpmodel.parameters(), lr=0.001) gp.util.train(gpmodel, optimizer) for i in range(8): xmin = next_x() gs = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=outer_gs[i]) plot(gs, xmin, xlabel=i+1, with_title=(i % ...
_____no_output_____
Apache-2.0
tutorial/source/bo.ipynb
FlorianWilhelm/pyro
UMAP This script generates UMAP representations from spectrograms (previously generated). Installing and loading libraries
import os import pandas as pd import sys import numpy as np from pandas.core.common import flatten import pickle import umap from pathlib import Path import datetime import scipy import matplotlib.pyplot as plt import seaborn as sns import matplotlib import librosa.display from scipy.spatial.distance import pdist, squa...
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
Setting constants Setting project, input and output folders.
wd = os.getcwd() DATA = os.path.join(os.path.sep, str(Path(wd).parents[0]), "data", "processed") FIGURES = os.path.join(os.path.sep, str(Path(wd).parents[0]), "reports", "figures") DF_DICT = {} for dftype in ['full', 'reduced', 'balanced']: DF_DICT[dftype] = os.path.join(os.path.sep, DATA, "df_focal_"+dftype+".pk...
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
UMAP projection Choose dataset
#dftype='full' dftype='reduced' #dftype='balanced' spec_df = pd.read_pickle(DF_DICT[dftype]) labels = spec_df.call_lable.values spec_df.shape
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
Choose feature
specs = spec_df.spectrograms.copy() specs = [calc_zscore(x) for x in specs] data = create_padded_data(specs)
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
Run UMAP
# 3D embedding_filename = os.path.join(os.path.sep, DATA,'basic_UMAP_3D_'+dftype+'_default_params.csv') print(embedding_filename) if (LOAD_EXISTING and os.path.isfile(embedding_filename)): embedding = np.loadtxt(embedding_filename, delimiter=";") print("File already exists") else: reducer = umap.UMAP(n_com...
/home/mthomas/Documents/MPI_work/projects/meerkat/meerkat_umap_pv/data/processed/basic_UMAP_2D_reduced_default_params.csv File already exists
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
Visualization
pal="Set2"
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
2D Plots
if OVERWRITE_FIGURES: outname = os.path.join(os.path.sep, FIGURES, 'UMAP_2D_plot_'+dftype+'_nolegend.jpg') else: outname=None print(outname) umap_2Dplot(embedding2D[:,0], embedding2D[:,1], labels, pal, outname=outname, showlegend=False)
None
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
3D Plot Matplotlib
if OVERWRITE_FIGURES: outname = os.path.join(os.path.sep, FIGURES, 'UMAP_3D_plot_'+dftype+'_nolegend.jpg') else: outname=None print(outname) mara_3Dplot(embedding[:,0], embedding[:,1], embedding[:,2], labels, pal, outname, showleg...
None
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
PlotlyInteractive viz in plotly (though without sound or spectrogram)
#plotly_viz(embedding[:,0], # embedding[:,1], # embedding[:,2], # labels, # pal)
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
Embedding evaluation Evaluate the embedding based on calltype labels of nearest neighbors.
from evaluation_functions import nn, sil # produce nearest neighbor statistics nn_stats = nn(embedding, np.asarray(labels), k=5)
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
Calculate metrics
print("Log final metric (unweighted):",nn_stats.get_S()) print("Abs final metric (unweighted):",nn_stats.get_Snorm()) print(nn_stats.knn_accuracy()) if OVERWRITE_FIGURES: outname = os.path.join(os.path.sep, FIGURES, 'heatS_UMAP_'+dftype+'.png') else: outname=None print(outname) nn_stats.plot_heat_S(outname=ou...
/home/mthomas/Documents/MPI_work/projects/meerkat/meerkat_umap_pv/reports/figures/heatfold_UMAP_reduced.png
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
Within vs. outside distances
from evaluation_functions import plot_within_without if OVERWRITE_FIGURES: outname = os.path.join(os.path.sep, FIGURES,"distanceswithinwithout_"+dftype+".png") else: outname=None print(outname) plot_within_without(embedding=embedding, labels=labels, outname=outname)
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
Silhouette Plot
sil_stats = sil(embedding, labels) if OVERWRITE_FIGURES: outname = os.path.join(os.path.sep, FIGURES, 'silplot_UMAP_'+dftype+'.png') else: outname=None print(outname) sil_stats.plot_sil(outname=outname) sil_stats.get_avrg_score()
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
How many dimensions? Evaluate, how many dimensions are best for the embedding.
specs = spec_df.spectrograms.copy() # normalize feature specs = [calc_zscore(x) for x in specs] # pad feature maxlen= np.max([spec.shape[1] for spec in specs]) flattened_specs = [pad_spectro(spec, maxlen).flatten() for spec in specs] data = np.asarray(flattened_specs) data.shape embeddings = {} for n_dims in range(1,...
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
Note that this is different than doing UMAP with n=10 components and then selection only the first x dimensions in UMAP space! Graph from embedding evaluation
if OVERWRITE_FIGURES: outname = os.path.join(os.path.sep,FIGURES,'simgraph_test.png') else: outname=None nn_stats.draw_simgraph(outname)
Graph saved at /home/mthomas/Documents/MPI_work/projects/meerkat/meerkat_umap_pv/reports/figures/simgraph_test.png
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
Resource: https://en.it1352.com/article/d096c1eadbb84c19b038eb9648153346.html Visualize example nearest neighbors
import random import scipy from sklearn.neighbors import NearestNeighbors knn=5 # Find k nearest neighbors nbrs = NearestNeighbors(metric='euclidean',n_neighbors=knn+1, algorithm='brute').fit(embedding) distances, indices = nbrs.kneighbors(embedding) # need to remove the first neighbor, because that is the datapoint i...
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
Visualize preprocessing steps
N_MELS = 40 MEL_BINS_REMOVED_UPPER = 5 MEL_BINS_REMOVED_LOWER = 5 # make plots calltypes = sorted(list(set(spec_df.call_lable.values))) fig = plt.figure(figsize=(10,6)) fig_name = 'preprocessing_examples_mara.png' fig.suptitle('Preprocessing steps', fontsize=16) k=1 # randomly choose 4 examples = spec_df.sample(n=6...
/home/mthomas/Documents/MPI_work/projects/meerkat/meerkat_umap_pv/reports/figures/preprocessing_examples_mara.png
MIT
notebooks/.ipynb_checkpoints/old_meerkat_UMAP_basic-checkpoint.ipynb
marathomas/meerkat_umap
There are 76,670 different agent ids in the training data.
import os import pickle import random import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline sns.set(rc={"figure.dpi":100, 'savefig.dpi':100}) sns.set_context('notebook') # Keys to the pickle objects CITY = 'city' LANE = 'lane' LANE_NORM = 'lane_norm' SCENE_IDX ...
_____no_output_____
MIT
exploratory_analysis/eda_scene.ipynb
and-le/cse-151b-argoverse
Size of training and test data
train_size = len([entry for entry in os.scandir(train_path)]) test_size = len([entry for entry in os.scandir(test_path)]) print(f"Number of training samples = {train_size}") print(f"Number of test samples = {test_size}")
Number of training samples = 205942 Number of test samples = 3200
MIT
exploratory_analysis/eda_scene.ipynb
and-le/cse-151b-argoverse
Scene object
# Open directory containing pickle files with os.scandir(train_path) as entries: scene = None # Get the first pickle file entry = next(entries) # Open the first pickle file and store its data with open(entry, "rb") as file: scene = pickle.load(file) # Look at key-value pairs print('Sc...
Scene object: city : <class 'str'> lane : shape = (72, 3) lane_norm : shape = (72, 3) scene_idx : <class 'int'> agent_id : <class 'str'> car_mask : shape = (60, 1) p_in : shape = (60, 19, 2) v_in : shape = (60, 19, 2) p_out : shape = (60, 30, 2) v_out : shape = (60, 30, 2) track_id : shape = (60, 30, 1)
MIT
exploratory_analysis/eda_scene.ipynb
and-le/cse-151b-argoverse
Scene Analysis
random.seed(1) def lane_centerline(scene): lane = scene[LANE] lane_norm = scene[LANE_NORM] fig, (ax1) = plt.subplots(nrows=1, ncols=1, figsize=(5, 5)) ax1.quiver(lane[:, 0], lane[:, 1], lane_norm[:, 0], lane_norm[:, 1], color='gray') ax1.set_xlabel('x') ax1.set_ylabel('y') ax1.set_title...
_____no_output_____
MIT
exploratory_analysis/eda_scene.ipynb
and-le/cse-151b-argoverse
Basic Tensor operations and GradientTape.In this graded assignment, you will perform different tensor operations as well as use [GradientTape](https://www.tensorflow.org/api_docs/python/tf/GradientTape). These are important building blocks for the next parts of this course so it's important to master the basics. Let's...
import tensorflow as tf import numpy as np
_____no_output_____
Apache-2.0
TensorFlow Advanced Techniques Specialization/Course-2/Custom and Distributed Training with TensorFlow/Week-1/C2W1_Assignment.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Exercise 1 - [tf.constant]((https://www.tensorflow.org/api_docs/python/tf/constant))Creates a constant tensor from a tensor-like object.
# Convert NumPy array to Tensor using `tf.constant` def tf_constant(array): """ Args: array (numpy.ndarray): tensor-like array. Returns: tensorflow.python.framework.ops.EagerTensor: tensor. """ ### START CODE HERE ### tf_constant_array = tf.constant(array) ### END CODE HERE ...
_____no_output_____
Apache-2.0
TensorFlow Advanced Techniques Specialization/Course-2/Custom and Distributed Training with TensorFlow/Week-1/C2W1_Assignment.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Note that for future docstrings, the type `EagerTensor` will be used as a shortened version of `tensorflow.python.framework.ops.EagerTensor`. Exercise 2 - [tf.square](https://www.tensorflow.org/api_docs/python/tf/math/square)Computes the square of a tensor element-wise.
# Square the input tensor def tf_square(array): """ Args: array (numpy.ndarray): tensor-like array. Returns: EagerTensor: tensor. """ # make sure it's a tensor array = tf.constant(array) ### START CODE HERE ### tf_squared_array = tf.square(array) ### END CODE HE...
_____no_output_____
Apache-2.0
TensorFlow Advanced Techniques Specialization/Course-2/Custom and Distributed Training with TensorFlow/Week-1/C2W1_Assignment.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Exercise 3 - [tf.reshape](https://www.tensorflow.org/api_docs/python/tf/reshape)Reshapes a tensor.
# Reshape tensor into the given shape parameter def tf_reshape(array, shape): """ Args: array (EagerTensor): tensor to reshape. shape (tuple): desired shape. Returns: EagerTensor: reshaped tensor. """ # make sure it's a tensor array = tf.constant(array) ### START COD...
_____no_output_____
Apache-2.0
TensorFlow Advanced Techniques Specialization/Course-2/Custom and Distributed Training with TensorFlow/Week-1/C2W1_Assignment.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Exercise 4 - [tf.cast](https://www.tensorflow.org/api_docs/python/tf/cast)Casts a tensor to a new type.
# Cast tensor into the given dtype parameter def tf_cast(array, dtype): """ Args: array (EagerTensor): tensor to be casted. dtype (tensorflow.python.framework.dtypes.DType): desired new type. (Should be a TF dtype!) Returns: EagerTensor: casted tensor. """ # make sure it's a...
_____no_output_____
Apache-2.0
TensorFlow Advanced Techniques Specialization/Course-2/Custom and Distributed Training with TensorFlow/Week-1/C2W1_Assignment.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Exercise 5 - [tf.multiply](https://www.tensorflow.org/api_docs/python/tf/multiply)Returns an element-wise x * y.
# Multiply tensor1 and tensor2 def tf_multiply(tensor1, tensor2): """ Args: tensor1 (EagerTensor): a tensor. tensor2 (EagerTensor): another tensor. Returns: EagerTensor: resulting tensor. """ # make sure these are tensors tensor1 = tf.constant(tensor1) tensor2 = tf.c...
_____no_output_____
Apache-2.0
TensorFlow Advanced Techniques Specialization/Course-2/Custom and Distributed Training with TensorFlow/Week-1/C2W1_Assignment.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Exercise 6 - [tf.add](https://www.tensorflow.org/api_docs/python/tf/add)Returns x + y element-wise.
# Add tensor1 and tensor2 def tf_add(tensor1, tensor2): """ Args: tensor1 (EagerTensor): a tensor. tensor2 (EagerTensor): another tensor. Returns: EagerTensor: resulting tensor. """ # make sure these are tensors tensor1 = tf.constant(tensor1) tensor2 = tf.constant(te...
_____no_output_____
Apache-2.0
TensorFlow Advanced Techniques Specialization/Course-2/Custom and Distributed Training with TensorFlow/Week-1/C2W1_Assignment.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Exercise 7 - Gradient TapeImplement the function `tf_gradient_tape` by replacing the instances of `None` in the code below. The instructions are given in the code comments.You can review the [docs](https://www.tensorflow.org/api_docs/python/tf/GradientTape) or revisit the lectures to complete this task.
def tf_gradient_tape(x): """ Args: x (EagerTensor): a tensor. Returns: EagerTensor: Derivative of z with respect to the input tensor x. """ with tf.GradientTape() as t: ### START CODE HERE ### # Record the actions performed on tensor x with `watch` t.wat...
_____no_output_____
Apache-2.0
TensorFlow Advanced Techniques Specialization/Course-2/Custom and Distributed Training with TensorFlow/Week-1/C2W1_Assignment.ipynb
nafiul-araf/TensorFlow-Advanced-Techniques-Specialization
Exploratory Data AnalysisIn this notebook, I have illuminated some of the strategies that one can use to explore the data and gain some insights about it.We will start from finding metadata about the data, to determining what techniques to use, to getting some important insights about the data. This is based on the IB...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy import stats %matplotlib inline
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Load the data as pandas dataframe
path='https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Data%20files/automobileEDA.csv' df = pd.read_csv(path) df.head()
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Metadata: The columns's typesFinding column's types is an important step. It serves two purposes:1. See if we need to convert some data. For example, price may be in string instead of numbers. This is very important as it could throw everything that we do afterwards off.2. Find out what type of analysis we need to do ...
df.dtypes
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
From the results above, we can see that we can roughly divide the types into two categories: numeric (int64 and float64) and object. Although object type can contain lots of things, it's used often to store string variables. A quick glance at the table tells us that there's no glaring errors in object types. Now we div...
df.corr()
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Note that the diagonal elements are always one; because correlation with itself is always one. Now, it seems somewhat daunting, and frankly, unneccessary to have this big of a table and correlation between things we don't care (say bore and stroke). If we want to find out the correlation with just price, using `corrwit...
corr = df.corrwith(df['price']) # Prettify pd.DataFrame(data=corr.values, index=corr.index, columns=['Correlation'])
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
From the table above, we have some idea about what can we expect the relationship should be like. As a refresher, in Pearson correlation, values range in [-1, 1] with -1 and 1 implying a perfect linear relationship and 0 implying none. A positive value implies a positive relationship (value increase in response to incr...
plt.figure(figsize=(5,5)) sns.regplot(x="engine-size", y="price", data=df);
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
As the engine-size goes up, the price goes up. This indicates a decent positive direct correlation between these two variables. Thus, we can say that the engine size is a good predictor of price since the regression line is almost a perfect diagonal line.We can also check this with the Pearson correlation we got above....
sns.regplot(x="highway-mpg", y="price", data=df);
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
The graph shows a decent negative realtionship. So, it could be a potential indicator. Although, it seems that the relationship isn't exactly normal--given the curve of the points. Let's try a higher order regression line.
sns.regplot(x="highway-mpg", y="price", data=df, order=2);
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
There. It seems much better. Weak Linear Relationship Not all variables have to be correlated. Let's check out the graph of "Peak-rpm" as a predictor variable for "price".
sns.regplot(x="peak-rpm", y="price", data=df);
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
From the graph, it's clear that peak rpm is a bad indicator of price. It seems that there is no relationship between them. It seems almost random. A quick check at the correlation value confirms this. The value is -0.1. It's very close to zero, implying no relationship. Although there are cases in which low value can b...
sns.boxplot(x="body-style", y="price", data=df);
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
We can infer that there is likely to be no significant relationship as there is a decent over lap. Let's examine engine "engine-location" and "price"
sns.boxplot(x="engine-location", y="price", data=df);
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Although there are a lot of outliers for the front, the distribution of price between these two engine-location categories is distinct enough to take engine-location as a potential good predictor of price.Let's examine "drive-wheels" and "price".
sns.boxplot(x="drive-wheels", y="price", data=df);
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Here we see that the distribution of price between the different drive-wheels categories differs; as such drive-wheels could potentially be a predictor of price. Statistical method to checking for a significant realtionship - ANOVAAlthough visualisation is helpful, it does not give us a concrete and certain vision in ...
grouped_anova = df[['drive-wheels', 'price']].groupby(['drive-wheels']) grouped_anova.head(2)
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
We can obtain the values of the method group using the method `get_group()`
grouped_anova.get_group('4wd')['price']
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Finally, we use the function `f_oneway()` to obtain the F-test score and P-value.
# ANOVA f_val, p_val = stats.f_oneway(grouped_anova.get_group('fwd')['price'], grouped_anova.get_group('rwd')['price'], grouped_anova.get_group('4wd')['price']) print( "ANOVA results: F=", f_val, ", P =", p_val)
ANOVA results: F= 67.95406500780399 , P = 3.3945443577151245e-23
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
From the result, we can see that we have a large F-test score and a very small p-value. Still, we need to check if all three tested groups are highly correlated? Separately: fwd and rwd
f_val, p_val = stats.f_oneway(grouped_anova.get_group('fwd')['price'], grouped_anova.get_group('rwd')['price']) print( "ANOVA results: F=", f_val, ", P =", p_val )
ANOVA results: F= 130.5533160959111 , P = 2.2355306355677845e-23
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Seems like the result is significant and they are correlated. Let's examine the other groups 4wd and rwd
f_val, p_val = stats.f_oneway(grouped_anova.get_group('4wd')['price'], grouped_anova.get_group('rwd')['price']) print( "ANOVA results: F=", f_val, ", P =", p_val)
ANOVA results: F= 8.580681368924756 , P = 0.004411492211225333
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
4wd and fwd
f_val, p_val = stats.f_oneway(grouped_anova.get_group('4wd')['price'], grouped_anova.get_group('fwd')['price']) print("ANOVA results: F=", f_val, ", P =", p_val)
ANOVA results: F= 0.665465750252303 , P = 0.41620116697845666
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Relationship between Categorical Data: Corrected Cramer's VA good way to test relation between two categorical variable is Corrected Cramer's V. **Note:** A p-value close to zero means that our variables are very unlikely to be completely unassociated in some population. However, this does not mean the variables are s...
df.describe()
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
To get the information about categorical variables, we need to specifically tell it to pandas to include them. For categorical variables, it shows:* Count* Unique values* The most common value or 'top'* Frequency of the 'top'
df.describe(include=['object'])
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Value CountsSometimes, we need to understand the distribution of the categorical data. This could mean understanding how many units of each characteristic/variable we have. `value_counts()` is a method in pandas that can help with it. If we use it with a series, it will give us the unique values and how many of them e...
df['drive-wheels'].value_counts().to_frame()
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
`.to_frame()` method is added to make it into a dataframe, hence making it look better.You can play around and rename the column and index name if you want. We can repeat the above process for the variable 'engine-location'.
df['engine-location'].value_counts().to_frame()
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Examining the value counts of the engine location would not be a good predictor variable for the price. This is because we only have three cars with a rear engine and 198 with an engine in the front, this result is skewed. Thus, we are not able to draw any conclusions about the engine location. GroupingGrouping is a u...
df['drive-wheels'].unique()
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
If we want to know, on average, which type of drive wheel is most valuable, we can group "drive-wheels" and then average them.
df[['drive-wheels','body-style','price']].groupby(['drive-wheels']).mean()
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
From our data, it seems rear-wheel drive vehicles are, on average, the most expensive, while 4-wheel and front-wheel are approximately the same in price.It's also possible to group with multiple variables. For example, let's group by both 'drive-wheels' and 'body-style'. This groups the dataframe by the unique combinat...
grouped_by_wheels_and_body = df[['drive-wheels','body-style','price']].groupby(['drive-wheels','body-style']).mean() grouped_by_wheels_and_body
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Although incredibly useful, it's a little hard to read. It's better to convert it to a pivot table.A pivot table is like an Excel spreadsheet, with one variable along the column and another along the row. There are various ways to do so. A way to do that is to use the method `pivot()`. However, with groups like the one...
grouped_by_wheels_and_body = grouped_by_wheels_and_body.unstack() grouped_by_wheels_and_body
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Often, we won't have data for some of the pivot cells. Often, it's filled with the value 0, but any other value could potentially be used as well. This could be mean or some other flag.
grouped_by_wheels_and_body.fillna(0)
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Let's do the same for body-style only
df[['price', 'body-style']].groupby('body-style').mean()
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Visualizing GroupsHeatmaps are a great way to visualize groups. They can show relationships clearly in this case. Do note that you need to be careful with the color schemes. Since chosing appropriate colorscheme is not only appropriate for your 'story' of the data, it is also important since it can impact the percepti...
sns.heatmap(grouped_by_wheels_and_body, cmap="Blues");
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
This heatmap plots the target variable (price) proportional to colour with respect to the variables 'drive-wheel' and 'body-style' in the vertical and horizontal axis respectively. This allows us to visualize how the price is related to 'drive-wheel' and 'body-style'. Correlation and Causation Correlation and causatio...
df.corr()
_____no_output_____
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Cramer's VCramer's V is a great method to calculate the relationship between two categorical variables. Read above about Cramer's V to get a better estimate.**General Rule of Thumb:*** V ∈ [0.1,0.3]: weak association* V ∈ [0.4,0.5]: medium association* V > 0.5: strong association ANOVA MethodAs discussed previously, ...
pearson_coef, p_value = stats.pearsonr(df['wheel-base'], df['price']) print("The Pearson Correlation Coefficient is", pearson_coef, " with a P-value of P =", p_value)
The Pearson Correlation Coefficient is 0.5846418222655081 with a P-value of P = 8.076488270732989e-20
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Since the p-value is $<$ 0.001, the correlation between wheel-base and price is statistically significant, although the linear relationship isn't extremely strong (~0.585)Let's try one more example: horsepower vs price.
pearson_coef, p_value = stats.pearsonr(df['horsepower'], df['price']) print("The Pearson Correlation Coefficient is", pearson_coef, " with a P-value of P = ", p_value)
The Pearson Correlation Coefficient is 0.809574567003656 with a P-value of P = 6.369057428259557e-48
Apache-2.0
Exploratory Data Analysis.ipynb
full-void/data-science-concepts
Bogumiła Walkowiak bogumila.walkowiak@grenoble-inp.org Joachim Mąkowski joachim-kajetan.makowski@grenoble-inp.org Intelligent Systems: Reasoning and Recognition Recognizing Digits using Neural Networks 1. IntroductionThe MNIST (Modified National Institute of Standards and Technology) dataset is a large collection of...
import numpy as np import tensorflow.compat.v1.keras.backend as K import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score,roc_curve,auc from sklearn.metrics impor...
_____no_output_____
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
3. Creating neural networks We decided to create a function. Thanks to it we will be able to write less code. Function trains model provided by argument of function, prints model's loss, accuracy, precision, recall and AUC for each digit and plots a history of training.
def predict_model(model, callbacks = [],batch_size=128, epochs = 4,lr=0.001): adam = keras.optimizers.Adam(lr=lr) model.compile(loss="categorical_crossentropy", optimizer=adam, metrics=["accuracy", "Precision","Recall"]) history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation...
_____no_output_____
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
We added an instance of EarlyStopping class, which provides us a mechanism of stopping algorithm before the whole training process is done. When 3 epochs are not achieving a better result (in our example higher validation accuracy) then our training is stopped and we restore the best model.
# simple early stopping es = keras.callbacks.EarlyStopping(monitor='val_accuracy', mode='max', verbose=1, patience = 3, restore_best_weights=True)
_____no_output_____
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
Basic Fully Connected Multi-layer Network The first network we have created is basic fully connected mutli-layer network:
model_fc = keras.Sequential([ layers.Dense(32, activation="relu",input_shape=(28,28,1)), layers.Dense(64, activation="relu"), layers.Flatten(), layers.Dense(128, activation="relu"), layers.Dropout(.25), layers.Dense(10, activation="softmax") ]) model_fc.summary() predict_model(model_fc, [e...
Model: "sequential_20" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_59 (Dense) (None, 28, 28, 32) 64 _________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
This is basic model achieves about 97,5% accuracy on test set. It is made of 2 hidden layers with reasonable number of units. Training this model is quite fast (on my laptop it was 5s per epoch, using GPU).As we see in plots our model started to overfits, because validation accuracy and loss was staying on the same lev...
model_fc_small = keras.Sequential([ layers.Dense(32, activation="relu",input_shape=(28,28,1)), layers.Flatten(), layers.Dense(64, activation="relu"), layers.Dropout(.25), layers.Dense(10, activation="softmax") ]) model_fc_small.summary() predict_model(model_fc_small, [es], epochs=100) model_fc...
Model: "sequential_2" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_7 (Dense) (None, 28, 28, 32) 64 __________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
Firstly, we tried different numbers of hidden layers. With 1 hidden layer the model the model was achieving around 96,5% on test set. The model is underfitted because this number of layers is not enough to explain the complexity of our data.Model with 4 hidden layers achieved 98,1% of accuracy but the training time was...
model_fc = keras.Sequential([ layers.Dense(10, activation="relu",input_shape=(28,28,1)), layers.Dense(20, activation="relu"), layers.Flatten(), layers.Dense(40, activation="relu"), layers.Dropout(.25), layers.Dense(10, activation="softmax") ]) model_fc.summary() predict_model(model_fc, [es...
Model: "sequential_3" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_13 (Dense) (None, 28, 28, 10) 20 __________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
In this situation we trained a model with small number of units in each layer. The model didn't achieve it's best. We can see, that train accuracy is much lower than validation accuracy. It is caused by insufficient number of units, so that our model decided to choose higher accuracy in validation data at the expense o...
model_fc = keras.Sequential([ layers.Dense(100, activation="relu",input_shape=(28,28,1)), layers.Dense(200, activation="relu"), layers.Flatten(), layers.Dense(400, activation="relu"), layers.Dropout(.25), layers.Dense(10, activation="softmax") ]) model_fc.summary() predict_model(model_fc, ...
Model: "sequential_4" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_17 (Dense) (None, 28, 28, 100) 200 __________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
In this model we see that it's overfitting after third epoch. It is caused by too high number of units. Different learning rate
model_fc_01 = keras.Sequential([ layers.Dense(32, activation="relu",input_shape=(28,28,1)), layers.Dense(64, activation="relu"), layers.Flatten(), layers.Dense(128, activation="relu"), layers.Dropout(.25), layers.Dense(10, activation="softmax") ]) model_fc_01.summary() predict_model(model_...
Model: "sequential_21" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_63 (Dense) (None, 28, 28, 32) 64 _________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
We took our first model and decided to train it with different learning rates. With learning rate 0.05 we received very bad results (accuracy around 92%). The scores are so bad because our optimizer did not find good weights, because it had to change values with too big "jump".
model_fc_00001 = keras.Sequential([ layers.Dense(32, activation="relu",input_shape=(28,28,1)), layers.Dense(64, activation="relu"), layers.Flatten(), layers.Dense(128, activation="relu"), layers.Dropout(.25), layers.Dense(10, activation="softmax") ]) model_fc_00001.summary() predict_model(...
Model: "sequential_15" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= dense_46 (Dense) (None, 28, 28, 32) 64 _________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
Model with learning rate equals 0.00001 performed pretty well but it needed 54 epochs to achieve 97,1% accuracy (compared to 6 epochs using standard learning rate equals 0.001). This is because optimizer "jumped" too small distance searching best results, and it had to do many iterations to find the best weights. Basi...
model_cnn = keras.Sequential([ layers.Conv2D(32, (3,3), activation="relu", input_shape=(28,28,1)), layers.MaxPooling2D (2,2), layers.Conv2D(64, (3,3), activation="relu"), layers.MaxPooling2D (2,2), layers.Flatten(), layers.Dropout(.5), layers.Dense(10, activation="softmax") ]) model_cn...
Model: "sequential_5" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 26, 26, 32) 320 __________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
Our first convolutional model with 2 convolutional layers was performing even better then fully connected neural networks. This model is not overfitted, because train and validation loss and accuracy are close to each other. It has only 34,826 parameters to train, so the training of such model is pretty fast. On test s...
model_cnn_short = keras.Sequential([ layers.Conv2D(32, (3,3), activation="relu", input_shape=(28,28,1)), layers.MaxPooling2D (2,2), layers.Flatten(), layers.Dropout(.5), layers.Dense(10, activation="softmax") ]) model_cnn_short.summary() predict_model(model_cnn_short, [es], epochs=100)
Model: "sequential_6" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_2 (Conv2D) (None, 26, 26, 32) 320 __________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
Next model has only 1 convolution layer which has more parameters (54,410) because of less number of pooling layers. The results are satisfying, but not as good as previous model (test accuracy equals 98,2%).
model_cnn_long = keras.Sequential([ layers.Conv2D(32, (3,3), activation="relu", input_shape=(28,28,1)), layers.MaxPooling2D ((2,2),1), layers.Conv2D(64, (3,3), activation="relu"), layers.MaxPooling2D ((2,2),1), layers.Conv2D(128, (3,3), activation="relu"), layers.MaxPooling2D ((2,2),1), ...
Model: "sequential_28" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_32 (Conv2D) (None, 26, 26, 32) 320 _________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
Next we created a neural network with 4 convolutional layers and with 17 milion parameters. The model was not overfitted. It had accuracy around 99.2% for test, train and validation model. Time needed to train this model was much higher (19s per epoch comparing to 3s per epoch in CNN that we have implemented). This is ...
model_cnn_min = keras.Sequential([ layers.Conv2D(4, (3,3), activation="relu", input_shape=(28,28,1)), layers.MaxPooling2D (2,2), layers.Conv2D(16, (3,3), activation="relu"), layers.MaxPooling2D (2,2), layers.Flatten(), layers.Dropout(.5), layers.Dense(10, activation="softmax") ]) model...
Model: "sequential_9" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_9 (Conv2D) (None, 26, 26, 4) 40 __________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
Next we decided to check how number of filters impact to performance of model. Reducing number of filter in convolutional layers made our model worse than basic model. Accuracy has fallen to 97.8%, because this model was too simple to explain complexity of our data. This model is underfitted.
model_cnn_max = keras.Sequential([ layers.Conv2D(128, (3,3), activation="relu", input_shape=(28,28,1)), layers.MaxPooling2D (2,2), layers.Conv2D(512, (3,3), activation="relu"), layers.MaxPooling2D (2,2), layers.Flatten(), layers.Dropout(.5), layers.Dense(10, activation="softmax") ]) mo...
Model: "sequential_10" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_11 (Conv2D) (None, 26, 26, 128) 1280 _________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
Next we increased number of filters. This caused a raise of number of parameters to over 700 thousands but model did not perform better than basic model. Test accuracy was 99%, which is slightly less than basic model's accuracy. It means that we should not use such high number of filters because we do not need them. Th...
model_cnn_pool5 = keras.Sequential([ layers.Conv2D(32, (3,3), activation="relu", input_shape=(28,28,1)), layers.MaxPooling2D (5,3), layers.Conv2D(64, (3,3), activation="relu"), layers.MaxPooling2D (5,3), layers.Flatten(), layers.Dropout(.5), layers.Dense(10, activation="softmax") ]) mo...
Model: "sequential_17" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_13 (Conv2D) (None, 26, 26, 32) 320 _________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
Next, we checked different size of pooling layers. We decided to create a MaxPooling layers with size equals (5,5) and stride equals 3. It means that we take a square of values with size 5x5 then we look for max value, we write it in the middle of square and than we "move" 3 numbers in right or down direction. As we ca...
model_cnn_avg = keras.Sequential([ layers.Conv2D(32, (3,3), activation="relu", input_shape=(28,28,1)), layers.AveragePooling2D (3,3), layers.Conv2D(64, (3,3), activation="relu"), layers.AveragePooling2D (3,3), layers.Flatten(), layers.Dropout(.5), layers.Dense(10, activation="softmax")...
Model: "sequential_18" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_15 (Conv2D) (None, 26, 26, 32) 320 _________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
After, we changed MaxPooling layer to AveragePooling layer. The difference between this two layers is that AveragePooling layer sums the values in the square and divides by the number of values in square. Results are worse than basic model because MaxPooling, by its characteristics, is better when we have black backgro...
model_cnn_fc = keras.Sequential([ layers.Conv2D(32, (3,3), activation="relu", input_shape=(28,28,1)), layers.MaxPooling2D (2,2), layers.Conv2D(64, (3,3), activation="relu"), layers.MaxPooling2D (2,2), layers.Flatten(), layers.Dense(128, activation="relu"), layers.Dense(32, activation="...
Model: "sequential_19" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_17 (Conv2D) (None, 26, 26, 32) 320 _________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
The performance of a published network (LeNet5, VGG, Yolo, etc) for recognizing MNIST Digits We decided to implement the architecture of LeNet5 network. The LeNet-5 architecture consists of two sets of convolutional and average pooling layers, followed by a flattening convolutional layer, then two fully-connected laye...
lenet5 = keras.Sequential([ layers.Conv2D(filters=6, kernel_size=(3, 3), activation='relu', input_shape=(28,28,1)), layers.AveragePooling2D(), layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu'), layers.AveragePooling2D(), layers.Flatten(), layers.Dense(units=120, act...
Model: "sequential_27" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_30 (Conv2D) (None, 26, 26, 6) 60 _________________________________...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
The best network
from sklearn.metrics import confusion_matrix y_pred = model_cnn_long.predict(x_test) y_pred1 = list(np.argmax(y_pred, axis=1)) y_test1 = list(np.argmax(y_test, axis = 1)) confusion_matrix = confusion_matrix(y_test1, y_pred1) print(confusion_matrix)
[[654 0 0 0 0 0 0 0 0 0] [ 0 765 0 0 0 0 0 1 0 1] [ 1 1 697 1 0 0 0 3 1 0] [ 0 0 0 707 0 0 0 2 0 0] [ 0 0 0 0 670 0 1 0 0 2] [ 1 1 0 0 0 648 0 0 0 2] [ 1 0 0 1 0 1 697 0 0 0] [ 0 0 0 0 ...
MIT
MNIST_Recognizer.ipynb
ColdBacon/Digit-recognizer
Predicting Movie Review Sentiment with BERT on TF Hub If you’ve been following Natural Language Processing over the past year, you’ve probably heard of BERT: Bidirectional Encoder Representations from Transformers. It’s a neural network architecture designed by Google researchers that’s totally transformed what’s state...
from sklearn.model_selection import train_test_split import pandas as pd import tensorflow as tf import tensorflow_hub as hub from datetime import datetime tf.logging.set_verbosity(tf.logging.INFO)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /usr/local/lib/python3.6/dis...
Apache-2.0
predicting_movie_reviews_with_bert_on_tf_hub.ipynb
bedman3/bert
In addition to the standard libraries we imported above, we'll need to install BERT's python package.
!pip install bert-tensorflow import bert from bert import run_classifier from bert import optimization from bert import tokenization
WARNING: Logging before flag parsing goes to stderr. W0414 10:19:55.760469 140105573619520 deprecation_wrapper.py:119] From /usr/local/lib/python3.6/dist-packages/bert/optimization.py:87: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.
Apache-2.0
predicting_movie_reviews_with_bert_on_tf_hub.ipynb
bedman3/bert
Below, we'll set an output directory location to store our model output and checkpoints. This can be a local directory, in which case you'd set OUTPUT_DIR to the name of the directory you'd like to create. If you're running this code in Google's hosted Colab, the directory won't persist after the Colab session ends.Alt...
# Set the output directory for saving model file # Optionally, set a GCP bucket location OUTPUT_DIR = 'output_files'#@param {type:"string"} #@markdown Whether or not to clear/delete the directory and create a new one DO_DELETE = False #@param {type:"boolean"} #@markdown Set USE_BUCKET and BUCKET if you want to (option...
***** Model output directory: output_files *****
Apache-2.0
predicting_movie_reviews_with_bert_on_tf_hub.ipynb
bedman3/bert
Data First, let's download the dataset, hosted by Stanford. The code below, which downloads, extracts, and imports the IMDB Large Movie Review Dataset, is borrowed from [this Tensorflow tutorial](https://www.tensorflow.org/hub/tutorials/text_classification_with_tf_hub).
from tensorflow import keras import os import re # Load all files from a directory in a DataFrame. def load_directory_data(directory): data = {} data["sentence"] = [] data["sentiment"] = [] for file_path in os.listdir(directory): with tf.gfile.GFile(os.path.join(directory, file_path), "r") as f: data...
_____no_output_____
Apache-2.0
predicting_movie_reviews_with_bert_on_tf_hub.ipynb
bedman3/bert
To keep training fast, we'll take a sample of 5000 train and test examples, respectively.
# train = train.sample(5000) # test = test.sample(5000) train.columns
_____no_output_____
Apache-2.0
predicting_movie_reviews_with_bert_on_tf_hub.ipynb
bedman3/bert
For us, our input data is the 'sentence' column and our label is the 'polarity' column (0, 1 for negative and positive, respecitvely)
DATA_COLUMN = 'text' LABEL_COLUMN = 'stars' # label_list is the list of labels, i.e. True, False or 0, 1 or 'dog', 'cat' label_list = [1, 2, 3, 4, 5]
_____no_output_____
Apache-2.0
predicting_movie_reviews_with_bert_on_tf_hub.ipynb
bedman3/bert
Data PreprocessingWe'll need to transform our data into a format BERT understands. This involves two steps. First, we create `InputExample`'s using the constructor provided in the BERT library.- `text_a` is the text we want to classify, which in this case, is the `Request` field in our Dataframe. - `text_b` is used if...
# Use the InputExample class from BERT's run_classifier code to create examples from the data train_InputExamples = train.apply(lambda x: bert.run_classifier.InputExample(guid=None, # Globally unique ID for bookkeeping, unused in this example text_a = x...
_____no_output_____
Apache-2.0
predicting_movie_reviews_with_bert_on_tf_hub.ipynb
bedman3/bert