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
Plot excitatory cells
n_panels = sum(a.shape[1] for a in data_exc.segments[0].analogsignalarrays) + 2 plt.subplot(n_panels, 1, 1) plot_spiketrains(data_exc.segments[0]) panel = 3 for array in data_exc.segments[0].analogsignalarrays: for i in range(array.shape[1]): plt.subplot(n_panels, 1, panel) plot_signal(array, i, col...
_____no_output_____
BSD-3-Clause
src/experimental_code/.ipynb_checkpoints/Izh_LSM_StaticSyn-checkpoint.ipynb
Roboy/LSM_SpiNNaker_MyoArm
______Copyright Pierian DataFor more information, visit us at www.pieriandata.com MA Moving AveragesIn this section we'll compare Simple Moving Averages to Exponentially Weighted Moving Averages in terms of complexity and performance.Related Functions:pandas.DataFrame.rolling(window)  Provides rolling window...
import pandas as pd import numpy as np %matplotlib inline airline = pd.read_csv('../Data/airline_passengers.csv',index_col='Month',parse_dates=True) airline.dropna(inplace=True) airline.head()
_____no_output_____
Apache-2.0
tsa/jose/UDEMY_TSA_FINAL (1)/05-Time-Series-Analysis-with-Statsmodels/02-EWMA-Exponentially-Weighted-Moving-Average.ipynb
juspreet51/ml_templates
___ SMA Simple Moving AverageWe've already shown how to create a simple moving average by applying a mean function to a rolling window.For a quick review:
airline['6-month-SMA'] = airline['Thousands of Passengers'].rolling(window=6).mean() airline['12-month-SMA'] = airline['Thousands of Passengers'].rolling(window=12).mean() airline.head(15) airline.plot();
_____no_output_____
Apache-2.0
tsa/jose/UDEMY_TSA_FINAL (1)/05-Time-Series-Analysis-with-Statsmodels/02-EWMA-Exponentially-Weighted-Moving-Average.ipynb
juspreet51/ml_templates
___ EWMA Exponentially Weighted Moving Average We just showed how to calculate the SMA based on some window. However, basic SMA has some weaknesses:* Smaller windows will lead to more noise, rather than signal* It will always lag by the size of the window* It will never reach to full peak or valley of the data due to t...
airline['EWMA12'] = airline['Thousands of Passengers'].ewm(span=12,adjust=False).mean() airline[['Thousands of Passengers','EWMA12']].plot();
_____no_output_____
Apache-2.0
tsa/jose/UDEMY_TSA_FINAL (1)/05-Time-Series-Analysis-with-Statsmodels/02-EWMA-Exponentially-Weighted-Moving-Average.ipynb
juspreet51/ml_templates
Comparing SMA to EWMA
airline[['Thousands of Passengers','EWMA12','12-month-SMA']].plot(figsize=(12,8)).autoscale(axis='x',tight=True);
_____no_output_____
Apache-2.0
tsa/jose/UDEMY_TSA_FINAL (1)/05-Time-Series-Analysis-with-Statsmodels/02-EWMA-Exponentially-Weighted-Moving-Average.ipynb
juspreet51/ml_templates
Lecture 7
# imports # imports import numpy as np from scipy.ndimage import uniform_filter1d from scipy.stats import shapiro from matplotlib import pyplot as plt import pandas from statsmodels.tsa.seasonal import seasonal_decompose import statsmodels.api as sm from statsmodels.stats.stattools import durbin_watson import statsmo...
_____no_output_____
BSD-3-Clause
OCEA-267/Lectures/W4_L7.ipynb
profxj/ocea200
Monte Carlo
nrand = 100
_____no_output_____
BSD-3-Clause
OCEA-267/Lectures/W4_L7.ipynb
profxj/ocea200
Random
def grab_norm(size=nrand): return np.random.normal(size=size) time = np.arange(r_norm.size) data = pandas.DataFrame() data['time'] = time
_____no_output_____
BSD-3-Clause
OCEA-267/Lectures/W4_L7.ipynb
profxj/ocea200
Fit
data['norm'] = grab_norm() formula = "norm ~ time" mod1 = smf.glm(formula=formula, data=data).fit()#, family=sm.families.Binomial()).fit() mod1.summary() mod1.pvalues.Intercept
_____no_output_____
BSD-3-Clause
OCEA-267/Lectures/W4_L7.ipynb
profxj/ocea200
Plot
def plot_me(data, model, entry): plt.clf() fig = plt.figure(figsize=(12,8)) # ax = plt.gca() ax.plot(data['time'], data[entry], 'o', ms=2) # Fit ax.plot(data['time'], mod1.fittedvalues, label=f'p-value({entry}) = {mod1.pvalues.Intercept}') # set_fontsize(ax, 17) ax.legend(fontsiz...
_____no_output_____
BSD-3-Clause
OCEA-267/Lectures/W4_L7.ipynb
profxj/ocea200
Run a bunch
key = 'norm' data[key] = grab_norm() formula = f"{key} ~ time" mod1 = smf.glm(formula=formula, data=data).fit()#, family=sm.families.Binomial()).fit() plot_me(data, mod1, key)
_____no_output_____
BSD-3-Clause
OCEA-267/Lectures/W4_L7.ipynb
profxj/ocea200
Log-normal
def grab_lognorm(size=nrand): return np.random.lognormal(size=size) key = 'lnorm' data[key] = grab_lognorm() formula = f"{key} ~ time" mod1 = smf.glm(formula=formula, data=data).fit()#, family=sm.families.Binomial()).fit() plot_me(data, mod1, key) mod1.summary()
_____no_output_____
BSD-3-Clause
OCEA-267/Lectures/W4_L7.ipynb
profxj/ocea200
Auto-correlated data
## Stolen from the internet... def sample_signal(n_samples, corr, mu=0, sigma=1): assert 0 < corr < 1, "Auto-correlation must be between 0 and 1" # Find out the offset `c` and the std of the white noise `sigma_e` # that produce a signal with the desired mean and variance. # See https://en.wikipedia.org...
_____no_output_____
BSD-3-Clause
OCEA-267/Lectures/W4_L7.ipynb
profxj/ocea200
Import libraries and load files
from tensorflow.python.client import device_lib def get_available_gpus(): local_device_protos = device_lib.list_local_devices() return [x.name for x in local_device_protos if x.device_type == 'GPU'] get_available_gpus() import tensorflow as tf import pandas as pd import numpy as np from sklearn.feature_extrac...
_____no_output_____
MIT
notebooks/1_0_agglomerative_clustering.ipynb
nymarya/school-budgets-for-education
FunctionTransformers
# Define combine_text_columns() def combine_text_columns(data_frame): """ converts all text in each row of data_frame to single vector """ # Drop non-text columns that are in the df text_data = data_frame[categoric].copy() # Replace nans with blanks text_data.fillna("", inplace=True) ...
_____no_output_____
MIT
notebooks/1_0_agglomerative_clustering.ipynb
nymarya/school-budgets-for-education
PipelineApply the transformations on numeric and categorica data. Neither dimension reduction or standard scaler are used.
pl = Pipeline([ ('union', FeatureUnion( transformer_list = [ ('numeric_features', Pipeline([ ('selector', get_numeric_data), ('imp', SimpleImputer()) ])), ('text_features', Pipeline([ ('select...
_____no_output_____
MIT
notebooks/1_0_agglomerative_clustering.ipynb
nymarya/school-budgets-for-education
Applying the steps, we got a sparse matrix with 1048578 features.
data_X= pl.fit_transform(X, labels_true) rus = RandomUnderSampler() X_resampled, y_resampled = rus.fit_resample(data_X, labels_true) X_resampled.shape y_resampled.shape
_____no_output_____
MIT
notebooks/1_0_agglomerative_clustering.ipynb
nymarya/school-budgets-for-education
With the purpose of calculating the adjusted rand score, we need to set the labels to numbers between 0 and 10. TrainingThe model is trained and tested using the number of groups varying between 2 and 20. As the agglomerative clustering method is deterministic, the model is fitted only one time.
results = [] for k in range(2, 21): agg = AgglomerativeClustering(memory='mycachedir', compute_full_tree=True, n_clusters=k) start = datetime.now() with tf.device('/gpu:0'): #fit model to data cluster_labels = agg.fit_predict(X_resampled) end = datetime.now() # The sil...
_____no_output_____
MIT
notebooks/1_0_agglomerative_clustering.ipynb
nymarya/school-budgets-for-education
Visual Explanation of KNNFor the class presentation, I use the following plots to discuss using k-nearest neighbors to estimate outcome based on a predictor variable. In this case, averages were calculated manually with k=3.
import pandas as pd from matplotlib import pyplot as plt
_____no_output_____
MIT
KNN_Explanation_Visual.ipynb
mmccown5/QCM_project
I load my example data. These are semi-random points I picked to give the plot non-linear data with some trend and grouping.
data = pd.read_csv("visual.txt",sep="\t") data.head()
_____no_output_____
MIT
KNN_Explanation_Visual.ipynb
mmccown5/QCM_project
Plot the example data with pyplot. Note that the scales are removed, as it doesn't matter for the purpose of the presentation.
fig, ax = plt.subplots() ax.tick_params(left = False, labelleft = False, bottom=False, labelbottom=False) plt.scatter(data.X, data.Y) plt.ylabel("Outcome") plt.xlabel("Putative Predictor") plt.savefig("vis1.png",dpi=300) plt.show()
_____no_output_____
MIT
KNN_Explanation_Visual.ipynb
mmccown5/QCM_project
Now add red points to represent new values of the putative predictor for which the outcome is unknown. The blue points will be used as training dataset while the red are treated as test points. First, I plot the test points at the bottom of the graph. (This was zero, but that changed the y range shown and I didn't like...
fig, ax = plt.subplots() ax.tick_params(left = False, labelleft = False, bottom=False, labelbottom=False) plt.scatter(data.X, data.Y) plt.scatter([2,5.5,9.5], [0,0,0],color='red') plt.ylabel("Outcome") plt.xlabel("Putative Predictor") plt.savefig("vis2.png",dpi=300) plt.show() fig, ax = plt.subplots() ax.tick_par...
_____no_output_____
MIT
KNN_Explanation_Visual.ipynb
mmccown5/QCM_project
Next, move the test points to the y value predicted by knn with k of 3.
fig, ax = plt.subplots() ax.tick_params(left = False, labelleft = False, bottom=False, labelbottom=False) plt.scatter(data.X, data.Y) plt.scatter([2,5.5,9.5], [3.8,8.5,4.7],color='red') plt.ylabel("Outcome") plt.xlabel("Putative Predictor") plt.savefig("vis3.png",dpi=300) plt.show()
_____no_output_____
MIT
KNN_Explanation_Visual.ipynb
mmccown5/QCM_project
Impact of consensus clustering on stability
import pandas as pd import matplotlib.pylab as plt import seaborn as sns sns.set_style("whitegrid") plt.rcParams['figure.figsize'] = (8,6) plt.rcParams['font.size'] = 20
_____no_output_____
CC-BY-4.0
notebooks/si-06-variance-impact-of-consensus-clustering.ipynb
QuantLaw/Measuring-Law-Over-Time
US
def make_boxplot(dataset, metric, ylabel, save_path=None): df = pd.read_pickle(f'../results/variance_impact_of_consensus_clustering_{dataset}.pickle') fig, ax = plt.subplots() ax.boxplot( [ df.loc[metric,:].loc[i,:]['values'].tolist() for i in sorted(df.loc[metric,:].index.u...
_____no_output_____
CC-BY-4.0
notebooks/si-06-variance-impact-of-consensus-clustering.ipynb
QuantLaw/Measuring-Law-Over-Time
DE
make_boxplot('de_reg', 'NMI', 'Normalized Mutual Information', '../graphics/variance_impact_of_consensus_clustering_nmi_de_reg.pdf') make_boxplot('de_reg', 'Rand', 'Adjusted Rand Index', '../graphics/variance_impact_of_consensus_clustering_rand_de_reg.pdf')
_____no_output_____
CC-BY-4.0
notebooks/si-06-variance-impact-of-consensus-clustering.ipynb
QuantLaw/Measuring-Law-Over-Time
01 - Structure of a python package *Python Zen: "Namespaces are one honking great idea - let's do more of those!"*We introduced the concept of python modules in a [previous unit](../week_03/01-Import-Scopes). Today we are going into more details and will introduce Python "**packages**", which contain more than one mod...
def print_n(): print('The number N in the function is: {}'.format(N)) N += 1 N = 10 print_n()
_____no_output_____
CC-BY-4.0
book/week_07/01-Package-structure.ipynb
fmaussion/scientific_programming
So how is this example different to the one above, which worked fine as explained? We just added a line *below* the one that used to work before. So now there is a variable ``N`` in the function, and it overrides the module-level one. The python interpreter detects that variable and raises an error at execution, indepe...
x = 2 y = 1 def func(x): x = x + y return x print(func(3)) print(func(x)) print(x) print(y)
_____no_output_____
CC-BY-4.0
book/week_07/01-Package-structure.ipynb
fmaussion/scientific_programming
What can we learn from this example? That the local (function) scope variable ``x`` has nothing to do with the global scope variable ``x``. For the python interpreter, both are unrelated and their name is irrelevant. What is relevant though is which scope they are attached to (if you are interested to know which variab...
import numpy as np a = np.array([1.123456789]) print(a) np.set_printoptions(precision=4) print(a)
_____no_output_____
CC-BY-4.0
book/week_07/01-Package-structure.ipynb
fmaussion/scientific_programming
We changed the value of a variable at the module level (we don't know its name but it isn't relevant here) which is now taken into account by the numpy print function. Let's say we'd like to have a counter of the number of times a function has been called. We can do this with the following syntax:
count = 0 def func(): global count # without this, count would be local! count += 1 func() func() print(count)
_____no_output_____
CC-BY-4.0
book/week_07/01-Package-structure.ipynb
fmaussion/scientific_programming
Note that in practice, global variables that need updating are rarely single integers or floats like in this example. The reasons for this will be explained later on, once you've learned more about python packages and the import system. Are global variables truly "global" in python? If by this question we mean "glob...
import numpy import math import scipy print(math.pi, 'from the math module') print(numpy.pi, 'from the numpy package') print(scipy.pi, 'from the scipy package')
_____no_output_____
CC-BY-4.0
book/week_07/01-Package-structure.ipynb
fmaussion/scientific_programming
The only exception to the import rule are [built-in functions](https://docs.python.org/3/library/functions.html), which are available everywhere and have their own scope. If you want to know more about the four different python scopes, read this [blog post by Sebastian Raschka](http://sebastianraschka.com/Articles/2014...
import numpy numpy.__file__
_____no_output_____
CC-BY-4.0
book/week_07/01-Package-structure.ipynb
fmaussion/scientific_programming
The experiment was raised by the ICLR2022 reviewers.We aim to evaluate the methods in different experiment settings.
import os, sys import pandas as pd import wandb import numpy as np from tqdm.notebook import tqdm import seaborn as sns import matplotlib.pyplot as plt from collections import defaultdict from IPython.display import display sns.set_style("ticks") cmap = sns.color_palette() sns.set_palette(sns.color_palette()) cache_pat...
_____no_output_____
MIT
ipynb/Digits vary budget distribution.ipynb
illidanlab/SplitMix
FedAvg
mode = 'FedAvg' api = wandb.Api() sweep = api.sweep(sweep_dict[mode]) df_dict = fetch_config_summary( sweep.runs, config_keys = ['width_scale'], summary_keys = ['avg test acc', 'GFLOPs', 'model size (MB)'] ) df = pd.DataFrame(df_dict) df['mode'] = mode df['width_scale'] = df['width_scale'] * 100 df['width'...
_____no_output_____
MIT
ipynb/Digits vary budget distribution.ipynb
illidanlab/SplitMix
SHeteroFL
mode = 'SHeteroFL' api = wandb.Api() sweep = api.sweep(sweep_dict[mode]) df_dict = fetch_config_summary( sweep.runs, config_keys = ['test_slim_ratio'], summary_keys = ['avg test acc', 'GFLOPs', 'model size (MB)'] ) df = pd.DataFrame(df_dict) df['test_slim_ratio'] = df['test_slim_ratio'] * 100 df['width'] =...
_____no_output_____
MIT
ipynb/Digits vary budget distribution.ipynb
illidanlab/SplitMix
Split-Mix
dfs = [] # for atom_slim_ratio in [0.125, 0.25]: for mode in ['SplitMix']: # , 'SplitMix incr']: print(f"mode: {mode}") api = wandb.Api() sweep = api.sweep(sweep_dict[mode]) df_dict = fetch_config_summary( sweep.runs, config_keys = ['test_slim_ratio', 'atom_slim_ratio'], summa...
_____no_output_____
MIT
ipynb/Digits vary budget distribution.ipynb
illidanlab/SplitMix
Aggregation
agg = pd.concat([v for k, v in agg_df_dict.items()]) cmap = sns.color_palette(as_cmap=True) len(cmap)
_____no_output_____
MIT
ipynb/Digits vary budget distribution.ipynb
illidanlab/SplitMix
more budget-sufficient clients
agg = pd.concat([v for k, v in agg_df_dict.items()]) agg = agg.reset_index() agg['avg test acc'] = agg['avg test acc'] * 100 agg['MFLOPs'] = agg['GFLOPs'] * 1e3 agg['method'] = agg['mode'].apply(lambda n: n if n != 'FedAvg' else 'Ind. FedAvg') agg['budgets'] = agg['slim_ratios'].apply(lambda n: (n.replace('d', '/')) if...
_____no_output_____
MIT
ipynb/Digits vary budget distribution.ipynb
illidanlab/SplitMix
step-increase budgets
agg = pd.concat([v for k, v in agg_df_dict.items()]) agg = agg.reset_index() agg['avg test acc'] = agg['avg test acc'] * 100 agg['MFLOPs'] = agg['GFLOPs'] * 1e3 agg['method'] = agg['mode'].apply(lambda n: n if n != 'FedAvg' else 'Ind. FedAvg') agg['budgets'] = agg['slim_ratios'].apply(lambda n: (n.replace('d', '/')) if...
_____no_output_____
MIT
ipynb/Digits vary budget distribution.ipynb
illidanlab/SplitMix
log normal budget distribution
ln_agg_df_dict = {} for mode in ['SplitMix ln', 'HeteroFL ln']: # 'SplitMix step=0.25 non-exp' api = wandb.Api() sweep = api.sweep(sweep_dict[mode]) print(f"mode: {mode}") api = wandb.Api() sweep = api.sweep(sweep_dict[mode]) df_dict = fetch_config_summary( sweep.runs, conf...
_____no_output_____
MIT
ipynb/Digits vary budget distribution.ipynb
illidanlab/SplitMix
*Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python" by [Sebastian Raschka](https://sebastianraschka.com). All code examples are released under the [MIT license](https://github.com/rasbt/deep-learning-book/blob/master/LICEN...
%load_ext watermark %watermark -a 'Sebastian Raschka' -v -p tensorflow,numpy
Sebastian Raschka CPython 3.6.1 IPython 6.1.0 tensorflow 1.1.0 numpy 1.12.1
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
Using Input Pipelines to Read Data from TFRecords Files TensorFlow provides users with multiple options for providing data to the model. One of the probably most common methods is to define placeholders in the TensorFlow graph and feed the data from the current Python session into the TensorFlow `Session` using the `f...
# Note that executing the following code # cell will download the MNIST dataset # and save all the 60,000 images as separate JPEG # files. This might take a few minutes depending # on your machine. import numpy as np from helper import mnist_export_to_jpg np.random.seed(123) mnist_export_to_jpg(path='./')
Extracting ./train-images-idx3-ubyte.gz Extracting ./train-labels-idx1-ubyte.gz Extracting ./t10k-images-idx3-ubyte.gz Extracting ./t10k-labels-idx1-ubyte.gz
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
The `mnist_export_to_jpg` function called above creates 3 directories, mnist_train, mnist_test, and mnist_validation. Note that the names of the subdirectories correspond directly to the class label of the images that are stored under it:
import os for i in ('train', 'valid', 'test'): dirs = [d for d in os.listdir('mnist_%s' % i) if not d.startswith('.')] print('mnist_%s subdirectories' % i, dirs)
mnist_train subdirectories ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] mnist_valid subdirectories ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] mnist_test subdirectories ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
To make sure that the images look okay, the snippet below plots an example image from the subdirectory `mnist_train/9/`:
%matplotlib inline import matplotlib.image as mpimg import matplotlib.pyplot as plt import os some_img = os.path.join('./mnist_train/9/', os.listdir('./mnist_train/9/')[0]) img = mpimg.imread(some_img) print(img.shape) plt.imshow(img, cmap='binary');
(28, 28)
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
Note: The JPEG format introduces a few artifacts that we can see in the image above. In this case, we use JPEG instead of PNG. Here, JPEG is used for demonstration purposes since that's still format many image datasets are stored in. 1. Saving images as TFRecords files First, we are going to convert the images into a ...
import glob import numpy as np import tensorflow as tf def images_to_tfrecords(data_stempath='./mnist_', shuffle=False, random_seed=None): def int64_to_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) for s i...
_____no_output_____
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
Note that it is important to shuffle the dataset so that we can later make use of TensorFlow's [`tf.train.shuffle_batch`](https://www.tensorflow.org/api_docs/python/tf/train/shuffle_batch) function and don't need to load the whole dataset into memory to shuffle epochs.
images_to_tfrecords(shuffle=True, random_seed=123)
_____no_output_____
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
Just to make sure that the images were serialized correctly, let us load an image back from TFRecords using the [`tf.python_io.tf_record_iterator`](https://www.tensorflow.org/api_docs/python/tf/python_io/tf_record_iterator) and display it:
import tensorflow as tf import numpy as np record_iterator = tf.python_io.tf_record_iterator(path='mnist_train.tfrecords') for r in record_iterator: example = tf.train.Example() example.ParseFromString(r) label = example.features.feature['label'].int64_list.value[0] print('Label:', label) im...
Label: 2
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
So far so good, the image above looks okay. In the next secction, we will introduce a slightly different approach for loading the images, namely, the [`TFRecordReader`](https://www.tensorflow.org/api_docs/python/tf/TFRecordReader), which we need to load images inside a TensorFlow graph. 2. Loading images via the TFRec...
def read_one_image(tfrecords_queue, normalize=True): reader = tf.TFRecordReader() key, value = reader.read(tfrecords_queue) features = tf.parse_single_example(value, features={'label': tf.FixedLenFeature([], tf.int64), 'image': tf.FixedLenFeature([784], tf.int64)}) label = tf....
_____no_output_____
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
To use this `read_one_image` function to fetch images in a TensorFlow session, we will make use of queue runners as illustrated in the following example:
g = tf.Graph() with g.as_default(): queue = tf.train.string_input_producer(['mnist_train.tfrecords'], num_epochs=10) label, image = read_one_image(queue) with tf.Session(graph=g) as sess: sess.run(tf.local_variables_initializer()) sess.run(tf.global_var...
Label: [ 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.] Image dimensions: (784,)
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
- The `tf.train.string_input_producer` produces a filename queue that we iterate over in the session. Note that we need to call `sess.run(tf.local_variables_initializer())` if we define a fixed number of `num_epochs` in `tf.train.string_input_producer`. Alternatively, `num_epochs` can be set to `None` to iterate "infin...
g = tf.Graph() with g.as_default(): queue = tf.train.string_input_producer(['mnist_train.tfrecords'], num_epochs=10) label, image = read_one_image(queue) label_batch, image_batch = tf.train.shuffle_batch([label, image], ...
Batch size: 64
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
The other relevant arguments we provided to `tf.train.shuffle_batch` are described below:- `capacity`: An integer that defines the maximum number of elements in the queue.- `min_after_dequeue`: The minimum number elements in the queue after a dequeue, which is used to ensure that a minimum number of data points have be...
########################## ### SETTINGS ########################## # Hyperparameters learning_rate = 0.1 batch_size = 128 n_epochs = 15 n_iter = n_epochs * (45000 // batch_size) # Architecture n_hidden_1 = 128 n_hidden_2 = 256 height, width = 28, 28 n_classes = 10 ########################## ### GRAPH DEFINITION ##...
Epoch: 001 | AvgCost: 0.007 Epoch: 002 | AvgCost: 0.469 Epoch: 003 | AvgCost: 0.240 Epoch: 004 | AvgCost: 0.183 Epoch: 005 | AvgCost: 0.151 Epoch: 006 | AvgCost: 0.128 Epoch: 007 | AvgCost: 0.110 Epoch: 008 | AvgCost: 0.099 Epoch: 009 | AvgCost: 0.087 Epoch: 010 | AvgCost: 0.078 Epoch: 011 | AvgCost: 0.070 Epoch: 012 |...
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
After looking at the graph above, you probably wondered why we used [`tf.placeholder_with_default`](https://www.tensorflow.org/api_docs/python/tf/placeholder_with_default) to define the two placeholders:```pythontf_images = tf.placeholder_with_default(image_batch, shape=[None,...
record_iterator = tf.python_io.tf_record_iterator(path='mnist_test.tfrecords') with tf.Session() as sess: saver1 = tf.train.import_meta_graph('./mlp.meta') saver1.restore(sess, save_path='./mlp') num_correct = 0 for idx, r in enumerate(record_iterator): example = tf.train.Example() ...
INFO:tensorflow:Restoring parameters from ./mlp Test accuracy: 97.3%
MIT
code/model_zoo/tensorflow_ipynb/tfrecords.ipynb
wpsliu123/Sebastian_Raschka-Deep-Learning-Book
The Binomial Distribution Let $X_1, X_2, \ldots , X_n$ be i.i.d. Bernoulli $(p)$ random variables and let $S_n = X_1 + X_2 \ldots + X_n$. That's a formal way of saying:- Suppose you have a fixed number $n$ of success/failure trials; and- the trials are independent; and- on each trial, the probability of success is $p...
from scipy import stats
_____no_output_____
MIT
notebooks/Chapter_06/01_Binomial_Distribution.ipynb
choldgraf/prob140
The function `stats.binom.pmf` takes three arguments: $k$, $n$, and $p$, in that order. It returns the numerical value of $P(S_n = k)$ For short, we will say that the function returns the binomial $(n, p)$ probability of $k$.The acronym "pmf" stands for "probability mass function" which as we have noted earlier is some...
stats.binom.pmf(3, 7, 1/6)
_____no_output_____
MIT
notebooks/Chapter_06/01_Binomial_Distribution.ipynb
choldgraf/prob140
You can also specify an array or list of values of $k$, and `stats.binom.pmf` will return an array consisting of all their probabilities.
stats.binom.pmf([2, 3, 4], 7, 1/6)
_____no_output_____
MIT
notebooks/Chapter_06/01_Binomial_Distribution.ipynb
choldgraf/prob140
Thus to find $P(2 \le S_7 \le 4)$, you can use
sum(stats.binom.pmf([2, 3, 4], 7, 1/6))
_____no_output_____
MIT
notebooks/Chapter_06/01_Binomial_Distribution.ipynb
choldgraf/prob140
Binomial Histograms To visualize binomial distributions we will use the `prob140` method `Plot`, by first using `stats.binom.pmf` to calculate the binomial probabilities. The cell below plots the distribution of $S_7$ above. Notice how we start by specifying all the possible values of $S_7$ in the array `k`.
n = 7 p = 1/6 k = np.arange(n+1) binom_7_1_6 = stats.binom.pmf(k, n, p) binom_7_1_6_dist = Table().values(k).probability(binom_7_1_6) Plot(binom_7_1_6_dist)
_____no_output_____
MIT
notebooks/Chapter_06/01_Binomial_Distribution.ipynb
choldgraf/prob140
Not surprisingly, the graph shows that in 7 rolls of a die you are most likely to get around 1 six.This distribution is not symmetric, as you would expect. But something interesting happens to the distribution of the number of sixes when you increase the number of rolls.
n = 600 p = 1/6 k = np.arange(n+1) binom_600_1_6 = stats.binom.pmf(k, n, p) binom_600_1_6_dist = Table().values(k).probability(binom_600_1_6) Plot(binom_600_1_6_dist)
_____no_output_____
MIT
notebooks/Chapter_06/01_Binomial_Distribution.ipynb
choldgraf/prob140
This distribution is close to symmetric, even though the die has only a 1/6 chance of showing a six.Also notice that while the the *possible* values of the number of sixes range from 0 to 600, the *probable* values are in a much smaller range. The `plt.xlim` function allows us to zoom in on the probable values. The sem...
Plot(binom_600_16_dist, edges=True) plt.xlim(70, 130);
_____no_output_____
MIT
notebooks/Chapter_06/01_Binomial_Distribution.ipynb
choldgraf/prob140
But the binomial $(n, p)$ distribution doesn't always look bell shaped if $n$ is large.Something quite different happens if for example your random variable is the number of successes in 600 independent trials that have probability 1/600 of success on each trial. Then the distribution of the number of successes is bino...
n = 600 p = 1/600 k = np.arange(n+1) binom_600_1_600 = stats.binom.pmf(k, n, p) binom_600_1_600_dist = Table().values(k).probability(binom_600_1_600) Plot(binom_600_1_600_dist)
_____no_output_____
MIT
notebooks/Chapter_06/01_Binomial_Distribution.ipynb
choldgraf/prob140
We really can't see that at all! Let's zoom in. When we set the limits on the horizontal axis, we have to account for the bar at 0 being centered at the 0 and hence starting at -0.5.
Plot(binom_600_1_600_dist, edges=True) plt.xlim(-1, 10);
_____no_output_____
MIT
notebooks/Chapter_06/01_Binomial_Distribution.ipynb
choldgraf/prob140
Chapter 1- toc: true - badges: true- comments: true- categories: [Python,Deeplearning] 1.1 신경망 연구의 역사 1.1.1 다층 신경망에 대한 기대와 실망
- (1)
_____no_output_____
Apache-2.0
_notebooks/2021-07-28-deepl.ipynb
junhyeongpak/juniorpaak
"Neural Network Visualizer Streamlit App"> Visualize the predictions of your intermediate neural network layers- toc: false- branch: master- badges: true- comments: true- categories: [visualization, streamlit, explainable-AI]- image: images/some_folder/your_image.png- hide: false- search_exclude: true Import Librarie...
%matplotlib inline import tensorflow as tf import numpy as np import matplotlib.pyplot as plt
_____no_output_____
Apache-2.0
_notebooks/2020-10-13-Neural Network Visualizer Web app.ipynb
sharanbabu19/sharan19
Download Data
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
_____no_output_____
Apache-2.0
_notebooks/2020-10-13-Neural Network Visualizer Web app.ipynb
sharanbabu19/sharan19
Plot Examples
plt.figure(figsize=(10, 10)) for i in range(16): plt.subplot(4, 4, i + 1) plt.imshow(x_train[i], cmap='binary') plt.xlabel(str(y_train[i])) plt.xticks([]) plt.yticks([]) plt.show()
_____no_output_____
Apache-2.0
_notebooks/2020-10-13-Neural Network Visualizer Web app.ipynb
sharanbabu19/sharan19
Normalize Data
x_train = np.reshape(x_train, (60000, 784)) x_train = x_train / 255. x_test = np.reshape(x_test, (10000, 784)) x_test = x_test / 255.
_____no_output_____
Apache-2.0
_notebooks/2020-10-13-Neural Network Visualizer Web app.ipynb
sharanbabu19/sharan19
Create a Neural Network Model
model = tf.keras.models.Sequential([ tf.keras.layers.Dense(32, activation='sigmoid', input_shape=(784,)), tf.keras.layers.Dense(32, activation='sigmoid'), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
_____no_output_____
Apache-2.0
_notebooks/2020-10-13-Neural Network Visualizer Web app.ipynb
sharanbabu19/sharan19
Train the Model
_ = model.fit( x_train, y_train, validation_data=(x_test, y_test), epochs=20, batch_size=1024, verbose=2 )
Train on 60000 samples, validate on 10000 samples Epoch 1/20 60000/60000 - 1s - loss: 2.1994 - accuracy: 0.3593 - val_loss: 1.9857 - val_accuracy: 0.6710 Epoch 2/20 60000/60000 - 0s - loss: 1.7957 - accuracy: 0.6828 - val_loss: 1.5774 - val_accuracy: 0.7260 Epoch 3/20 60000/60000 - 0s - loss: 1.3886 - accuracy: 0.7427 ...
Apache-2.0
_notebooks/2020-10-13-Neural Network Visualizer Web app.ipynb
sharanbabu19/sharan19
Save the Model
model.save('model.h5')
_____no_output_____
Apache-2.0
_notebooks/2020-10-13-Neural Network Visualizer Web app.ipynb
sharanbabu19/sharan19
ml_server.py
import json import tensorflow as tf import numpy as np import os import random import string from flask import Flask, request app = Flask(__name__) model = tf.keras.models.load_model('model.h5') feature_model = tf.keras.models.Model(model.inputs, [layer.output for layer in model.layers]) _, (x_test, _) = tf.keras.d...
_____no_output_____
Apache-2.0
_notebooks/2020-10-13-Neural Network Visualizer Web app.ipynb
sharanbabu19/sharan19
app.py
import requests import json import numpy as np import streamlit as st import os import matplotlib.pyplot as plt URI = 'http://127.0.0.1:5000' st.title('Neural Network Visualizer') st.sidebar.markdown('# Input Image') if st.button('Get random predictions'): response = requests.post(URI, data={}) # print(respo...
_____no_output_____
Apache-2.0
_notebooks/2020-10-13-Neural Network Visualizer Web app.ipynb
sharanbabu19/sharan19
TensorFlow TutorialWelcome to this week's programming assignment. Until now, you've always used numpy to build neural networks. Now we will step you through a deep learning framework that will allow you to build neural networks more easily. Machine learning frameworks like TensorFlow, PaddlePaddle, Torch, Caffe, Keras...
import math import numpy as np import h5py import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.python.framework import ops from tf_utils import load_dataset, random_mini_batches, convert_to_one_hot, predict %matplotlib inline np.random.seed(1)
_____no_output_____
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
Now that you have imported the library, we will walk you through its different applications. You will start with an example, where we compute for you the loss of one training example. $$loss = \mathcal{L}(\hat{y}, y) = (\hat y^{(i)} - y^{(i)})^2 \tag{1}$$
y_hat = tf.constant(36, name='y_hat') # Define y_hat constant. Set to 36. y = tf.constant(39, name='y') # Define y. Set to 39 loss = tf.Variable((y - y_hat)**2, name='loss') # Create a variable for the loss init = tf.global_variables_initializer() # When init is run later (sessi...
9
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
Writing and running programs in TensorFlow has the following steps:1. Create Tensors (variables) that are not yet executed/evaluated. 2. Write operations between those Tensors.3. Initialize your Tensors. 4. Create a Session. 5. Run the Session. This will run the operations you'd written above. Therefore, when we create...
a = tf.constant(2) b = tf.constant(10) c = tf.multiply(a,b) print(c)
Tensor("Mul:0", shape=(), dtype=int32)
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
As expected, you will not see 20! You got a tensor saying that the result is a tensor that does not have the shape attribute, and is of type "int32". All you did was put in the 'computation graph', but you have not run this computation yet. In order to actually multiply the two numbers, you will have to create a sessio...
sess = tf.Session() print(sess.run(c))
20
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
Great! To summarize, **remember to initialize your variables, create a session and run the operations inside the session**. Next, you'll also have to know about placeholders. A placeholder is an object whose value you can specify only later. To specify values for a placeholder, you can pass in values by using a "feed d...
# Change the value of x in the feed_dict x = tf.placeholder(tf.int64, name = 'x') print(sess.run(2 * x, feed_dict = {x: 3})) sess.close()
6
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
When you first defined `x` you did not have to specify a value for it. A placeholder is simply a variable that you will assign data to only later, when running the session. We say that you **feed data** to these placeholders when running the session. Here's what's happening: When you specify the operations needed for a...
# GRADED FUNCTION: linear_function def linear_function(): """ Implements a linear function: Initializes X to be a random tensor of shape (3,1) Initializes W to be a random tensor of shape (4,3) Initializes b to be a random tensor of shape (4,1) Returns: result -- r...
result = [[-2.15657382] [ 2.95891446] [-1.08926781] [-0.84538042]]
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
*** Expected Output ***: ```result = [[-2.15657382] [ 2.95891446] [-1.08926781] [-0.84538042]]``` 1.2 - Computing the sigmoid Great! You just implemented a linear function. Tensorflow offers a variety of commonly used neural network functions like `tf.sigmoid` and `tf.softmax`. For this exercise lets compute the sigmo...
# GRADED FUNCTION: sigmoid def sigmoid(z): """ Computes the sigmoid of z Arguments: z -- input value, scalar or vector Returns: results -- the sigmoid of z """ # Create a placeholder for x. Name it 'x'. x = tf.placeholder(tf.float32, name = 'x') # compute sigmoi...
sigmoid(0) = 0.5 sigmoid(12) = 0.999994
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
*** Expected Output ***: **sigmoid(0)**0.5 **sigmoid(12)**0.999994 **To summarize, you how know how to**:1. Create placeholders2. Specify the computation graph corresponding to operations you want to compute3. Create the session4. Run the session, using a feed dictionary if necessary to specify placeholder variable...
# GRADED FUNCTION: cost def cost(logits, labels): """     Computes the cost using the sigmoid cross entropy          Arguments:     logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)     labels -- vector of labels y (1 or 0) Note: What we've been calling "...
cost = [ 0.79813886 0.91301525 0.40318605 0.34115386]
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
** Expected Output** : ```cost = [ 0.79813886 0.91301525 0.40318605 0.34115386]``` 1.4 - Using One Hot encodingsMany times in deep learning you will have a y vector with numbers ranging from 0 to C-1, where C is the number of classes. If C is for example 4, then you might have the following y vector which you will ...
# GRADED FUNCTION: one_hot_matrix def one_hot_matrix(labels, C): """ Creates a matrix where the i-th row corresponds to the ith class number and the jth column corresponds to the jth training example. So if example j had a label i. Then entry (i,j) will be 1. ...
one_hot = [[ 0. 0. 0. 1. 0. 0.] [ 1. 0. 0. 0. 0. 1.] [ 0. 1. 0. 0. 1. 0.] [ 0. 0. 1. 0. 0. 0.]]
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
**Expected Output**: ```one_hot = [[ 0. 0. 0. 1. 0. 0.] [ 1. 0. 0. 0. 0. 1.] [ 0. 1. 0. 0. 1. 0.] [ 0. 0. 1. 0. 0. 0.]]``` 1.5 - Initialize with zeros and onesNow you will learn how to initialize a vector of zeros and ones. The function you will be calling is `tf.ones()`. To initialize with zeros y...
# GRADED FUNCTION: ones def ones(shape): """ Creates an array of ones of dimension shape Arguments: shape -- shape of the array you want to create Returns: ones -- array containing only ones """ # Create "ones" tensor using tf.ones(...). (approx. 1 line) ones = t...
ones = [ 1. 1. 1.]
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
**Expected Output:** **ones** [ 1. 1. 1.] 2 - Building your first neural network in tensorflowIn this part of the assignment you will build a neural network using tensorflow. Remember that there are two parts to implement a tensorflow model:- Create the com...
# Loading the dataset X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
_____no_output_____
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
Change the index below and run the cell to visualize some examples in the dataset.
# Example of a picture index = 0 plt.imshow(X_train_orig[index]) print ("y = " + str(np.squeeze(Y_train_orig[:, index])))
y = 5
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
As usual you flatten the image dataset, then normalize it by dividing by 255. On top of that, you will convert each label to a one-hot vector as shown in Figure 1. Run the cell below to do so.
# Flatten the training and test images X_train_flatten = X_train_orig.reshape(X_train_orig.shape[0], -1).T X_test_flatten = X_test_orig.reshape(X_test_orig.shape[0], -1).T # Normalize image vectors X_train = X_train_flatten/255. X_test = X_test_flatten/255. # Convert training and test labels to one hot matrices Y_train...
number of training examples = 1080 number of test examples = 120 X_train shape: (12288, 1080) Y_train shape: (6, 1080) X_test shape: (12288, 120) Y_test shape: (6, 120)
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
**Note** that 12288 comes from $64 \times 64 \times 3$. Each image is square, 64 by 64 pixels, and 3 is for the RGB colors. Please make sure all these shapes make sense to you before continuing. **Your goal** is to build an algorithm capable of recognizing a sign with high accuracy. To do so, you are going to build a t...
# GRADED FUNCTION: create_placeholders def create_placeholders(n_x, n_y): """ Creates the placeholders for the tensorflow session. Arguments: n_x -- scalar, size of an image vector (num_px * num_px = 64 * 64 * 3 = 12288) n_y -- scalar, number of classes (from 0 to 5, so -> 6) Returns:...
X = Tensor("X_1:0", shape=(12288, ?), dtype=float32) Y = Tensor("Y_1:0", shape=(6, ?), dtype=float32)
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
**Expected Output**: **X** Tensor("Placeholder_1:0", shape=(12288, ?), dtype=float32) (not necessarily Placeholder_1) **Y** Tensor("Placeholder_2:0", shape=(6, ?), dtype=float32) (not necessarily Placeholder_2) ...
# GRADED FUNCTION: initialize_parameters def initialize_parameters(): """ Initializes parameters to build a neural network with tensorflow. The shapes are: W1 : [25, 12288] b1 : [25, 1] W2 : [12, 25] b2 : [12, 1] ...
W1 = <tf.Variable 'W1:0' shape=(25, 12288) dtype=float32_ref> b1 = <tf.Variable 'b1:0' shape=(25, 1) dtype=float32_ref> W2 = <tf.Variable 'W2:0' shape=(12, 25) dtype=float32_ref> b2 = <tf.Variable 'b2:0' shape=(12, 1) dtype=float32_ref>
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
**Expected Output**: **W1** **b1** **W2** **b2** As expected, the parameters ...
# GRADED FUNCTION: forward_propagation def forward_propagation(X, parameters): """ Implements the forward propagation for the model: LINEAR -> RELU -> LINEAR -> RELU -> LINEAR -> SOFTMAX Arguments: X -- input dataset placeholder, of shape (input size, number of examples) parameters -- python d...
Z3 = Tensor("Add_2:0", shape=(6, ?), dtype=float32)
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
**Expected Output**: **Z3** Tensor("Add_2:0", shape=(6, ?), dtype=float32) You may have noticed that the forward propagation doesn't output any cache. You will understand why below, when we get to brackpropagation. 2.4 Compute costAs seen before, it is very ...
# GRADED FUNCTION: compute_cost def compute_cost(Z3, Y): """ Computes the cost Arguments: Z3 -- output of forward propagation (output of the last LINEAR unit), of shape (6, number of examples) Y -- "true" labels vector placeholder, same shape as Z3 Returns: cost - Tensor of the c...
cost = Tensor("Mean:0", shape=(), dtype=float32)
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
**Expected Output**: **cost** Tensor("Mean:0", shape=(), dtype=float32) 2.5 - Backward propagation & parameter updatesThis is where you become grateful to programming frameworks. All the backpropagation and the parameters update is taken care of in 1 line of...
def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001, num_epochs = 1500, minibatch_size = 32, print_cost = True): """ Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX. Arguments: X_train -- training set, of shape (input size = 1...
_____no_output_____
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
Run the following cell to train your model! On our machine it takes about 5 minutes. Your "Cost after epoch 100" should be 1.048222. If it's not, don't waste time; interrupt the training by clicking on the square (⬛) in the upper bar of the notebook, and try to correct your code. If it is the correct cost, take a break...
parameters = model(X_train, Y_train, X_test, Y_test)
Cost after epoch 0: 1.913693 Cost after epoch 100: 1.048222 Cost after epoch 200: 0.756012 Cost after epoch 300: 0.590844 Cost after epoch 400: 0.483423 Cost after epoch 500: 0.392928 Cost after epoch 600: 0.323629 Cost after epoch 700: 0.262100 Cost after epoch 800: 0.210199 Cost after epoch 900: 0.171622 Cost after e...
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
**Expected Output**: **Train Accuracy** 0.999074 **Test Accuracy** 0.716667 Amazing, your algorithm can recognize a sign representing a figure between 0 and 5 with 71.7% accuracy.**Insights**:- Your mod...
import scipy from PIL import Image from scipy import ndimage ## START CODE HERE ## (PUT YOUR IMAGE NAME) my_image = "thumbs_up.jpg" ## END CODE HERE ## # We preprocess your image to fit your algorithm. fname = "images/" + my_image image = np.array(ndimage.imread(fname, flatten=False)) image = image/255. my_image = s...
_____no_output_____
MIT
4. Convolutional Neural Networks/tensorflow_deep_nn.ipynb
c-abbott/deep-learning
Comparing calibrated analytical with E2E imagesIn the process of generating the analytical matrix with `matrix_building_analytical.py` the code produces *calibrated* pair-wise aberrated analytical images. The script `matrix_building_analytical.py` does the same thing but produces pair-wise aberrated E2E images. In thi...
import os import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import LogNorm from astropy.io import fits %matplotlib inline os.chdir('../../pastis/') from config import CONFIG_INI import util_pastis as util # Reading parameters from configfile which_tel = CONFIG_INI.get('telescope', 'name') nb_se...
_____no_output_____
BSD-3-Clause
Jupyter Notebooks/JWST and WebbPSF/8_Comparing calibrated analytical with E2E images.ipynb
ivalaginja/PASTIS
Task 2b: Extracting data from OCR'd PDFs Import the needed libraries. We'll be using the amazing [pdfplumber](https://github.com/jsvine/pdfplumber) to gather lines from the account PDF.
import pdfplumber import pandas as pd from matplotlib.patches import Rectangle import matplotlib.pyplot as plt from decimal import Decimal import re %matplotlib inline
_____no_output_____
MIT
2b-pdf-plumber.ipynb
drkane/pdf-accounts
Function for printing a diagram with the boundaries of the words on a page.
def print_words(p): fig = plt.figure(figsize=(4,6)) ax = fig.add_axes([0,0,1,1]) _ = ax.set_xlim(left=0, right=int(p.width)) _ = ax.set_ylim(top=0, bottom=int(p.height)) for i in p.extract_words(): r = Rectangle( # (left, bottom), width, height, (i['x0'], i['bottom']...
_____no_output_____
MIT
2b-pdf-plumber.ipynb
drkane/pdf-accounts
Get a sample PDFThis is a PDF that has been OCR'ed using the process in task 2a. The `p` variable represents the page with the Balance Sheet on.
pdf = pdfplumber.open("test_accounts.pdf") p = pdf.pages[19]
_____no_output_____
MIT
2b-pdf-plumber.ipynb
drkane/pdf-accounts
Here's a representation of what the page looks like.
print_words(p)
_____no_output_____
MIT
2b-pdf-plumber.ipynb
drkane/pdf-accounts
Approach 1: Use inbuilt `extract_table` functionThis approach does find a table, but it's not great for getting at the data within.
pd.DataFrame(p.extract_table({ "horizontal_strategy": "text", "vertical_strategy": "text", "snap_tolerance": 6, "join_tolerance": 2, }))
_____no_output_____
MIT
2b-pdf-plumber.ipynb
drkane/pdf-accounts
Approach 2: Detecting linesThis function should output a series of recetangles giving separated lines in a PDF page. It's based on finding gaps between lines, so relies on there being vertical white space.
def detect_lines(p, x_tolerance=0): """ Detect lines in a PDF page """ cells = pd.DataFrame(p.extract_words(x_tolerance=x_tolerance)).sort_values(["top", "x0"]) row_ranges = [] this_range = [] for i in range(0, int(p.height)): result = ((cells['bottom'] >= i) & (cells['top'] <= i)).s...
_____no_output_____
MIT
2b-pdf-plumber.ipynb
drkane/pdf-accounts
Draw a picture of the page with the lines highlighted.
im = p.to_image() im.draw_rects(detect_lines(p, 0))
_____no_output_____
MIT
2b-pdf-plumber.ipynb
drkane/pdf-accounts
Approach 3: Use the `extract_text` function to get linesOnce the lines have been found, use a regex to find the data.
p.extract_text(y_tolerance=30).split('\n') def get_finances(pdf): finance_regex = r'(.*)\s+(\(?\-?[\,0-9]+\)?)\s+(\(?\-?[\,0-9]+\)?)$' def process_match(match): match = { "text": match[0], "value1": match[1], "value2": match[2] } for i in ("v...
_____no_output_____
MIT
2b-pdf-plumber.ipynb
drkane/pdf-accounts