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 |
|---|---|---|---|---|---|
https://xavierbourretsicotte.github.io/LDA_QDA.html | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib.colors as colors
# from mpl_toolkits.mplot3d import Axes3D
# from mpl_toolkits import mplot3d
from sklearn import linear_model, datasets
import seaborn as sns
import itertools
%matplotlib inline
sns.set()
#plt.style.use('seab... | /usr/local/lib/python3.7/dist-packages/seaborn/axisgrid.py:316: UserWarning: The `size` parameter has been renamed to `height`; please update your code.
warnings.warn(msg, UserWarning)
| MIT | Chapter 4/Python/discriminant analysis/QDA visualization from outside.ipynb | borisgarbuzov/schulich_data_science_1 |
Visualizing the gaussian estimations and the boundary lines | #Estimating the parameters
mu_list = np.split(df1.groupby('species').mean().values,[1,2])
sigma = df1.cov().values
pi_list = df1.iloc[:,2].value_counts().values / len(df1)
# Our 2-dimensional distribution will be over variables X and Y
N = 100
X = np.linspace(3, 8, N)
Y = np.linspace(1.5, 5, N)
X, Y = np.meshgrid(X, Y... | /usr/local/lib/python3.7/dist-packages/seaborn/axisgrid.py:316: UserWarning: The `size` parameter has been renamed to `height`; please update your code.
warnings.warn(msg, UserWarning)
| MIT | Chapter 4/Python/discriminant analysis/QDA visualization from outside.ipynb | borisgarbuzov/schulich_data_science_1 |
Visualizing the Gaussian estimations with different covariance matrices | #Estimating the parameters
mu_list = np.split(df1.groupby('species').mean().values,[1,2])
sigma_list = np.split(df1.groupby('species').cov().values,[2,4], axis = 0)
pi_list = df1.iloc[:,2].value_counts().values / len(df1)
# Our 2-dimensional distribution will be over variables X and Y
N = 100
X = np.linspace(3, 8, N)
... | /usr/local/lib/python3.7/dist-packages/seaborn/axisgrid.py:316: UserWarning: The `size` parameter has been renamed to `height`; please update your code.
warnings.warn(msg, UserWarning)
| MIT | Chapter 4/Python/discriminant analysis/QDA visualization from outside.ipynb | borisgarbuzov/schulich_data_science_1 |
Visualizing the quadratic boundary curves | #Estimating the parameters
mu_list = np.split(df1.groupby('species').mean().values,[1,2])
sigma_list = np.split(df1.groupby('species').cov().values,[2,4], axis = 0)
pi_list = df1.iloc[:,2].value_counts().values / len(df1)
# Our 2-dimensional distribution will be over variables X and Y
N = 200
X = np.linspace(4, 8, N)
... | /usr/local/lib/python3.7/dist-packages/seaborn/axisgrid.py:316: UserWarning: The `size` parameter has been renamed to `height`; please update your code.
warnings.warn(msg, UserWarning)
| MIT | Chapter 4/Python/discriminant analysis/QDA visualization from outside.ipynb | borisgarbuzov/schulich_data_science_1 |
QDA Accuracy | from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
X_data = df1.iloc[:,0:2]
y_labels = df1.iloc[:,2].replace({'setosa':0,'versicolor':1,'virginica':2}).copy()
qda = QuadraticDiscriminantAnalysis(store_covariance=True)
qda.fit(X_data,y_labels)
#Numpy accuracy
y_pred = np.array( [predict_QDA_class... | _____no_output_____ | MIT | Chapter 4/Python/discriminant analysis/QDA visualization from outside.ipynb | borisgarbuzov/schulich_data_science_1 |
03 Geometric Machine Learning for Shape Analysis E) Unsupervised Learning: Dimension Reduction$\color{003660}{\text{Nina Miolane - Assistant Professor}}$ @ BioShape Lab @ UCSB ECE This Unit- **Unit 1 (Geometry - Math!)**: Differential Geometry for Engineers- **Unit 2 (Shapes)**: Computational Representations of Biom... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.patches as mpatches
import warnings
warnings.filterwarnings("ignore")
import geomstats.datasets.utils as data_utils
ne... | (22, 5, 3)
[0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]
[ 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10]
| MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
Plot two optical shapes: | two_nerves = nerves[monkeys == 0]
print(two_nerves.shape)
two_labels = labels[monkeys == 0]
print(two_labels)
label_to_str = {0: "Normal nerve", 1: "Glaucoma nerve"}
label_to_color = {
0: (102 / 255, 178 / 255, 255 / 255, 1.0),
1: (255 / 255, 178 / 255, 102 / 255, 1.0),
}
fig = plt.figure(); ax = Axes3D(fig); ... | _____no_output_____ | MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
Refresher: Traditional Principal Component Analysis $\color{EF5645}{\text{Principal Component Analysis (PCA)}}$ is an:- orthogonal projection of the data (belonging to a vector space $\mathbb{R}^D$),- into a (lower dimensional) linear subspace $\mathbb{R}^d$, $d < D$, - so that the variance of the projected data is ma... | from geomstats.geometry.hyperboloid import Hyperboloid
from geomstats.learning.frechet_mean import FrechetMean
from geomstats.learning.pca import TangentPCA
import matplotlib.pyplot as plt
import numpy as np
import geomstats.visualization as viz | _____no_output_____ | MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
1. Set-up- $\color{EF5645}{\text{Decide on the model:}}$ We use tangent PCA- $\color{EF5645}{\text{Decide on a loss function:}}$ Minimize -variance | # Synthetic data
hyperbolic_plane = Hyperboloid(dim=2)
data = hyperbolic_plane.random_point(n_samples=140)
# Set-up
mean = FrechetMean(metric=hyperbolic_plane.metric)
tpca = TangentPCA(metric=hyperbolic_plane.metric, n_components=2) | _____no_output_____ | MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
2. $\color{EF5645}{\text{Split dataset into train / test sets:}}$ - Train $X_1, ..., X_{n_\text{train}}$: build the algorithm - Test $X_{n_\text{train}+1}, ..., X_n$: assess its performances. | from sklearn.model_selection import train_test_split
train, test = train_test_split(data)
print(train.shape)
print(test.shape) | (105, 3)
(35, 3)
| MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
3. $\color{EF5645}{\text{Train:}}$ Build the algorithm | mean.fit(train)
mean_estimate = mean.estimate_
tpca = tpca.fit(train, base_point=mean_estimate)
tangent_projected_data = tpca.transform(train) | _____no_output_____ | MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
4. $\color{EF5645}{\text{Test:}}$ Assess its performances | geodesic_0 = hyperbolic_plane.metric.geodesic(
initial_point=mean_estimate, initial_tangent_vec=tpca.components_[0]
)
geodesic_1 = hyperbolic_plane.metric.geodesic(
initial_point=mean_estimate, initial_tangent_vec=tpca.components_[1]
)
n_steps = 100
t = np.linspace(-1, 1, n_steps)
geodesic_poin... | _____no_output_____ | MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
On Kendall Shape Spaces | from geomstats.geometry.pre_shape import PreShapeSpace, KendallShapeMetric
m_ambient = 3
k_landmarks = 5
preshape = PreShapeSpace(m_ambient=m_ambient, k_landmarks=k_landmarks)
matrices_metric = preshape.embedding_metric
nerves_preshape = preshape.projection(nerves)
print(nerves_preshape.shape)
print(preshape.belong... | _____no_output_____ | MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
1. Set-up- $\color{EF5645}{\text{Decide on the model:}}$ We use tangent PCA- $\color{EF5645}{\text{Decide on a loss function:}}$ Minimize -variance | kendall_metric = KendallShapeMetric(m_ambient=m_ambient, k_landmarks=k_landmarks)
tpca = TangentPCA(kendall_metric) | _____no_output_____ | MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
2. $\color{EF5645}{\text{Split dataset into train / test sets:}}$ - Train $X_1, ..., X_{n_\text{train}}$: build the algorithm - Test $X_{n_\text{train}+1}, ..., X_n$: assess its performances. | from sklearn.model_selection import train_test_split
train_nerves_shape = nerves_shape[:18]
test_nerves_shape = nerves_shape[18:]
print(train_nerves_shape.shape)
print(test_nerves_shape.shape)
| (18, 5, 3)
(4, 5, 3)
| MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
3. $\color{EF5645}{\text{Train:}}$ Build the algorithm | tpca.fit(train_nerves_shape)
plt.plot(tpca.explained_variance_ratio_)
plt.xlabel("Number of principal tangent components", size=14)
plt.ylabel("Fraction of explained variance", size=14); | _____no_output_____ | MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
Two principal components describe around 60% of the variance. We plot the data projected in the tangent space defined by these two principal components. 4. $\color{EF5645}{\text{Test:}}$ Assess its performances- We project the whole dataset on the principal components. | X = tpca.transform(nerves_shape)
plt.figure(figsize=(11, 11))
for label, col in label_to_color.items():
mask = labels == label
plt.scatter(X[mask, 0], X[mask, 1], color=col, s=100, label=label_to_str[label])
plt.legend(fontsize=14)
for label, x, y in zip(monkeys, X[:, 0], X[:, 1]):
plt.annotate(label, xy=(x... | _____no_output_____ | MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
Dimension Reduction Method 2: Principal Geodesic Analysis - Variance. Following the work of Frรฉchet, we define the sample variance of the data as the expected value of the squared Riemannian distance from the mean.- Geodesic subspaces. The lower-dimensional subspaces in PCA are linear subspaces. For general manifolds ... | - The subspace $V_{k}=\operatorname{span}\left(\left\{v_{1}, \ldots, v_{k}\right\}\right)$ is:
- the $k$-dimensional subspace
- that maximizes the variance
- of the data projected to that subspace: $\pi_{V_1}(x_i) = v \cdot x_{i}$ | _____no_output_____ | MIT | lectures/03_e_dimension_reduction.ipynb | bioshape-lab/ece594n |
Label Detection. Face Detection and Comparison, Celebrity Recognition, Image moderation, Text in image detection | import cv2
import boto3
import numpy as np
import os
import matplotlib.pyplot as plt
# Helpers
def show_image(filename):
image = cv2.imread(filename)
plt.imshow(image)
plt.show()
# Change color channels
def show_image_rgb(filename):
image = cv2.imread(filename)
plt.imshow(cv2.cvtColor(image, cv... | _____no_output_____ | MIT | Rekognition.ipynb | jsalomon-mdsol/medihack-aws-code |
In this notebook I'm generating the movements and the states variables (torques and angles) in order to produce this movement using the 2dof simulator. Some of the algorithms (or inspiration) to simulate the 2dof arm came from: http://www.gribblelab.org/compneuro/ Here starts the 2 joint arm study Main functions to ... | # Makes possible to show the output from matplotlib inline
%matplotlib inline
import matplotlib.pyplot as plt
# Makes the figures in the PNG format:
# For more information see %config InlineBackend
%config InlineBackend.figure_formats=set([u'png'])
plt.rcParams['figure.figsize'] = 20, 10
import numpy
import sys
impo... | _____no_output_____ | MIT | 2DofArm_simulation_data_generator_and_physics.ipynb | ricardodeazambuja/IJCNN2017 |
End of the main functions! Adjusting the parameters: | # Experiment identifier
sim_sets = ["set_A", "set_B", "set_C", "set_D"]
sim_set = sim_sets[0]
# Base dir to save / access
base_dir = "2DofArm_simulation_data"
# List with all trajectories to be generated
# [[[start_x,start_y],[final_x,final_y]],...]
trajectories = [[[0.75,0.25],[0.0,0.5]], [[0.25,0.60],[-0.25,0.60]]... | CPU times: user 15.6 ms, sys: 6.15 ms, total: 21.7 ms
Wall time: 1.69 s
| MIT | 2DofArm_simulation_data_generator_and_physics.ipynb | ricardodeazambuja/IJCNN2017 |
Plotly - Create Waterfall chart (Advanced) **Tags:** plotly chart warterfall dataviz Input Install packages | !pip install numpy
!pip install matplotlib | _____no_output_____ | BSD-3-Clause | Plotly/Create Waterfall chart (Advanced).ipynb | Charles-de-Montigny/awesome-notebooks |
Import library | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter | _____no_output_____ | BSD-3-Clause | Plotly/Create Waterfall chart (Advanced).ipynb | Charles-de-Montigny/awesome-notebooks |
Model Create the waterfall chart | #Use python 2.7+ syntax to format currency
def money(x, pos):
'The two args are the value and tick position'
return "${:,.0f}".format(x)
formatter = FuncFormatter(money)
#Data to plot. Do not include a total, it will be calculated
index = ['sales','returns','credit fees','rebates','late charges','shipping']
da... | _____no_output_____ | BSD-3-Clause | Plotly/Create Waterfall chart (Advanced).ipynb | Charles-de-Montigny/awesome-notebooks |
Output Display result | #Scale up the y axis so there is room for the labels
my_plot.set_ylim(0,blank.max()+int(plot_offset))
#Rotate the labels
my_plot.set_xticklabels(trans.index,rotation=0)
my_plot.get_figure().savefig("waterfall.png",dpi=200,bbox_inches='tight') | _____no_output_____ | BSD-3-Clause | Plotly/Create Waterfall chart (Advanced).ipynb | Charles-de-Montigny/awesome-notebooks |
State feedback control for the mass-spring-damper systemGiven the mass-spring-damper system, we want to control it in order to have a step response with zero error at steady state and a settling time for 5% tolerance band of less than 6 s.The system's equations written in state space form are:$$\begin{bmatrix}\dot{x_1... | %matplotlib inline
import control as control
import numpy
import sympy as sym
from IPython.display import display, Markdown
import ipywidgets as widgets
import matplotlib.pyplot as plt
#print a matrix latex-like
def bmatrix(a):
"""Returns a LaTeX bmatrix - by Damir Arbula (ICCT project)
:a: numpy array
... | _____no_output_____ | BSD-3-Clause | ICCT_en/examples/04/SS-33_State_feedback_control_for_the_mass-spring-damper_system.ipynb | ICCTerasmus/ICCT |
Operations for indexing, splitting, slicing and iterating over a dataset | import numpy as np | _____no_output_____ | MIT | Chapter_01.Operations_numpy_and_pandas/Numpy_operations.Indexing_slicing_splitting_iterator_sorting_combining_reshaping.ipynb | Eduardo0697/DataVisualizationWorkshop |
Indexing | dataset = np.genfromtxt('../Datasets/normal_distribution_splittable.csv', delimiter=',')
# Mean of the second row
second_row = dataset[1]
np.mean(second_row)
# Mean of the last row
last_row = dataset[-1]
np.mean(last_row)
# Mean of the first value of the first row
first_val_first_row = dataset[0][0]
print(np.mean(first... | _____no_output_____ | MIT | Chapter_01.Operations_numpy_and_pandas/Numpy_operations.Indexing_slicing_splitting_iterator_sorting_combining_reshaping.ipynb | Eduardo0697/DataVisualizationWorkshop |
Slicing | # Create a 2x2 matrix that starts in the second row and second column
subsection_2x2 = dataset[1:3, 1:3]
np.mean(subsection_2x2)
# Get every element in the 5th row, but only get every second element of that row
every_other_elem = dataset[4, ::2]
print(dataset[4])
print(every_other_elem)
print(np.mean(every_other_elem))... | [ 94.11176915 99.62387832 104.51786419 97.62787811 93.97853495
98.75108352 106.05042487 100.07721494 106.89005002]
[106.89005002 100.07721494 106.05042487 98.75108352 93.97853495
97.62787811 104.51786419 99.62387832 94.11176915]
100.18096645222222
| MIT | Chapter_01.Operations_numpy_and_pandas/Numpy_operations.Indexing_slicing_splitting_iterator_sorting_combining_reshaping.ipynb | Eduardo0697/DataVisualizationWorkshop |
Splitting | # Split horizontally the dataset in three equal subsets
hor_splits = np.hsplit(dataset,(3))
# Split the first third in 2 equal vertically parts
ver_splits = np.vsplit(hor_splits[0],(2))
print("Dataset", dataset.shape)
print("Subset", ver_splits[0].shape) | Dataset (24, 9)
Subset (12, 3)
| MIT | Chapter_01.Operations_numpy_and_pandas/Numpy_operations.Indexing_slicing_splitting_iterator_sorting_combining_reshaping.ipynb | Eduardo0697/DataVisualizationWorkshop |
Iterating | # Iterate over the whole dataset using nditer
curr_index = 0
for x in np.nditer(dataset):
print(x, curr_index)
curr_index += 1
# Iterate over the whole dataset using ndenumerate
for index, value in np.ndenumerate(dataset):
print(index, value) | (0, 0) 99.14931546
(0, 1) 104.03852715
(0, 2) 107.43534677
(0, 3) 97.85230675
(0, 4) 98.74986914
(0, 5) 98.80833412
(0, 6) 96.81964892
(0, 7) 98.56783189
(0, 8) 101.34745901
(1, 0) 92.02628776
(1, 1) 97.10439252
(1, 2) 99.32066924
(1, 3) 97.24584816
(1, 4) 92.9267508
(1, 5) 92.65657752
(1, 6) 105.7197853
(1, 7) 101.231... | MIT | Chapter_01.Operations_numpy_and_pandas/Numpy_operations.Indexing_slicing_splitting_iterator_sorting_combining_reshaping.ipynb | Eduardo0697/DataVisualizationWorkshop |
Filtering | vals_greater_five = dataset[dataset > 105]
vals_greater_five
vals_between_90_95 = np.extract((dataset > 90) & (dataset < 95), dataset)
vals_between_90_95
rows, cols = np.where(abs(dataset - 100) < 1)
# Create a list comprehension
one_away_indices = [[rows[index], cols[index]] for (index, _) in np.ndenumerate(rows)]
one... | _____no_output_____ | MIT | Chapter_01.Operations_numpy_and_pandas/Numpy_operations.Indexing_slicing_splitting_iterator_sorting_combining_reshaping.ipynb | Eduardo0697/DataVisualizationWorkshop |
Sorting | # Each row will be sorted
row_sorted = np.sort(dataset)
row_sorted
# Sort each column
col_sorted = np.sort(dataset, axis=0)
col_sorted
# create a sorted index list using a fancy indexing to keep the order of the dataset and only obtain the values of index
index_sorted = np.argsort(dataset[0])
dataset[0][index_sorted] | _____no_output_____ | MIT | Chapter_01.Operations_numpy_and_pandas/Numpy_operations.Indexing_slicing_splitting_iterator_sorting_combining_reshaping.ipynb | Eduardo0697/DataVisualizationWorkshop |
Combining | # Dividimos horizontalmente en 3 partes nuestro dataset es decir si son 12 columnas serian 3 bloques de 4 columnas
thirds = np.hsplit(dataset, (3))
print(dataset.shape)
print(thirds[0].shape)
#Dividimos verticalmente el primer bloque de los 3, en 2 partes , es decir si son 10 filas serian 2 bloques de 5 filas c/u
halfe... | _____no_output_____ | MIT | Chapter_01.Operations_numpy_and_pandas/Numpy_operations.Indexing_slicing_splitting_iterator_sorting_combining_reshaping.ipynb | Eduardo0697/DataVisualizationWorkshop |
Reshaping | # Reshape the dataset in to a single list
single_list = np.reshape(dataset, (1, -1))
print(dataset.shape)
print(single_list.shape)
# reshaping to a matrix with two columns
# -1 Tells python to figure oyt the dimension out itself
two_col_dataset = dataset.reshape(-1, 2)
print(two_col_dataset.shape) | (108, 2)
| MIT | Chapter_01.Operations_numpy_and_pandas/Numpy_operations.Indexing_slicing_splitting_iterator_sorting_combining_reshaping.ipynb | Eduardo0697/DataVisualizationWorkshop |
Colombian Identity Codes Introduction The function `clean_co_nit()` cleans a column containing Colombian identity code (NIT) strings, and standardizes them in a given format. The function `validate_co_nit()` validates either a single NIT strings, a column of NIT strings or a DataFrame of NIT strings, returning `True`... | import pandas as pd
import numpy as np
df = pd.DataFrame(
{
"nit": [
"2131234321",
"2131234325",
"51824753556",
"51 824 753 556",
"hello",
np.nan,
"NULL"
],
"address": [
"123 Pine Ave.",
... | _____no_output_____ | MIT | docs/source/user_guide/clean/clean_co_nit.ipynb | jwa345/dataprep |
1. Default `clean_co_nit`By default, `clean_co_nit` will clean nit strings and output them in the standard format with proper separators. | from dataprep.clean import clean_co_nit
clean_co_nit(df, column = "nit") | _____no_output_____ | MIT | docs/source/user_guide/clean/clean_co_nit.ipynb | jwa345/dataprep |
2. Output formats This section demonstrates the output parameter. `standard` (default) | clean_co_nit(df, column = "nit", output_format="standard") | _____no_output_____ | MIT | docs/source/user_guide/clean/clean_co_nit.ipynb | jwa345/dataprep |
`compact` | clean_co_nit(df, column = "nit", output_format="compact") | _____no_output_____ | MIT | docs/source/user_guide/clean/clean_co_nit.ipynb | jwa345/dataprep |
3. `inplace` parameterThis deletes the given column from the returned DataFrame. A new column containing cleaned NIT strings is added with a title in the format `"{original title}_clean"`. | clean_co_nit(df, column="nit", inplace=True) | _____no_output_____ | MIT | docs/source/user_guide/clean/clean_co_nit.ipynb | jwa345/dataprep |
4. `errors` parameter `coerce` (default) | clean_co_nit(df, "nit", errors="coerce") | _____no_output_____ | MIT | docs/source/user_guide/clean/clean_co_nit.ipynb | jwa345/dataprep |
`ignore` | clean_co_nit(df, "nit", errors="ignore") | _____no_output_____ | MIT | docs/source/user_guide/clean/clean_co_nit.ipynb | jwa345/dataprep |
4. `validate_co_nit()` `validate_co_nit()` returns `True` when the input is a valid NIT. Otherwise it returns `False`.The input of `validate_co_nit()` can be a string, a Pandas DataSeries, a Dask DataSeries, a Pandas DataFrame and a dask DataFrame.When the input is a string, a Pandas DataSeries or a Dask DataSeries, u... | from dataprep.clean import validate_co_nit
print(validate_co_nit("2131234321"))
print(validate_co_nit("2131234325"))
print(validate_co_nit("51824753556"))
print(validate_co_nit("51 824 753 556"))
print(validate_co_nit("hello"))
print(validate_co_nit(np.nan))
print(validate_co_nit("NULL")) | _____no_output_____ | MIT | docs/source/user_guide/clean/clean_co_nit.ipynb | jwa345/dataprep |
Series | validate_co_nit(df["nit"]) | _____no_output_____ | MIT | docs/source/user_guide/clean/clean_co_nit.ipynb | jwa345/dataprep |
DataFrame + Specify Column | validate_co_nit(df, column="nit") | _____no_output_____ | MIT | docs/source/user_guide/clean/clean_co_nit.ipynb | jwa345/dataprep |
Only DataFrame | validate_co_nit(df) | _____no_output_____ | MIT | docs/source/user_guide/clean/clean_co_nit.ipynb | jwa345/dataprep |
Setup | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = "3" | _____no_output_____ | Apache-2.0 | AICA_v2.ipynb | Mayner0220/AICA |
To prevent elements such as Tensorflow import logs, perform these tasks. | import glob
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print("Device:", tpu.master())
tf.config.experimental_connect_to_cluster(tpu)
tf.tpu.experimental.initialize_tpu_system(tpu)
strategy = tf.distribute.... | _____no_output_____ | Apache-2.0 | AICA_v2.ipynb | Mayner0220/AICA |
Convert the data | def _bytes_feature(value: [str, bytes]) -> tf.train.Feature:
"""string / byte๋ฅผ byte_list๋ก ๋ฐํํฉ๋๋ค."""
if isinstance(value, type(tf.constant(0))):
value = value.numpy() # BytesList๋ EagerTensor์์ ๋ฌธ์์ด์ ํ์ง ์์ต๋๋ค.
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float_feature... | _____no_output_____ | Apache-2.0 | AICA_v2.ipynb | Mayner0220/AICA |
Load the data | train_dataset = tf.data.TFRecordDataset("./tfrecord/train.tfrecord")
test_dataset = tf.data.TFRecordDataset("./tfrecord/test.tfrecord")
TRAIN_DATA_SIZE = len(list(train_dataset))
train_size = int(0.75 * TRAIN_DATA_SIZE)
train_dataset = train_dataset.shuffle(1000)
test_dataset = test_dataset.shuffle(1000)
validation_d... | _____no_output_____ | Apache-2.0 | AICA_v2.ipynb | Mayner0220/AICA |
Visualize dataset | # train TFRecord
for image_features in parsed_train_dataset.take(1):
image_raw = image_features["raw_image"].numpy()
image_label = image_features["label"].numpy()
display.display(display.Image(data=image_raw))
print("Label:", image_label)
# test TFRecord
for image_features in parsed_test_dataset.take(1)... | _____no_output_____ | Apache-2.0 | AICA_v2.ipynb | Mayner0220/AICA |
Build Model | # ๊ฒฝ์ฆ ์น๋งค, ์ค์ฆ๋ ์น๋งค, ๋น ์น๋งค, ๋งค์ฐ ๊ฒฝ๋ฏธํ ์น๋งค
CLASS_NAMES = ['MildDementia', 'ModerateDementia', 'NonDementia', 'VeryMildDementia']
NUM_CLASSES = len(CLASS_NAMES)
TRAIN_DATA_SIZE = len(list(parsed_train_dataset))
train_size = int(0.75 * TRAIN_DATA_SIZE)
# val_size = int(0.25 * TRAIN_DATA_SIZE)
# ํ
์คํธ์ฉ ๋ฐ์ดํฐ์
์ ๋ฐ๋ก ์กด์ฌํ๊ธฐ์ ๋ถํ ํ์ง ์๋๋ค.
# test... | _____no_output_____ | Apache-2.0 | AICA_v2.ipynb | Mayner0220/AICA |
Train Model | @tf.autograph.experimental.do_not_convert
def exponential_decay(lr0, s):
def exponential_decay_fn(epoch):
return lr0 * 0.1 **(epoch / s)
return exponential_decay_fn
exponential_decay_fn = exponential_decay(0.01, 20)
lr_scheduler = tf.keras.callbacks.LearningRateScheduler(exponential_decay_fn)
checkpo... | _____no_output_____ | Apache-2.0 | AICA_v2.ipynb | Mayner0220/AICA |
**SONAR_ISSUES**This notebook the selection of the rellevant attributes of the table `SONAR_ISSUES`.First, we import the libraries we need and, then, we read the corresponding csv. | import pandas as pd
sonarIssues = pd.read_csv("../../../data/raw/SONAR_ISSUES.csv")
print(sonarIssues.shape)
list(sonarIssues) | (1941508, 18)
| MIT | notebooks/2-DataPreparation/1-SelectData/3-DB-SONAR-ISSUES.ipynb | chus-chus/softwareDevTypes |
We select the desired attributes of the table. | attributes = ['projectID', 'creationDate', 'closeDate', 'creationCommitHash', 'closeCommitHash', 'type', 'severity',
'debt', 'author']
sonarIssues = sonarIssues[attributes]
print(sonarIssues.shape)
sonarIssues.head() | (1941508, 9)
| MIT | notebooks/2-DataPreparation/1-SelectData/3-DB-SONAR-ISSUES.ipynb | chus-chus/softwareDevTypes |
We save this new table into a csv. | sonarIssues.to_csv('../../../data/interim/DataPreparation/SelectData/SONAR_ISSUES_select.csv', header=True) | _____no_output_____ | MIT | notebooks/2-DataPreparation/1-SelectData/3-DB-SONAR-ISSUES.ipynb | chus-chus/softwareDevTypes |
R - Week 2 (exercises) R-code on solving equations with inverse matrix Solve the following system of equations: 1. $2x+y+2z=3$2. $x-3z=-5$3. $2y+5z=4$ $$ \begin{bmatrix} 2 & 1 & 2 \\ 1 & 6 & -3 \\ 0 & 2 & 5 \end{bmatrix} \cdot \begin{bmatrix} x \\ y \\ z \end{bmatrix} = \begin{bmatrix} 3 & -5 & 4 \end{bmatrix} $$ $ A... | A = matrix(c(2,1,2,1,6,-3,0,2,5), nrow=3)
A | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
The inverse $A^{-1}$ is: | solve(A) | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
Define vector $\vec{b}$: | b = c(3, -5, 4) | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
Solve the system with R functions `solve(A,b)`: | solve(A,b) | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
Solve the system with $\vec{x}=A^{-1}\vec{b}$: | solve(A) %*% b | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
R-code on least square method $y=ax+b$ $A\cdot \vec{x} = \vec{b}$$A^T\cdot A \vec{x} = A^T \vec{b}$$(A^T A)^{-1}A^T A \vec{x} = A^T \vec{b}$$(A^T A)^{-1} ...$ Define $\vec{x}=\begin{bmatrix}12 & 2 & 3 & 5 & 10 & 9 & 8 \end{bmatrix}$: | x = c(12, 2, 3, 5, 10, 9, 8)
x | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
Define $\vec{y} = \begin{bmatrix}125 & 30 & 43 & 62 & 108 & 102 & 90 \end{bmatrix}$: | y = c(125, 30, 43, 62, 108, 102, 90)
y
length(x)==length(y)
A = matrix(union(x,y), nrow=length(x))
A
lm(y~x)
fit <- function(x) 9.488*x+13.583
fit(5)
plot(x,sapply(x, fit), 'l', col='blue')
points(x,y)
x
y | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
$y=ax+b$ | X = matrix(c(y, rep(1, length(y))), ncol=2)
X
b = matrix(y)
b | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
Dit is de vorm $A\cdot\vec{x} = \vec{b}$. Wat we op willen lossen met $A^{-1}A\vec{x}=A^{-1}\vec{b}$, maar dit werkt niet omdat $A$ geen vierkante matrix is en daardoor geen inverse kan bepalen voor $A$.Door gebruik te maken van de getransponeerde $A^T$ kunnen we een vierkante matrix krijgen. Dus matrix-vermenigvuldige... | t(A) %*% A | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
Wat inderdaad een vierkant matrix geeft. Vervolgens is deze op te lossen door de inverse te bepalen. De hele formule wordt dan:$$ (A^T \cdot A)^{-1}\cdot(A^T \cdot A)\cdot\vec{x} = (A^T \cdot A)^{-1} \cdot A^T \cdot \vec{b} $$Laat $B = (A^T \cdot A)^{-1}$ zijn. Substitueren en vereenvoudigen geeft: $$ I\cdot\vec{x} = B... | B = solve(t(A) %*% A)
B
B %*% t(A) %*% b
lm(y~x) | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
**Versimpeld voorbeeld lreg** | A = matrix(c(-1,0,2,3,1,1,1,1),ncol=2)
A
b = c(-1,2,1,2)
b
x = A[0:4]
solve(t(A) %*% A) %*% t(A) %*% b
lm(b~x)
fit <- function(x) 0.5*x+0.5
plot(-5:5, sapply(-5:5, fit), 'l')
points(x,b)
lreg <- function(x, y) {
A = cbind(x, rep(1, length(x)))
s = solve(t(A) %*% A) %*% t(A) %*% y
function(x) s[1] * x + s[2]... | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
With other functionality: Least squares regression model Find the best fitting line $y=ax+b$ for the following data points: | x <- c(12,2,3,5,10,9,8)
b <- c(125,30,43,62,108,102,90) | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
We can do this by solving the equation $A\vec{x}=\vec{b}$. Constructing the equation with the matrices for our data points yields:$$ \begin{bmatrix} 12 & 1 \\ 2 & 1 \\ 3 & 1 \\ 5 & 1 \\ 10 & 1 \\ 9 & 1 \\ 8 & 1 \end{bmatrix} \cdot \begin{bmatrix}a \\ b \end{bmatrix} = \begin{bmatrix} 125 \\ 30 \\ 43 \\ 62 \\ 108 \\ 102... | ones <- rep(1, length(x))
A <- cbind(x, ones)
A | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
If we want to solve the equation $A\vec{x}=\vec{b}$ we can multiply both sides $A^{-1}$ to get:$$ \begin{align} A\vec{x}&=\vec{b} \\ (A^{-1}\cdot A)\vec{x}&=A^{-1}\vec{b} \\ I\vec{x}&=A^{-1}\vec{b} \end{align} $$ However, we need to calculate the inverse of $A$, but $A$ is not a square matrix. To solve this problem we ... | S = solve(t(A) %*% A) %*% t(A) %*% b | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
The resulting matrix $S$ will have our coefficients $a$ and $b$ to construct the line: | lsm = c(S[2], S[1])
lsm | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
If we verify the coefficients with built-in R functionality for least-squares regression, we can see that our solution is correct. | lm(b~x) | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
Plotting our values yields: | plot(x, b)
abline(lsm) | _____no_output_____ | Unlicense | Applied Math/Y1S4/Data Science/.ipynb_checkpoints/R - Week 2 (exercises)-checkpoint.ipynb | darkeclipz/jupyter-notebooks |
Copyright 2018 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License"); { display-mode: "form" }
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE... | _____no_output_____ | CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
Custom differentiationThis tutorial will show you how to define your own custom derivatives, perform derivative surgery, and implement your own gradient checkpointing API in just 5 lines of Swift. Declaring custom derivatives You can define custom derivatives for any Swift function that has differentiable parameters ... | import Glibc
func sillyExp(_ x: Float) -> Float {
let ๐ = Float(M_E)
print("Taking ๐(\(๐)) to the power of \(x)!")
return pow(๐, x)
}
@differentiating(sillyExp)
func sillyDerivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
let y = sillyExp(x)
return (value: y, pullback: { v ... | Taking ๐(2.7182817) to the power of 3.0!
exp(3) = 20.085535
Taking ๐(2.7182817) to the power of 3.0!
๐exp(3) = 20.085535
| CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
Stop derivatives from propagatingCommonly known as "stop gradient" in machine learning use cases, method [`withoutDerivative()`](https://www.tensorflow.org/swift/api_docs/Protocols/Differentiable/s:10TensorFlow14DifferentiablePAAE17withoutDerivativexyF) stops derivatives from propagating.Plus, `withoutDerivative()` ca... | let x: Float = 2.0
let y: Float = 3.0
gradient(at: x, y) { x, y in
sin(sin(sin(x))) + cos(cos(cos(y))).withoutDerivative()
} | _____no_output_____ | CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
Derivative surgeryMethod [`withGradient(_:)`](https://www.tensorflow.org/swift/api_docs/Protocols/Differentiable/s:10TensorFlow14DifferentiablePAAE12withGradientyxy15CotangentVectorQzzcF) makes arbitrary operations (including mutation) run on the gradient at a value during the enclosing functionโs backpropagation. Use... | var x: Float = 30
x.gradient { x -> Float in
// Print the partial derivative with respect to the result of `sin(x)`.
let a = sin(x).withGradient { print("โ+/โsin = \($0)") }
// Force the partial derivative with respect to `x` to be `0.5`.
let b = log(x.withGradient { (dx: inout Float) in
print(... | โlog/โx = 0.033333335, but rewritten to 0.5
โ+/โsin = 1.0
| CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
Use it in a neural network module Just like how we used it in a simple `Float` function, we can use it in any numerical application, like the following neural network built using the [Swift for TensorFlow Deep Learning Library](https://github.com/tensorflow/swift-apis). | import TensorFlow
struct MLP: Layer {
var layer1 = Dense<Float>(inputSize: 2, outputSize: 10, activation: relu)
var layer2 = Dense<Float>(inputSize: 10, outputSize: 1, activation: relu)
@differentiable
func applied(to input: Tensor<Float>, in context: Context) -> Tensor<Float> {
let h0 = l... | Loss: 0.33426732
โL/โลท = [[-0.25], [-0.078446716], [-0.12092987], [0.031454742]]
โL/โlayer1 = [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-0.03357383, -0.027463656, 0.037523113, -0.002631738, -0.030937709, -0.014981618, -0.02623924, -0.026290288, 0.027446445, 0.01046889], [-0.051755875, -0.042336714, 0.057843... | CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
Recomputing activations during backpropagation to save memory (checkpointing)Checkpointing is a traditional technique in reverse-mode automatic differentiation to save memory when computing derivatives by making large intermediate values in the original computation not be saved in memory for backpropagation, but inste... | /// Given a differentiable function, returns the same differentiable function except when
/// derivatives of this function is being computed, values in the original function that are needed
/// for computing the derivatives will be recomputed, instead of being captured by the differnetial
/// or pullback.
///
/// - Par... | _____no_output_____ | CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
Verify it works | let input: Float = 10.0
print("Running original computation...")
// Differentiable multiplication with checkpointing.
let square = makeRecomputedInGradient { (x: Float) -> Float in
print(" Computing square...")
return x * x
}
// Differentiate `f(x) = (cos(x))^2`.
let (output, backprop) = input.valueWithPullb... | Running original computation...
Computing square...
Running backpropagation...
Computing square...
Gradient = -0.9129453
| CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
Extend it to neural network modulesIn this example, we define a simple convolutional neural network.```swiftstruct Model: Layer { var conv = Conv2D(filterShape: (5, 5, 3, 6)) var maxPool = MaxPool2D(poolSize: (2, 2), strides: (2, 2)) var flatten = Flatten() var dense = Dense(inputSize: 36 * 6, outputSize: ... | // Same as the previous `makeRecomputedInGradient(_:)`, except it's for binary functions.
func makeRecomputedInGradient<T: Differentiable, U: Differentiable, V: Differentiable>(
_ original: @escaping @differentiable (T, U) -> V
) -> @differentiable (T, U) -> V {
return differentiableFunction { x, y in
(... | _____no_output_____ | CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
Then, we define a generic layer `ActivationRecomputing`. | /// A layer wrapper that makes the underlying layer's activations be discarded during application
/// and recomputed during backpropagation.
struct ActivationDiscarding<Wrapped: Layer>: Layer
where Wrapped.AllDifferentiableVariables == Wrapped.CotangentVector {
/// The wrapped layer.
var wrapped: Wrapped
... | _____no_output_____ | CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
Finally, we can add a method on all layers that returns the same layer except its activations are discarded during application and recomputeed during backpropagation. | extension Layer where AllDifferentiableVariables == CotangentVector {
func discardingActivations() -> ActivationDiscarding<Self> {
return ActivationDiscarding(wrapped: self)
}
} | _____no_output_____ | CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
Back in the model, all we have to change is to wrap the convolution layer into the activation-recomputing layer.```swiftvar conv = Conv2D(filterShape: (5, 5, 3, 6)).discardingActivations()``` Now, simply use it in the model! | struct Model: Layer {
var conv = Conv2D<Float>(filterShape: (5, 5, 3, 6)).discardingActivations()
var maxPool = MaxPool2D<Float>(poolSize: (2, 2), strides: (2, 2))
var flatten = Flatten<Float>()
var dense = Dense<Float>(inputSize: 36 * 6, outputSize: 10)
@differentiable
func applied(to input: T... | _____no_output_____ | CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
When we run a training loop, we can see that the convolution layer's activations are computed twice: once during layer application, and once during backpropagation. | // Use random training data.
let x = Tensor<Float>(randomNormal: [10, 16, 16, 3])
let y = Tensor<Int32>(rangeFrom: 0, to: 10, stride: 1)
var model = Model()
let opt = SGD<Model, Float>()
let context = Context(learningPhase: .training)
for i in 1...5 {
print("Starting training step \(i)")
print(" Running orig... | Starting training step 1
Running original computation...
Applying Conv2D<Float> layer...
Loss: 3.6660562
Running backpropagation...
Applying Conv2D<Float> layer...
Starting training step 2
Running original computation...
Applying Conv2D<Float> layer...
Loss: 3.1203392
Running backpropagation..... | CC-BY-4.0 | docs/site/tutorials/custom_differentiation.ipynb | sendilkumarn/swift |
์ผ๋ผ์ค๋ก AlexNet ๋ง๋ค๊ธฐ ์ด ๋
ธํธ๋ถ์์ [AlexNet](https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks)๊ณผ ๋น์ทํ ์ฌ์ธต ํฉ์ฑ๊ณฑ ์ ๊ฒฝ๋ง์ผ๋ก [Oxford Flowers](http://www.robots.ox.ac.uk/~vgg/data/flowers/17/) ๋ฐ์ดํฐ์
์ ๊ฝ์ 17๊ฐ์ ์นดํ
๊ณ ๋ฆฌ๋ก ๋ถ๋ฅํ๊ฒ ์ต๋๋ค. [
X = data['X']
Y = data['Y']
X.shape, Y.shape | _____no_output_____ | MIT | notebooks/10-2.alexnet_in_keras.ipynb | sunny191019/dl-illustrated |
์ ๊ฒฝ๋ง ๋ชจ๋ธ์ ๋ง๋ญ๋๋ค. | model = Sequential()
model.add(Conv2D(96, kernel_size=(11, 11), strides=(4, 4), activation='relu', input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2)))
model.add(BatchNormalization())
model.add(Conv2D(256, kernel_size=(5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(3, 3)... | Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 54, 54, 96) 34944
____________________________________... | MIT | notebooks/10-2.alexnet_in_keras.ipynb | sunny191019/dl-illustrated |
๋ชจ๋ธ์ ์ค์ ํฉ๋๋ค. | model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) | _____no_output_____ | MIT | notebooks/10-2.alexnet_in_keras.ipynb | sunny191019/dl-illustrated |
ํ๋ จ! | model.fit(X, Y, batch_size=64, epochs=100, verbose=1, validation_split=0.1, shuffle=True) | Epoch 1/100
20/20 [==============================] - 9s 78ms/step - loss: 4.6429 - accuracy: 0.1772 - val_loss: 6.9113 - val_accuracy: 0.0662
Epoch 2/100
20/20 [==============================] - 1s 50ms/step - loss: 3.2046 - accuracy: 0.2823 - val_loss: 3.8402 - val_accuracy: 0.1838
Epoch 3/100
20/20 [=================... | MIT | notebooks/10-2.alexnet_in_keras.ipynb | sunny191019/dl-illustrated |
NOTE:In the cell below you **MUST** use a batch size of 10 (`batch_size=10`) for the `train_generator` and the `validation_generator`. Using a batch size greater than 10 will exceed memory limits on the Coursera platform. | TRAINING_DIR = '/tmp/cats-v-dogs/training/'
train_datagen = ImageDataGenerator( rescale = 1.0/255. )
# NOTE: YOU MUST USE A BATCH SIZE OF 10 (batch_size=10) FOR THE
# TRAIN GENERATOR.
train_generator = train_datagen.flow_from_directory(TRAINING_DIR,
batch_size=10,
... | _____no_output_____ | MIT | Exercise_1_Cats_vs_Dogs_Question-FINAL.ipynb | Mostafa-wael/Convolutional-Neural-Networks-in-TensorFlow |
Submission Instructions | # Now click the 'Submit Assignment' button above. | _____no_output_____ | MIT | Exercise_1_Cats_vs_Dogs_Question-FINAL.ipynb | Mostafa-wael/Convolutional-Neural-Networks-in-TensorFlow |
When you're done or would like to take a break, please run the two cells below to save your work and close the Notebook. This will free up resources for your fellow learners. | %%javascript
<!-- Save the notebook -->
IPython.notebook.save_checkpoint();
%%javascript
IPython.notebook.session.delete();
window.onbeforeunload = null
setTimeout(function() { window.close(); }, 1000); | _____no_output_____ | MIT | Exercise_1_Cats_vs_Dogs_Question-FINAL.ipynb | Mostafa-wael/Convolutional-Neural-Networks-in-TensorFlow |
Helper function to plot | def plot_graph(axis_title, x, y_train, y_val, xlabel, ylabel, xtick_range, ytick_range, save_path=None):
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(9, 6))
line1 = ax.plot(x, y_train, color="blue", label="train")
line2 = ax.plot(x, y_val, color="red", label="val")
# Nicer visuals.
ax.set_ti... | _____no_output_____ | MIT | notebooks/plotTrainingGraphs.ipynb | CleonWong/Can-You-Find-The-Tumour |
Batch-size = 64 | df_64 = pd.read_csv("../results/fit/20201203_040325___INSTANCE/csv_logger/csv_logger.csv")
df_64.head()
plot_graph(axis_title="Batch Size = 64",
x=df_64["epoch"],
y_train=df_64["loss"],
y_val=df_64["val_loss"],
xlabel="Epoch",
ylabel="Binary crossentropy loss",
... | _____no_output_____ | MIT | notebooks/plotTrainingGraphs.ipynb | CleonWong/Can-You-Find-The-Tumour |
Batch-size = 10 | df_10 = pd.read_csv("../results/fit/20201203_013807___INSTANCE/csv_logger/csv_logger.csv")
df_10.head()
plot_graph(axis_title="Batch Size = 10",
x=df_10["epoch"],
y_train=df_10["loss"],
y_val=df_10["val_loss"],
xlabel="Epoch",
ylabel="Binary crossentropy loss",
... | _____no_output_____ | MIT | notebooks/plotTrainingGraphs.ipynb | CleonWong/Can-You-Find-The-Tumour |
--- Combine .csv | mass_train_df = pd.read_csv("../data/raw_data/csv-description-updated/Mass-Training-Description-UPDATED.csv")
mass_test_df = pd.read_csv("../data/raw_data/csv-description-updated/Mass-Test-Description-UPDATED.csv")
mass_df = pd.concat([mass_train_df, mass_test_df])
mass_df
# Create identifier column.
mass_df.insert(l... | _____no_output_____ | MIT | notebooks/plotTrainingGraphs.ipynb | CleonWong/Can-You-Find-The-Tumour |
Start create | # Image read dir
street_dir = '/root/notebooks/0858611-2/final_project/caltech_pedestrian_extractor/video_extractor/*'
people_dir = '/root/notebooks/0858611-2/final_project/caltech_pedestrian_extractor/js_on_image/people_img/Market-1501-v15.09.15'
# Image save dir
save_dir = '/root/notebooks/0858611-2/final_project/c... | _____no_output_____ | Apache-2.0 | 01_gene_train_dataset/discard/gandatamask3_test.ipynb | tony92151/pedestrian_generator |
Import Packages | # Import packages
import glob
import csv
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import psycopg2
| _____no_output_____ | CC-BY-3.0 | __Project Files/.ipynb_checkpoints/Data Cleaning_merge all data together_backup-checkpoint.ipynb | joannasys/Predictions-of-ICU-Mortality |
Append each .txt file into a DataFrameEach txt file is a row | # Iterate through each file name
main = pd.DataFrame()
for filename in glob.iglob('./training_set_a/*.txt'):
# Open each file as data
with open(filename) as inputfile:
data = list(csv.reader(inputfile)) # list of list
data = pd.DataFrame(data[1:],columns=data... | _____no_output_____ | CC-BY-3.0 | __Project Files/.ipynb_checkpoints/Data Cleaning_merge all data together_backup-checkpoint.ipynb | joannasys/Predictions-of-ICU-Mortality |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.