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
Image Segmentation* This code is **only** `tensorflow API` version for [TensorFlow tutorials/Image Segmentation](https://github.com/tensorflow/models/blob/master/samples/outreach/blogs/segmentation_blogpost/image_segmentation.ipynb) which is made of `tf.keras`.* You can see the detail description [tutorial link](https...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time import functools import numpy as np import matplotlib.pyplot as plt %matplotlib inline import matplotlib as mpl mpl.rcParams['axes.grid'] = False mpl.rcParams['figure.figsize'] = (12,12) ...
/home/lab4all/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Get all the files Since this tutorial will be using a dataset from [Giana Dataset](https://giana.grand-challenge.org/Dates/).
# Unfortunately you cannot downlaod GIANA dataset from website # So I upload zip file on my dropbox # if you want to download from my dropbox uncomment below #!wget https://goo.gl/mxikqa #!mv mxikqa sd_train.zip #!unzip sd_train.zip #!mkdir ../../datasets #!mv sd_train ../../datasets #!rm sd_train.zip dataset_dir = '.....
Number of training examples: 240 Number of test examples: 60
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Here's what the paths look like
x_train_filenames[:10] y_train_filenames[:10] y_test_filenames[:10]
_____no_output_____
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
VisualizeLet's take a look at some of the examples of different images in our dataset.
display_num = 5 r_choices = np.random.choice(num_train_examples, display_num) plt.figure(figsize=(10, 15)) for i in range(0, display_num * 2, 2): img_num = r_choices[i // 2] x_pathname = x_train_filenames[img_num] y_pathname = y_train_filenames[img_num] plt.subplot(display_num, 2, i + 1) plt.imshow(Image...
_____no_output_____
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Set up Let’s begin by setting up some parameters. We’ll standardize and resize all the shapes of the images. We’ll also set up some training parameters:
# Set hyperparameters image_size = 128 img_shape = (image_size, image_size, 3) batch_size = 8 max_epochs = 100 print_steps = 50 save_epochs = 50 train_dir = 'train/exp1'
_____no_output_____
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Build our input pipeline with `tf.data`Since we begin with filenames, we will need to build a robust and scalable data pipeline that will play nicely with our model. If you are unfamiliar with **tf.data** you should check out my other tutorial introducing the concept! Our input pipeline will consist of the following ...
def _process_pathnames(fname, label_path): # We map this function onto each pathname pair img_str = tf.read_file(fname) img = tf.image.decode_bmp(img_str, channels=3) label_img_str = tf.read_file(label_path) label_img = tf.image.decode_bmp(label_img_str, channels=1) resize = [image_size, image_size] i...
_____no_output_____
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Set up train and test datasetsNote that we apply image augmentation to our training dataset but not our validation dataset.
train_ds = get_baseline_dataset(x_train_filenames, y_train_filenames) test_ds = get_baseline_dataset(x_test_filenames, y_test_filenames, shuffle=False) train_ds
_____no_output_____
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Plot some train data
temp_ds = get_baseline_dataset(x_train_filenames, y_train_filenames, batch_size=1, max_epochs=1, shuffle=False) # Let's examine some of these augmented images temp_iter = temp_ds.make_one_shot_ite...
_____no_output_____
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Build the modelWe'll build the U-Net model. U-Net is especially good with segmentation tasks because it can localize well to provide high resolution segmentation masks. In addition, it works well with small datasets and is relatively robust against overfitting as the training data is in terms of the number of patches ...
def conv_block(inputs, num_outputs, is_training, scope): batch_norm_params = {'decay': 0.9, 'epsilon': 0.001, 'is_training': is_training, 'scope': 'batch_norm'} with tf.variable_scope(scope) as scope: with slim.arg_scope([slim.conv2d], ...
_____no_output_____
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Create a model (UNet)
model = UNet(train_ds=train_ds, test_ds=test_ds) model.build() # show info for trainable variables t_vars = tf.trainable_variables() slim.model_analyzer.analyze_vars(t_vars, print_info=True) opt = tf.train.AdamOptimizer(learning_rate=2e-4) with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)): opt...
_____no_output_____
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Train a model
%%time sess = tf.Session(config=sess_config) sess.run(tf.global_variables_initializer()) tf.logging.info('Start Session.') train_iterator = train_ds.make_one_shot_iterator() train_handle = sess.run(train_iterator.string_handle()) test_iterator = test_ds.make_one_shot_iterator() test_handle = sess.run(test_iterator.str...
Epochs: 98.33 global_step: 2950 loss: 0.090 (248.52 examples/sec; 0.032 sec/batch)
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Plot the loss
loss_history = np.asarray(loss_history) plt.plot(loss_history[:,0], loss_history[:,1]) plt.show()
_____no_output_____
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Evaluate the test dataset and Plot
test_ds_eval = get_baseline_dataset(x_test_filenames, y_test_filenames, batch_size=num_test_examples, max_epochs=1, shuffle=False) test_iterator_eval = test_ds_eval.make_one_s...
mean iou: 0.87998605
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Visualize testset
test_ds_visual = get_baseline_dataset(x_test_filenames, y_test_filenames, batch_size=1, max_epochs=1, shuffle=False) test_iterator_visual = test_ds_visual.make_one_sh...
_____no_output_____
Apache-2.0
tf.version.1/06.images/01.image_segmentation.ipynb
jinhwanhan/tensorflow.tutorials
Green's function============== Fundamental solution-------------------------------
from sympy import * init_printing() x1, x2, xi1, xi2 = symbols('x_1 x_2 xi_1 xi_2') E = -1/(2*pi) * log(sqrt((x1-xi1)**2 + (x2-xi2)**2)) E
_____no_output_____
MIT
PythonCodes/Exercises/Class-SEAS/green/.ipynb_checkpoints/green-checkpoint.ipynb
Nicolucas/C-Scripts
**Task**: Check that $\nabla^2_\xi E = 0$ for $x \neq \xi$.*Hint*: https://docs.sympy.org/latest/tutorial/calculus.htmlderivatives
diff(E,x,2)
_____no_output_____
MIT
PythonCodes/Exercises/Class-SEAS/green/.ipynb_checkpoints/green-checkpoint.ipynb
Nicolucas/C-Scripts
Directional derivative------------------------------
n1, n2 = symbols('n_1 n_2')
_____no_output_____
MIT
PythonCodes/Exercises/Class-SEAS/green/.ipynb_checkpoints/green-checkpoint.ipynb
Nicolucas/C-Scripts
**Task**: Compute the directional derivative $\frac{\partial E}{\partial n}$. **Task** (optional): Write a function which returns the directional derivative of an expression.
def ddn(expr): pass
_____no_output_____
MIT
PythonCodes/Exercises/Class-SEAS/green/.ipynb_checkpoints/green-checkpoint.ipynb
Nicolucas/C-Scripts
Multidimensional Pattern identification with SAX In-site viewThis script performs pattern identification over the {time, attribute} cuboid, that covers the intra-building frame. It serves for within-site exploration on how a given building operates across time and building-specific attributes.The data is first normali...
# Import modules import pandas as pd import numpy as np import time from sklearn.cluster import KMeans import sklearn.metrics as metrics from collections import Counter from sklearn.preprocessing import StandardScaler, MinMaxScaler # Plotting modules from plotly.offline import init_notebook_mode init_notebook_mode(conn...
_____no_output_____
MIT
code/04_Mining_CuboidB.ipynb
JulienLeprince/multidimensional-building-data-cube-pattern-identification
Read
# Read Cuboid blg_id = "Fox_education_Melinda" df = pd.read_csv(path_data + "cuboid_B_"+blg_id+".csv", index_col="timestamp") # Format index to datetime object df.index = pd.to_datetime(df.index, format='%Y-%m-%d %H:%M:%S') df.head()
_____no_output_____
MIT
code/04_Mining_CuboidB.ipynb
JulienLeprince/multidimensional-building-data-cube-pattern-identification
Pre-Mining Motifs identification
# SAX Parameters day_number_of_pieces = 4 alphabet_size = 3 scaler_function = StandardScaler() # Normalize per attribute df_normalized = ut.scale_df_columns_NanRobust(df, df.columns, scaler=scaler_function) # Perform SAX transformation sax_dict, counts, sax_data = ut.SAX_mining(df_normalized, W=day_number_of_pieces, ...
_____no_output_____
MIT
code/04_Mining_CuboidB.ipynb
JulienLeprince/multidimensional-building-data-cube-pattern-identification
Mining Attribute motifs clusteringAttribute daily profile motifs are clustered together resulting in a reduced number of typical patterns from the previous motif identification thanks to SAX trasnformation.
# Identify optimal cluster number wcss, sil = [], [] for meter in sax_data: wcss_l, sil_l = ut.elbow_method(sax_data[meter].iloc[indexes[meter]].interpolate(method='linear').transpose(), n_cluster_max=20) wcss.append(wcss_l) sil.append(sil_l) # Get similarity index quantiles (cross attributes) arr_sil, arr_...
_____no_output_____
MIT
code/04_Mining_CuboidB.ipynb
JulienLeprince/multidimensional-building-data-cube-pattern-identification
Practical Session 2: Classification algorithms*Notebook by Ekaterina Kochmar* 0.1 Your taskIn practical 1, you worked with the housing prices and bike sharing datasets on the tasks that required you to predict some value (e.g., price of a house) or amount (e.g., the count of rented bikes, or the number of registered ...
from sklearn import datasets digits = datasets.load_digits() list(digits.keys()) digits X, y = digits["data"], digits["target"] X.shape y.shape
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
You can access the digits and visualise them using the following code (feel free to select another digit):
import matplotlib from matplotlib import pyplot as plt some_digit = X[3] some_digit_image = some_digit.reshape(8, 8) plt.imshow(some_digit_image, cmap=matplotlib.cm.binary, interpolation="nearest") plt.axis("off") plt.show() y[3]
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
For the rest of the practical, apply the data preprocessing techniques, implement and evaluate the classification models on the digits dataset using the steps that you applied above to the iris dataset. Step 2: Splitting the data into training and test subsets
from sklearn.model_selection import StratifiedShuffleSplit split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42) split.get_n_splits(X, y) print(split) for train_index, test_index in split.split(X, y): print("TRAIN:", len(train_index), "TEST:", len(test_index)) X_train, X_test = X[t...
StratifiedShuffleSplit(n_splits=1, random_state=42, test_size=0.2, train_size=None) TRAIN: 1437 TEST: 360 (1437, 64) (1437,) (360, 64) (360,)
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Check proportions
import pandas as pd # def original_proportions(data): # props = {} # for value in set(data["target"]): # data_value = [i for i in data["target"] if i==value] # props[value] = len(data_value) / len(data["target"]) # return props def subset_proportions(subset): props = {} for value i...
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Case 1: Binary Classification
y_train_zero = (y_train == 0) # will return True when the label is 0 (i.e., zero) y_test_zero = (y_test == 0) y_test_zero zero_example = X_test[10]
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Perceptron
from sklearn.linear_model import SGDClassifier sgd = SGDClassifier(max_iter=5, tol=None, random_state=42, loss="perceptron", eta0=1, learning_rate="constant", penalty=None) sgd.fit(X_train, y_train_zero) sgd.predict([zero_example])
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Trying it for label 1
y_train_one = (y_train == 1) # True when the label is 1 (i.e., versicolor) y_test_one = (y_test == 1) y_test_one one_example = X_test[40] print("Class", y_test[40], "(", digits.target_names[y_test[40]], ")") sgd.fit(X_train, y_train_one) print(sgd.predict([one_example]))
Class 1 ( 1 ) [ True]
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Perceptron did well Logistic Regression
from sklearn.linear_model import LogisticRegression log_reg = LogisticRegression() log_reg.fit(X_train, y_train_zero) print(log_reg.predict([zero_example])) log_reg.fit(X_train, y_train_one) log_reg.predict([one_example])
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Looks like Logistic regression didn't get the 1 Naive Bayes
from sklearn.naive_bayes import GaussianNB, MultinomialNB gnb = MultinomialNB() # or: gnb = GaussianNB() gnb.fit(X_train, y_train_zero) gnb.predict([zero_example]) gnb.fit(X_train, y_train_one) gnb.predict([one_example])
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Naive Bayes did good Step 3: Evaluation Performance measures- Acc for cross-val
from sklearn.model_selection import cross_val_score print(cross_val_score(log_reg, X_train, y_train_zero, cv=5, scoring="accuracy")) print(cross_val_score(gnb, X_train, y_train_zero, cv=5, scoring="accuracy")) print(cross_val_score(sgd, X_train, y_train_zero, cv=5, scoring="accuracy")) print(cross_val_score(log_reg, X...
[0.97916667 0.97916667 0.96515679 0.97212544 0.95470383] [0.61805556 0.62847222 0.61324042 0.66550523 0.51916376] [0.97222222 0.95486111 0.95470383 0.95470383 0.95818815]
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Brute force predicting only non-ones
from sklearn.base import BaseEstimator import numpy as np np.random.seed(42) class NotXClassifier(BaseEstimator): def fit(self, X, y=None): pass def predict(self, X): return np.zeros((len(X), 1), dtype=bool) notone_clf = NotXClassifier() cross_val_score(notone_clf, X_train, y_train_one, cv...
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
- Confusion Matrix
from sklearn.model_selection import cross_val_predict from sklearn.metrics import confusion_matrix y_train_pred = cross_val_predict(log_reg, X_train, y_train_zero, cv=5) confusion_matrix(y_train_zero, y_train_pred) y_train_pred = cross_val_predict(gnb, X_train, y_train_zero, cv=5) confusion_matrix(y_train_zero, y_trai...
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
- precision, recall, f1
from sklearn.metrics import precision_score, recall_score, f1_score y_train_pred = cross_val_predict(gnb, X_train, y_train_one, cv=5) precision = precision_score(y_train_one, y_train_pred) # == 36 / (36 + 5) recall = recall_score(y_train_one, y_train_pred) # == 36 / (36 + 4) f1 = f1_score(y_train_one, y_train_pred) pr...
0.20454545454545456 0.9863013698630136 0.3388235294117647 0.832258064516129 0.8835616438356164 0.8571428571428571
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Oh no, poor gnb - Precision-recall treade-off Confidence score
log_reg.fit(X_train, y_train_one) y_scores = log_reg.decision_function([one_example]) y_scores threshold = 0 y_one_pred = (y_scores > threshold) y_one_pred threshold = -2 y_one_pred = (y_scores > threshold) y_one_pred
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Confidence scores
y_scores = cross_val_predict(log_reg, X_train, y_train_one, cv=5, method="decision_function") y_scores
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Plot precision vs recall
from sklearn.metrics import precision_recall_curve precisions, recalls, thresholds = precision_recall_curve(y_train_one, y_scores) def plot_pr_vs_threshold(precisions, recalls, thresholds): plt.plot(thresholds, precisions[:-1], "b--", label="Precision") plt.plot(thresholds, recalls[:-1], "g--", label="Recal...
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
- The Receiver Operating Characteristic (ROC)
from sklearn.metrics import roc_curve fpr, tpr, thresholds = roc_curve(y_train_one, y_scores) def plot_roc_curve(fpr, tpr, label=None): plt.plot(fpr, tpr, linewidth=2, label=label) plt.plot([0, 1], [0, 1], "k--") plt.axis([0, 1, 0, 1.01]) plt.xlabel("False positive rate (fpr)") plt.ylabel("True po...
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Looks like Logistic Regression outperformed Gaussian Naive Bayes Step 4: Data transformations Kernel trick- with gamma = 1 we get EXTREMELY bad results- gamma = 0.001 solves that
from sklearn.kernel_approximation import RBFSampler rbf_features = RBFSampler(gamma=0.001, random_state=42) X_train_features = rbf_features.fit_transform(X_train) print(X_train.shape, "->", X_train_features.shape) sgd_rbf = SGDClassifier(max_iter=100, random_state=42, loss="perceptron", eta0=1...
(1437, 64) -> (1437, 100) [-0.08948691 0.07840032 0.13012926 0.01843734 0.05243378 0.12363736 -0.13138175 0.12487656 -0.06774296 -0.13116408 0.14131867 0.13014406 -0.1412175 0.01781151 0.08980399 0.14045931 0.06150205 0.11652648 0.13544217 -0.11087697 0.13594337 -0.0800289 0.0574227 0.01216671 ...
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
- Precision, recall and F1 : non-kernel vs kernel GNB
y_train_pred = cross_val_predict(sgd, X_train, y_train_one, cv=5) precision = precision_score(y_train_one, y_train_pred) recall = recall_score(y_train_one, y_train_pred) f1 = f1_score(y_train_one, y_train_pred) print(precision, recall, f1) y_train_pred = cross_val_predict(sgd_rbf, X_train_features, y_train_one, cv=5) ...
0.8270676691729323 0.7534246575342466 0.7885304659498208 0.9154929577464789 0.8904109589041096 0.9027777777777778
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Case 2: Multi-class classification
sgd.fit(X_train, y_train) # i.e., all instances, not just one class print(sgd.predict([zero_example])) print(sgd.predict([one_example]))
[0] [1]
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
half good
sgd_rbf.fit(X_train_features, y_train) # i.e., all instances, not just one class X_test_features = rbf_features.transform(X_test) zero_rbf_example = X_test_features[10] # note that you need to transform the test data in the same way, too one_rbf_example = X_test_features[3] print(sgd_rbf.predict([zero_rbf_example])) p...
[0] [6]
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
half good
zero_scores = sgd_rbf.decision_function([zero_rbf_example]) print(zero_scores) # check which class gets the maximum score prediction = np.argmax(zero_scores) print(prediction) # check which class this corresponds to in the classifier print(sgd_rbf.classes_[prediction]) print(digits.target_names[sgd_rbf.classes_[predic...
[[ 1.32752637 -8.43047571 -0.56672488 -3.41607774 -2.43529497 -2.63031545 -3.12302686 -2.30546944 -3.48919124 -6.71624512]] 0 0 0
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
good
# with the kernel one_scores = sgd_rbf.decision_function([one_rbf_example]) print(one_scores) prediction = np.argmax(one_scores) print(prediction) print(digits.target_names[sgd_rbf.classes_[prediction]])
[[-1.43787351 -1.87790689 -2.6351228 -3.70534368 -2.11141745 -3.57570642 -0.83998359 -3.2773025 -2.55029636 -3.2336616 ]] 6 6
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
):
# without the kernel one_scores = sgd.decision_function([one_example]) print(one_scores) prediction = np.argmax(one_scores) print(prediction) print(digits.target_names[sgd.classes_[prediction]])
[[-10026. -333. -5977. -2605. -5370. -6327. -7540. -2234. -1181. -6917.]] 1 1
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
One VS One
from sklearn.multiclass import OneVsOneClassifier ovo_clf = OneVsOneClassifier(SGDClassifier(max_iter=100, random_state=42, loss="perceptron", eta0=1, learning_rate="constant", penalty=None)) ovo_clf.fit(X_train_features, y_train) ovo_clf.predict([one_rbf_example]) len(ovo_c...
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
10-way Naive Bayes
gnb.fit(X_train, y_train) gnb.predict([one_example])
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
wowIt correctly classifies the *one* example, so let's check how confident it is about this prediction (use `predict_proba` with `NaiveBayes` and `decision_function` with the `SGDClassifier`):
gnb.predict_proba([one_example])
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Cross-validation performance
print(cross_val_score(sgd_rbf, X_train_features, y_train, cv=5, scoring="accuracy")) print(cross_val_score(ovo_clf, X_train_features, y_train, cv=5, scoring="accuracy")) print(cross_val_score(gnb, X_train, y_train, cv=5, scoring="accuracy"))
[0.9375 0.90625 0.91637631 0.91986063 0.90592334] [0.93402778 0.92013889 0.92334495 0.91986063 0.91986063] [0.85416667 0.83333333 0.81881533 0.85365854 0.77700348]
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
ScalingLet's apply scaling
from sklearn.preprocessing import StandardScaler, MinMaxScaler #scaler = StandardScaler() scalar = MinMaxScaler() X_train_scaled = scaler.fit_transform(X_train.astype(np.float64)) X_train_features_scaled = scaler.fit_transform(X_train_features.astype(np.float64)) print(cross_val_score(sgd_rbf, X_train_features_scaled...
[0.93402778 0.90625 0.8989547 0.87108014 0.87456446] [0.94444444 0.9375 0.90940767 0.92682927 0.89198606] [0.79166667 0.78472222 0.76655052 0.80836237 0.72473868]
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
- StandardScaler() only made things worse[0.93402778 0.90625 0.8989547 0.87108014 0.87456446][0.94444444 0.9375 0.90940767 0.92682927 0.89198606][0.79166667 0.78472222 0.76655052 0.80836237 0.72473868]- MinMaxScaler() gives exact same values Step 5: Error Analysis
y_train_pred = cross_val_predict(sgd_rbf, X_train_features_scaled, y_train, cv=3) conf_mx = confusion_matrix(y_train, y_train_pred) conf_mx plt.imshow(conf_mx, cmap = "jet") plt.show() row_sums = conf_mx.sum(axis=1, keepdims=True) norm_conf_mx = conf_mx / row_sums np.fill_diagonal(norm_conf_mx, 0) plt.imshow(norm_conf_...
_____no_output_____
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Final step – evaluating on the test set
# non-kernel perceptron from sklearn.metrics import accuracy_score y_pred = sgd.predict(X_test) accuracy_score(y_test, y_pred) precision = precision_score(y_test, y_pred, average='weighted') recall = recall_score(y_test, y_pred, average='weighted') f1 = f1_score(y_test, y_pred, average='weighted') print(precision, rec...
0.9330274822584538 0.9305555555555556 0.9299190345492117
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
The OvO SGD classifier:
# One vs one from sklearn.metrics import accuracy_score X_test_features_scaled = scaler.transform(X_test_features.astype(np.float64)) y_pred = ovo_clf.predict(X_test_features_scaled) accuracy_score(y_test, y_pred) precision = precision_score(y_test, y_pred, average='weighted') recall = recall_score(y_test, y_pred, ave...
0.9038423919737274 0.8944444444444445 0.8906734076041858
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Naive Bayes
#Naive Bayes gnb.fit(X_train, y_train) y_pred = gnb.predict(X_test) accuracy_score(y_test, y_pred) precision = precision_score(y_test, y_pred, average='weighted') recall = recall_score(y_test, y_pred, average='weighted') f1 = f1_score(y_test, y_pred, average='weighted') print(precision, recall, f1)
0.8479871939298477 0.8111111111111111 0.8150828576150382
Apache-2.0
DSPNP_practical2/DSPNP_notebook2_digits.ipynb
frantu08/Data_Science_Unit_20-21
Collision Avoidance - Data CollectionIf you ran through the basic motion notebook, hopefully you're enjoying how easy it can be to make your Jetbot move around! Thats very cool! But what's even cooler, is making JetBot move around all by itself! This is a super hard task, that has many different approaches but the w...
import traitlets import ipywidgets.widgets as widgets from IPython.display import display from jetbot import Camera, bgr8_to_jpeg # camera = Camera.instance(width=224, height=224) image = widgets.Image(format='jpeg', width=224, height=224) # this width and height doesn't necessarily have to match the camera camera_lin...
_____no_output_____
MIT
.ipynb_checkpoints/data_collection-collisionavoidance_Jetbot_Joystick-checkpoint.ipynb
tomMEM/Jetbot-Project
Awesome, next let's create a few directories where we'll store all our data. We'll create a folder ``dataset`` that will contain two sub-folders ``free`` and ``blocked``, where we'll place the images for each scenario.
import os blocked_dir = 'dataset/blocked' free_dir = 'dataset/free' # we have this "try/except" statement because these next functions can throw an error if the directories exist already try: os.makedirs(free_dir) os.makedirs(blocked_dir) except FileExistsError: print('Directories are not created because ...
Directories are not created because they already exist
MIT
.ipynb_checkpoints/data_collection-collisionavoidance_Jetbot_Joystick-checkpoint.ipynb
tomMEM/Jetbot-Project
If you refresh the Jupyter file browser on the left, you should now see those directories appear. Next, let's create and display some buttons that we'll use to save snapshotsfor each class label. We'll also add some text boxes that will display how many images of each category that we've collected so far. This is use...
button_layout = widgets.Layout(width='128px', height='64px') free_button = widgets.Button(description='add free', button_style='success', layout=button_layout) blocked_button = widgets.Button(description='add blocked', button_style='danger', layout=button_layout) free_count = widgets.IntText(layout=button_layout, value...
_____no_output_____
MIT
.ipynb_checkpoints/data_collection-collisionavoidance_Jetbot_Joystick-checkpoint.ipynb
tomMEM/Jetbot-Project
Right now, these buttons wont do anything. We have to attach functions to save images for each category to the buttons' ``on_click`` event. We'll save the valueof the ``Image`` widget (rather than the camera), because it's already in compressed JPEG format!To make sure we don't repeat any file names (even across diff...
from uuid import uuid1 snapshot_image = widgets.Image(format='jpeg', width=224, height=224) def save_snapshot(directory): image_path = os.path.join(directory, str(uuid1()) + '.jpg') with open(image_path, 'wb') as f: f.write(image.value) # display snapshot that was saved snapshot_image.value = ...
_____no_output_____
MIT
.ipynb_checkpoints/data_collection-collisionavoidance_Jetbot_Joystick-checkpoint.ipynb
tomMEM/Jetbot-Project
Great! Now the buttons above should save images to the ``free`` and ``blocked`` directories. You can use the Jupyter Lab file browser to view these files!Now go ahead and collect some data 1. Place the robot in a scenario where it's blocked and press ``add blocked``2. Place the robot in a scenario where it's free and ...
!zip -r -q dataset.zip dataset
_____no_output_____
MIT
.ipynb_checkpoints/data_collection-collisionavoidance_Jetbot_Joystick-checkpoint.ipynb
tomMEM/Jetbot-Project
The Performance Of Models Trained On The MNIST Dataset On Custom-Drawn Images
import numpy as np import tensorflow as tf import sklearn, sklearn.linear_model, sklearn.multiclass, sklearn.naive_bayes import matplotlib.pyplot as plt import pandas as pd plt.rcParams["figure.figsize"] = (10, 10) plt.rcParams.update({'font.size': 12})
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Defining the data
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Making 1D versions of the MNIST images for the one-vs-rest classifier
train_images_flat = train_images.reshape((train_images.shape[0], train_images.shape[1] * train_images.shape[2])) / 255.0 test_images_flat = test_images.reshape((test_images.shape[0], test_images.shape[1] * test_images.shape[2])) / 255.0
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Making a 4D dataset and categorical labels for the neural net
train_images = np.expand_dims(train_images, axis=-1) / 255.0 test_images = np.expand_dims(test_images, axis=-1) / 255.0 #train_images = train_images.reshape(60000, 28, 28, 1) #test_images = test_images.reshape(10000, 28, 28, 1) train_labels_cat = tf.keras.utils.to_categorical(train_labels) test_labels_cat = tf.keras....
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Training Defining and training the one-vs-rest classifier
log_reg = sklearn.linear_model.SGDClassifier(loss='log', max_iter=1000, penalty='l2') classifier = sklearn.multiclass.OneVsRestClassifier(log_reg) classifier.fit(train_images_flat, train_labels)
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Defining and training the neural net
from tensorflow.keras import Sequential from tensorflow.keras import layers def create_model(): model = Sequential([ layers.Conv2D(64, 5, activation='relu', input_shape=(28, 28, 1)), layers.MaxPool2D(2), layers.Conv2D(128, 5, activation='relu'), layers.MaxPool2D(2), layers.Gl...
INFO:tensorflow:Assets written to: cnn-64-128-5-aug\assets
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Assessing model performance Loading drawn images
def read_images(filepaths, reverse=False): images = [] images_flat = [] for filepath in filepaths: image = tf.io.read_file(filepath) image = tf.image.decode_image(image, channels=1) image = tf.image.resize(image, (28, 28)) if reverse: image =...
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Creating labels for the one-vs-rest classifier and the neural net
labels = 100 * [0] + 98 * [1] + 100 * [2] + 101 * [3] + 99 * [4] + 111 * [5] + 89 * [6] + 110 * [7] + 93 * [8] + 112 * [9] labels = np.array(labels) labels.shape labels_cat = tf.keras.utils.to_categorical(labels) labels_cat.shape labels_cat[0]
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Plotting the drawn images and their corresponding labels
plot_images(images, labels)
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Evaluating model performance Neural net on MNIST test dataset
model.evaluate(test_images, test_labels_cat) from sklearn.metrics import classification_report, confusion_matrix predictions = np.argmax(model.predict(test_images), axis=-1) conf_mat = confusion_matrix(test_labels, predictions) conf_mat class_report = classification_report(test_labels, predictions, output_dict=True)...
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Neural net on drawn images
model.evaluate(images, labels_cat) predictions = np.argmax(model.predict(images), axis=-1) rows, cols = 5, 5 fig, axes = plt.subplots(rows, cols) fig.figsize=(15, 15) indices = np.random.choice(len(images), rows * cols) counter = 0 for i in range(rows): for j in range(cols): axes[i, j].imshow(ima...
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Plotting wrong predictions
wrong_predictions = list(filter(lambda x: x[1][0] != x[1][1], list(enumerate(zip(predictions, labels))))) len(wrong_predictions) cols, rows = 5, 5 fig, axes = plt.subplots(rows, cols) fig.figsize=(15, 15) counter = 0 for i in range(rows): for j in range(cols): axes[i, j].imshow(images[wrong_predictio...
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
One-vs-rest classifier on MNIST test dataset
classifier.score(test_images_flat, test_labels) predictions = classifier.predict(test_images_flat) conf_mat = confusion_matrix(test_labels, predictions) conf_mat class_report = classification_report(test_labels, predictions, output_dict=True) class_report
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
One-vs-rest classifier on drawn images
classifier.score(images_flat, labels) predictions = classifier.predict(images_flat) conf_mat = confusion_matrix(labels, predictions) conf_mat class_report = classification_report(labels, predictions, output_dict=True) class_report
_____no_output_____
MIT
notebooks/digit-classification-test.ipynb
MovsisyanM/digit-recognizer
Plot Comparison Between Algorithms Expects the input data to contain CSV files containing rewards per timestep
import os import numpy as np %reload_ext autoreload %autoreload 2
_____no_output_____
MIT
plot/plotFromRewards.ipynb
architsakhadeo/OHT
We need to read the CSV files (from a function in another file) to get the reward at each timestep for each run of each algorithm. Only the `dataPath` directories will be loaded.`load_data` loads the CSV files containing rewards as a python list of Pandas DataFrames.`dataPath` contains the exact path of the directories...
dataPath = ['esarsa/alpha-0.015625_driftProb--1,-1,-1,-1_driftScale-1000_enable-debug-0_epsilon-0.05_gamma-0.95_lambda-0.8_sensorLife-1,1,1,1_tiles-4_tilings-32', 'dqn/alpha-0.015625_driftProb--1,-1,-1,-1_driftScale-100_enable-debug-0_epsilon-0.05_gamma-0.95_lambda-0.8_sensorLife-1,1,1,1_tiles-4_tilings-32/...
Data will be stored for esarsa Loaded the rewards data from the csv files
MIT
plot/plotFromRewards.ipynb
architsakhadeo/OHT
The rewards can be transformed into the following values of transformation =1. 'Returns'2. 'Failures'3. 'Average-Rewards'4. 'Rewards' (no change)----------------------------------------------------------------------------------------------There is an additional parameter of window which can be any non-negative integer....
plottingData = {} from loadFromRewards import transform_data transformation = 'Returns' window = 2500 for alg, data in Data.items(): plottingData[alg] = transform_data(alg, data, transformation, window) print('Data will be plotted for', ', '.join([k for k in plottingData.keys()])) print('The stored rewards are ...
0 esarsa Data will be plotted for esarsa The stored rewards are transformed to: Returns
MIT
plot/plotFromRewards.ipynb
architsakhadeo/OHT
Here, we can plot the following statistics:1. Mean of all the runs2. Median run3. Run with the best performance (highest return, or equivalently least failures)4. Run with the worst performance (lowest return, or equivalently most failures)5. Mean along with the confidence interval (Currently, plots the mean along with...
from stats import getMean, getMedian, getBest, getWorst, getConfidenceIntervalOfMean, getRegion # Add color, linestyles as needed def plotMean(xAxis, data, color): mean = getMean(data) plt.plot(xAxis, mean, label=alg+'-mean', color=color) def plotMedian(xAxis, data, color): median = getMedian(data) p...
_____no_output_____
MIT
plot/plotFromRewards.ipynb
architsakhadeo/OHT
Details:- X axis for 'Average-Rewards' will start from 'window' timesteps and end with the final timesteps- Need to add color (shades), linestyle as per requirements- Currently plot one at a time by commenting out the others otherwise, it displays different colors for all.
# For saving figures #%matplotlib inline # For plotting in the jupyter notebook %matplotlib notebook import matplotlib.pyplot as plt colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] for alg, data in plottingData.items(): lenRun = len(data[0]) xAxis = np.array([i for i in range(1,lenRun+1)...
_____no_output_____
MIT
plot/plotFromRewards.ipynb
architsakhadeo/OHT
Classification with MNIST Dataset and ResNet networkThis script sets up a ResNet-style network to classify digits from the MNIST dataset.
import keras import keras.backend as K from keras.datasets import mnist from keras.models import Model from keras.layers import Input, Conv2D, Dense, Flatten, MaxPooling2D, Add, Activation, Dropout from keras.optimizers import SGD from matplotlib import pyplot as plt import numpy as np
Using TensorFlow backend.
MIT
mnist/resnet_mnist.ipynb
jonathanventura/nncookbook
Use a Keras utility function to load the MNIST dataset. We select only zeros and ones to do binary classification.
(x_train, y_train), (x_test, y_test) = mnist.load_data() y_train = keras.utils.to_categorical(y_train,10) y_test = keras.utils.to_categorical(y_test,10)
_____no_output_____
MIT
mnist/resnet_mnist.ipynb
jonathanventura/nncookbook
Resize the images to vectors and convert their datatype and range.
x_train = np.expand_dims(x_train,axis=-1) x_test = np.expand_dims(x_test,axis=-1) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 x_train = x_train*2.-1. x_test = x_test*2.-1.
_____no_output_____
MIT
mnist/resnet_mnist.ipynb
jonathanventura/nncookbook
Build a multi-class classifier model.
def res_block(x,c,s=1): if K.shape(x)[3] <> c or s <> 1: x_save = Conv2D(c,1,strides=s,activation=None)(x) else: x_save = x x = Conv2D(c,3,strides=s,padding='same',activation='relu',kernel_initializer='he_normal')(x) x = Conv2D(c,3,padding='same',activation=None,kernel_initializer='he_no...
____________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ==================================================================================================== input_1 (InputLay...
MIT
mnist/resnet_mnist.ipynb
jonathanventura/nncookbook
Set up the model to optimize the categorical crossentropy loss using stochastic gradient descent.
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
_____no_output_____
MIT
mnist/resnet_mnist.ipynb
jonathanventura/nncookbook
Optimize the model over the training data.
history = model.fit(x_train, y_train, batch_size=100, epochs=20, verbose=1, validation_data=(x_test, y_test)) plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.legend(['Training Loss','Testing Loss']) plt.xlabel('E...
_____no_output_____
MIT
mnist/resnet_mnist.ipynb
jonathanventura/nncookbook
Base class
#export class ProgressBar(): update_every,first_its = 0.2,5 def __init__(self, gen, total=None, display=True, leave=True, parent=None, master=None, comment=''): self.gen,self.parent,self.master,self.comment = gen,parent,master,comment self.total = len(gen) if total is None else total se...
_____no_output_____
Apache-2.0
nbs/01_fastprogress.ipynb
hsm/fastprogress
Notebook progress bars
#export if IN_NOTEBOOK: try: from IPython.display import clear_output, display, HTML import matplotlib.pyplot as plt import ipywidgets as widgets except: warn("Couldn't import ipywidgets properly, progress bar will use console behavior") IN_NOTEBOOK = False #export class ...
_____no_output_____
Apache-2.0
nbs/01_fastprogress.ipynb
hsm/fastprogress
Console progress bars
#export NO_BAR = False WRITER_FN = print FLUSH = True SAVE_PATH = None SAVE_APPEND = False MAX_COLS = 160 #export def printing(): return False if NO_BAR else (stdout.isatty() or IN_NOTEBOOK) #export class ConsoleProgressBar(ProgressBar): fill:str='█' end:str='\r' def __init__(self, gen, total=None, di...
_____no_output_____
Apache-2.0
nbs/01_fastprogress.ipynb
hsm/fastprogress
Export -
from nbdev.export import notebook2script notebook2script()
_____no_output_____
Apache-2.0
nbs/01_fastprogress.ipynb
hsm/fastprogress
Impotations de dependances
import numpy as np import pandas as pd #import matplotlib.pyplot as plt #import seaborn as sns from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn import svm from sklearn.metrics import accuracy_score #from sklearn.cluster import KMeans #from sklearn.model_...
_____no_output_____
MIT
Prediction_diabet.ipynb
bsyllaisidk/Architecture-L
chargement des données du fichier csv dans une trame de données pendas
diabet_data = pd.read_csv('/content/diabete.csv')
_____no_output_____
MIT
Prediction_diabet.ipynb
bsyllaisidk/Architecture-L
lecture des donnes du tableau
pd.read_csv
_____no_output_____
MIT
Prediction_diabet.ipynb
bsyllaisidk/Architecture-L
les 5 premiers lignes du tableau
diabet_data.head() # le nombre de ligne et de colonnes dans notre base de donnes diabet_data.shape #Pour obtenir les mesures statistique de cette donnee. diabet_data.describe()
_____no_output_____
MIT
Prediction_diabet.ipynb
bsyllaisidk/Architecture-L
le nombre de diabetique et le non diabetique 0--> non Diabetique1--> Diabetique
diabet_data['diabete'].value_counts() diabet_data.groupby('diabete').mean() #Sepearation de données et les etiquettes X=diabet_data.drop(columns='diabete', axis=1) Y=diabet_data['diabete'] #lecture de X print(X) print(Y)
0 1 1 0 2 1 3 0 4 1 .. 763 0 764 0 765 0 766 1 767 0 Name: diabete, Length: 768, dtype: int64
MIT
Prediction_diabet.ipynb
bsyllaisidk/Architecture-L
Normalisation des donnees.
scaler = StandardScaler() scaler.fit(X) standardized_date = scaler.transform(X) print(standardized_date) X = standardized_date Y = diabet_data['diabete'] print(X) print(Y) #Essaye de train fractionné X_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.2, stratify=Y, random_state=2) print(X.shape, X_tra...
(768, 8) (614, 8) (154, 8)
MIT
Prediction_diabet.ipynb
bsyllaisidk/Architecture-L
Model de formation
classifier = svm.SVC(kernel='linear')
_____no_output_____
MIT
Prediction_diabet.ipynb
bsyllaisidk/Architecture-L
Formation de la machine a vecteur classée
classifier.fit(X_train, Y_train)
_____no_output_____
MIT
Prediction_diabet.ipynb
bsyllaisidk/Architecture-L
Evaluation de modele Note de precision
# Score de precision sur les données de formation X_train_prediction = classifier.predict(X_train) training_data_accuracy = accuracy_score(X_train_prediction, Y_train) print('Score de precision sur les données de formation : ', training_data_accuracy) # Score de precision sur les données de formation X_test_prediction ...
Score de precision sur les données de teste : 0.7727272727272727
MIT
Prediction_diabet.ipynb
bsyllaisidk/Architecture-L
Faaier un systeme predictif
input_data = (2,197,70,45,543,30.5,0.158,53) # Changement de inptu_data en tableau nympy input_data_as_numpy_array = np.asarray(input_data) # Remodeler le tableau comme nous le predisons une instance input_data_reshaped = input_data_as_numpy_array.reshape(1,-1) # normaliser l’entrée de donnees std_date = scaler.tra...
[[-0.54791859 2.38188392 0.04624525 1.53455054 4.02192191 -0.18943689 -0.94794368 1.68125866]] [1] La peronne est diabetique
MIT
Prediction_diabet.ipynb
bsyllaisidk/Architecture-L
Breakdown of lethality
import pickle import pandas as pd import os import seaborn as sns import matplotlib.pyplot as plt import numpy as np from ast import literal_eval
_____no_output_____
MIT
notebooks/10b-anlyz_run02-synthetic_lethal_classes-feat1.ipynb
pritchardlabatpsu/cga