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 |
|---|---|---|---|---|---|
Энтропия и критерий Джини$p_i$ - вероятность нахождения системы в i-ом состоянии.Энтропия Шеннона определяется для системы с N возможными состояниями следующим образом$S = - \sum_{i=1}^Np_ilog_2p_i$ Критерий Джини (Gini Impurity). Максимизацию этого критерия можно интерпретировать как максимизацию числа пар объектов ... | import numpy as np
import math
def get_possibilities(y):
count = len(y)
uniq_values = set(y)
possibilities = []
for value in uniq_values:
possibilities.append(len(y[y ==value]) / count)
return possibilities
def gini_impurity(y: np.ndarray) -> float:
possibilities = get_possibilities(y)... | _____no_output_____ | MIT | 07-KNN, DT, Bayes/Homework.ipynb | PetrovaDaria/mlmathmech |
Information gainВам надо реализовать функцию inform_gain, которая будет вычислять прирост информации для критерия (энтропия или критерий Джини) при разбиении выбрки по признаку (threshold).Прирост информации при разбиении выборки по признаку Q (например x≤12) определяется как$IG(Q)=S_0- \sum_{i=1}^q\frac{N_i}{N}S_i$ ... | import numpy as np
import math
def get_possibilities(y):
count = len(y)
y = list(y)
uniq_values = set(y)
possibilities = []
for value in uniq_values:
possibilities.append(len(list(filter(lambda x: x == value, y))) / count)
return possibilities
def gini_impurity(y: np.ndarray) -> float:... | 0.6099865470109875
| MIT | 07-KNN, DT, Bayes/Homework.ipynb | PetrovaDaria/mlmathmech |
Best splitРеализуйте функцию find_best_split, которая находит наилучшее разбиение по всем признакам. На вход подется обучающая выборка и функция критерий. Необходимо вернуть: индекс фичи, значение границы (threshold) и результат разбиение (information gain). | import math
def get_possibilities(y):
count = len(y)
y = list(y)
uniq_values = set(y)
possibilities = []
for value in uniq_values:
possibilities.append(len(list(filter(lambda x: x == value, y))) / count)
return possibilities
def gini_impurity(y: np.ndarray) -> float:
possibilities ... | _____no_output_____ | MIT | 07-KNN, DT, Bayes/Homework.ipynb | PetrovaDaria/mlmathmech |
Мое дерево решенийВаша задача реализовать свой простой KNNClassifier для бинарных данных. Вам нужно реализовать 3 метода:fit - обучение классификатораpredict - предсказание для новых объектовpredict_proba - предсказание вероятностей новых объектовУ нашего классификатора будет лишь два гиперпараметра - максимальная глу... | import math
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
class MyDecisionTreeClassifier(BaseEstimator, ClassifierMixin):
def __init__(self, max_depth=4, criterion='entropy'):
self.eps = 0.001
self.max_depth = max_depth
self.criterion = criterion # 'entropy' or... | X [ 1 2 -1 -1 2 3]
threshold 1
y [1 1 0 0 0 0]
first [0, 0]
second [1, 1, 0, 0]
value 1 score 0.2513333333333334
X [ 1 2 -1 -1 2 3]
threshold 2
y [1 1 0 0 0 0]
first [1, 0, 0]
second [1, 0, 0]
value 2 score 0.0
X [ 1 2 -1 -1 2 3]
threshold 3
y [1 1 0 0 0 0]
first [1, 1, 0, 0, 0]
second [0]... | MIT | 07-KNN, DT, Bayes/Homework.ipynb | PetrovaDaria/mlmathmech |
Наивный БайесТребуется написать свой классификтор, на основе наивного баеса. Необходимо реализовать аналог MultinomialNB.$y_{test}=argmax_cln(P(y_{test}=c))+\sum_{j=1}^mln(P(f_j|y_{test}=c)+ \alpha)$, c∈{0,1}На вход подаются численные категориальные признаки. Классы: 00 и 11. У классификатора будет единственный параме... | from sklearn.base import BaseEstimator, ClassifierMixin
from collections import defaultdict
from math import log, inf
import numpy as np
class MyNaiveBayes(BaseEstimator, ClassifierMixin):
def __init__(self, alpha=1):
self.alpha = alpha
self.classes = [0, 1]
self.class_counts = {0: 0, 1: 0}... | _____no_output_____ | MIT | 07-KNN, DT, Bayes/Homework.ipynb | PetrovaDaria/mlmathmech |
Check 0-3 - Toddler Above 3 - 12 - Kid Above 12 - 19 - Teen Above 19 - 30 - Young Adults Above 30 - 50 - Adults Above 50 - 60 - Mature Above 60 - 80 - Senior Citizens Above 80 - Super Senior Citizens | age = input("Enter age ")
age = int(age)
print(type(age))
if age <=3:
print("Toddler")
elif age > 3 and age <= 12:
print("Kid")
elif age > 12 and age <= 19:
print("Teen")
elif age > 19 and age <= 30:
print("Young Adult")
elif age > 30 and age < 50:
print("Adult")
elif age >= 50 and age < 60:
pri... | Enter age 45
<class 'int'>
Adult
| MIT | Python Basics/First.ipynb | kashish-goel/Machine-Learning |
Loading the dataThe dataset comes preloaded in Keras, which means I don't need to open or read any files manually and one simple command will get us training and testing data. The command to load the data will actually split the words into training and testing sets and labels. There is a parameter for how many words w... | # load the data(it's comes preloaded with Keras)
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=1000)
print(x_train.shape)
print(x_test.shape) | (25000,)
(25000,)
| MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
Examining the dataNotice that the data has been already pre-processed, where all the words have numbers, and the reviews come in as a vector with the words that the review contains. For example, if the word 'the' is the first one in our dictionary, and a review contains the word 'the', then there is a 1 in the corresp... | print(x_train[0])
print(y_train[0]) | [1, 14, 22, 16, 43, 530, 973, 2, 2, 65, 458, 2, 66, 2, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 2, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 2, 336, 385, 39, 4, 172, 2, 2, 17, 546, 38, 13, 447, 4, 192, 50, 16, 6, 147, 2, 19, 14, 22, 4, 2, 2, 469, 4, 22, 71, 87, 12, 16, 43, 530, 38, 76, 15, 13, 2, 4, 22, 17,... | MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
One-hot encoding the dataNow, let's turn the input vectors into (0,1)-vectors. For example, if the pre-processed vector contains the number 14, then in the processed vector, the 14th entry will be 1. | # one-hot encoding the input into vector mode, each of length 1000
tokenizer = Tokenizer(num_words=1000)
x_train = tokenizer.sequences_to_matrix(x_train, mode='binary')
x_test = tokenizer.sequences_to_matrix(x_test, mode='binary')
print(x_train[0]) | [0. 1. 1. 0. 1. 1. 1. 1. 1. 1. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. 0. 1. 1. 0.
0. 1. 1. 0. 1. 0. 1. 0. 1. 1. 0. 1. 1. 0. 1. 1. 0. 0. 0. 1. 0. 0. 1. 0.
1. 0. 1. 1. 1. 0. 0. 0. 1. 0. 0. 0. 0. 0. 1. 0. 0. 1. 1. 0. 0. 0. 0. 1.
0. 0. 0. 0. 1. 1. 0. 0. 0. 0. 1. 0. 0. 0. 0. 1. 1. 0. 0. 0. 1. 0. 0. 0.
0. 0. 1. 0. 1. 0. 0. 1. 1. ... | MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
And we'll also one-hot encode the output. | # one-hot encoding the output
num_classes = 2
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
print(y_train.shape)
print(y_test.shape) | (25000, 2)
(25000, 2)
| MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
Building the model architecture | # build the model architecture with one layer of length 100
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=1000))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.summary()
# compile the model using categorical_crossentropy loss, and rmsprop optimizer.
model.com... | WARNING: Logging before flag parsing goes to stderr.
W0719 18:29:40.188429 6340 deprecation_wrapper.py:119] From c:\users\aditya\appdata\local\programs\python\python37\lib\site-packages\keras\backend\tensorflow_backend.py:74: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instea... | MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
Training the model | # train the model
hist = model.fit(x_train, y_train,
batch_size=32,
epochs=10,
validation_data=(x_test, y_test),
verbose=2) | W0719 18:56:13.029227 6340 deprecation.py:323] From c:\users\aditya\appdata\local\programs\python\python37\lib\site-packages\tensorflow\python\ops\math_grad.py:1250: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for upda... | MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
Evaluating the model | # evaluate the model
score = model.evaluate(x_test, y_test, verbose=0)
print("Accuracy: ", score[1]) | Accuracy: 0.85532
| MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
The trained model has an accuracy of 85.53%. Let's make some changes in our model architecture to improve the accuracy. It might be possible by adding one more hidden layer and dropout to reduce overfitting. Let's explore now. | # build the model architecture with one layer of length 100
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=1000))
model.add(Dropout(0.5))
model.add(Dense(256, activation='relu')) # newly added layer
model.add(Dropout(0.3)) # added dropout regularization of 0.3
model.add(Dense(... | Accuracy: 0.85736
| MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
Although small, the new model with an extra hidden and a dropout layer shows the accuracy of 85.73% which is higher than the previous model. Let's experiment with applying reduced dropout of 0.2 and 0.1 to the corresponding dropout layers. | # build the model architecture with one layer of length 100
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=1000))
model.add(Dropout(0.2)) # changed dropout to 0.2 from 0.5
model.add(Dense(256, activation='relu')) # newly added layer
model.add(Dropout(0.1)) # c... | Accuracy: 0.8448
| MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
It can be observed that the acuracy takes a hit, being reduced to 84.48% from 85.73%, when the dropout values are changed from 0.5 to 0.2 for the first dropout layer and from 0.3 to 0.1 for the second dropout layer. For the chosen network configuration, reducing the dropout rate in the hidden layers did not lift perfor... | # build the model architecture with one layer of length 100
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=1000))
model.add(Dropout(0.5)) # changed dropout rate from to 0.2 to 0.5 again
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.4)) # changed ... | _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_9 (Dense) (None, 512) 512512
________________________________________________________... | MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
Lets's see what happens when model is trained with increased batch_size of 200 aand higher epochs 0f 50. | # train the model
hist = model.fit(x_train, y_train,
batch_size=200,
epochs=50,
validation_data=(x_test, y_test),
verbose=2) | Train on 25000 samples, validate on 25000 samples
Epoch 1/50
- 14s - loss: 0.4686 - acc: 0.7798 - val_loss: 0.3315 - val_acc: 0.8578
Epoch 2/50
- 9s - loss: 0.3312 - acc: 0.8605 - val_loss: 0.3414 - val_acc: 0.8527
Epoch 3/50
- 9s - loss: 0.2891 - acc: 0.8792 - val_loss: 0.3564 - val_acc: 0.8510
Epoch 4/50
- 9s - l... | MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
From the results, it is obvious that the model is overfitting. We need to tweak the hyperparameters again in order to improve the network's performance. Let's explore the effect of increase in nodes of the hidden layer on the model's performaance. | # build the model architecture with one layer of length 100
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=1000))
model.add(Dropout(0.5))
model.add(Dense(384, activation='relu')) # increased no. of nodes in the hidden layer from 256 to 384
model.add(Dropout(0.3)) # changed dro... | Train on 25000 samples, validate on 25000 samples
Epoch 1/10
- 75s - loss: 0.4219 - acc: 0.8170 - val_loss: 0.3624 - val_acc: 0.8565
Epoch 2/10
- 29s - loss: 0.3557 - acc: 0.8574 - val_loss: 0.3674 - val_acc: 0.8612
Epoch 3/10
- 28s - loss: 0.3341 - acc: 0.8695 - val_loss: 0.3708 - val_acc: 0.8580
Epoch 4/10
- 29s ... | MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
The network performance shows improvement as compared to the performance of the previous network architecture. Lets change the optimizer 'rmsprop' used in the previous model to 'adam' and check network's performance. | # build the model architecture with one layer of length 100
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=1000))
model.add(Dropout(0.5))
model.add(Dense(384, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(num_classes, activation='softmax'))
model.summary()
# compi... | Accuracy: 0.8496
| MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
Here, in this case the 'rmsprop' seems to be a better optimizer than 'adam' for the model in terms of its performance(test accuracy) which is 85.70% and 84.96% respectively. Now, let us add an extra hidden layer before the output layer and apply dropout to it. | # build the model architecture with one layer of length 100
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=1000))
model.add(Dropout(0.5))
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.3))
model.add(Dense(256, activation='relu')) # newly added hidden layer
model.add(Dropout(0.3)) ... | Accuracy: 0.85252
| MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
Let's increase the number of nodes in the first hidden layer to 384 and see what happens. | # build the model architecture with one layer of length 100
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=1000))
model.add(Dropout(0.5))
model.add(Dense(384, activation='relu')) # changed number of nodes to 384
model.add(Dropout(0.3))
model.add(Dense(256, activation='relu'))
model.add(Dropout(... | Accuracy: 0.85892
| MIT | IMDB_in _Keras.ipynb | adityasaxena26/analyzing-IMDb-data-in-Keras |
========================================================================Illustration of Gaussian process classification (GPC) on the XOR dataset========================================================================This example illustrates GPC on XOR data. Compared are a stationary, isotropickernel (RBF) and a non-sta... | print(__doc__)
# Authors: Jan Hendrik Metzen <jhm@informatik.uni-bremen.de>
#
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF, DotProduct
xx, yy = np.meshgrid(np.linspace(-3, 3... | _____no_output_____ | Apache-2.0 | 01 Machine Learning/scikit_examples_jupyter/gaussian_process/plot_gpc_xor.ipynb | alphaolomi/colab |
Interpolation [Gerard Gorman](http://www.imperial.ac.uk/people/g.gorman), [Matthew Piggott](http://www.imperial.ac.uk/people/m.d.piggott), [Christian Jacobs](http://www.christianjacobs.uk) Interpolation vs curve-fittingConsider a discrete set of data points $$ (x_i, y_i),\quad i=0,\ldots,N,$$and that we wish to appro... | %pylab inline
# Invent some raw data
x=numpy.array([0.5,2.0,4.0,5.0,7.0,9.0])
y=numpy.array([0.5,0.4,0.3,0.1,0.9,0.8])
# For clarity we are going to add a small margin to all the plots.
pylab.margins(0.1)
# We want to overlay a plot the raw data a few times so lets make this a function.
def plot_raw_data(x,y):
... | Populating the interactive namespace from numpy and matplotlib
| MIT | 2016-1/w06/Interpolation-Exercises.ipynb | forero/ComputationalLab |
We can use [scipy.interpolate.lagrange](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.lagrange.html)from [SciPy](http://www.scipy.org) to generate the **Lagrange polynomial** for a dataset as shown below.(Note: SciPy provides a [wide range of interpolators](http://docs.scipy.org/doc/scipy/refere... | import scipy.interpolate
# Create the Lagrange polynomial for the given points.
lp=scipy.interpolate.lagrange(x, y)
# Evaluate this fuction at a high resolution so that we can get a smooth plot.
xx=numpy.linspace(0.4, 9.1, 100)
pylab.plot(xx, lp(xx), 'b', label='Lagrange')
# Overlay raw data
plot_raw_data(x, y)
# ... | _____no_output_____ | MIT | 2016-1/w06/Interpolation-Exercises.ipynb | forero/ComputationalLab |
Error in Lagrange interpolationNote that it can be proven that in the case where we are interpolating a known function (e.g. a complex non-polynomial function by a simpler polynomial), the error is proportional to the distance from any of the data points (which makes sense as the error is obviously zero at these point... | # Calculate coefficients of polynomial degree 0 - ie a constant value.
poly_coeffs=numpy.polyfit(x, y, 0)
# Construct a polynomial function which we can use to evaluate for arbitrary x values.
p0 = numpy.poly1d(poly_coeffs)
pylab.plot(xx, p0(xx), 'k', label='Constant')
# Fit a polynomial degree 1 - ie a straight line... | _____no_output_____ | MIT | 2016-1/w06/Interpolation-Exercises.ipynb | forero/ComputationalLab |
Model Deployment Once we have built and trained our models for feature engineering (using Amazon SageMaker Processing and SKLearn) and binary classification (using the XGBoost open-source container for Amazon SageMaker), we can choose to deploy them in a pipeline on Amazon SageMaker Hosting, by creating an Inference Pi... | import sagemaker
import sys
import IPython
# Let's make sure we have the required version of the SM PySDK.
required_version = '2.49.2'
def versiontuple(v):
return tuple(map(int, (v.split("."))))
if versiontuple(sagemaker.__version__) < versiontuple(required_version):
!{sys.executable} -m pip install -U sagem... | _____no_output_____ | Apache-2.0 | 04_deploy_model/04_deploy_model.ipynb | Niobiumkey/amazon-sagemaker-build-train-deploy |
Retrieve model artifacts First, we need to create two Amazon SageMaker **Model** objects, which associate the artifacts of training (serialized model artifacts in Amazon S3) to the Docker container used for inference. In order to do that, we need to get the paths to our serialized models in Amazon S3. For the SKLea... | from notebook_utilities import get_latest_training_job_name, get_training_job_s3_model_artifacts
# SKLearn model artifacts path.
sklearn_model_path = 's3://{0}/{1}/output/sklearn/model.tar.gz'.format(bucket_name, prefix)
# XGBoost model artifacts path.
training_base_job_name = 'end-to-end-ml-sm-xgb'
latest_training_j... | _____no_output_____ | Apache-2.0 | 04_deploy_model/04_deploy_model.ipynb | Niobiumkey/amazon-sagemaker-build-train-deploy |
SKLearn Featurizer Model Let's build the SKLearn model. For hosting this model we also provide a custom inference script, that is used to process the inputs and outputs and execute the transform.The inference script is implemented in the `sklearn_source_dir/inference.py` file. The custom script defines:- a custom `inp... | !pygmentize sklearn_source_dir/inference.py | _____no_output_____ | Apache-2.0 | 04_deploy_model/04_deploy_model.ipynb | Niobiumkey/amazon-sagemaker-build-train-deploy |
Now, let's create the `SKLearnModel` object, by providing the custom script and S3 model artifacts as input. | import time
from sagemaker.sklearn import SKLearnModel
code_location = 's3://{0}/{1}/code'.format(bucket_name, prefix)
sklearn_model = SKLearnModel(name='end-to-end-ml-sm-skl-model-{0}'.format(str(int(time.time()))),
model_data=sklearn_model_path,
entry_point=... | _____no_output_____ | Apache-2.0 | 04_deploy_model/04_deploy_model.ipynb | Niobiumkey/amazon-sagemaker-build-train-deploy |
XGBoost Model Similarly to the previous steps, we can create an `XGBoost` model object. Also here, we have to provide a custom inference script.The inference script is implemented in the `xgboost_source_dir/inference.py` file. The custom script defines:- a custom `input_fn` for pre-processing inference requests. This ... | !pygmentize xgboost_source_dir/inference.py | _____no_output_____ | Apache-2.0 | 04_deploy_model/04_deploy_model.ipynb | Niobiumkey/amazon-sagemaker-build-train-deploy |
Now, let's create the `XGBoostModel` object, by providing the custom script and S3 model artifacts as input. | import time
from sagemaker.xgboost import XGBoostModel
code_location = 's3://{0}/{1}/code'.format(bucket_name, prefix)
xgboost_model = XGBoostModel(name='end-to-end-ml-sm-xgb-model-{0}'.format(str(int(time.time()))),
model_data=xgboost_model_path,
entry_point=... | _____no_output_____ | Apache-2.0 | 04_deploy_model/04_deploy_model.ipynb | Niobiumkey/amazon-sagemaker-build-train-deploy |
Pipeline Model Once we have models ready, we can deploy them in a pipeline, by building a `PipelineModel` object and calling the `deploy()` method. | import sagemaker
import time
from sagemaker.pipeline import PipelineModel
pipeline_model_name = 'end-to-end-ml-sm-xgb-skl-pipeline-{0}'.format(str(int(time.time())))
pipeline_model = PipelineModel(
name=pipeline_model_name,
role=role,
models=[
sklearn_model,
xgboost_model],
sagemaker... | _____no_output_____ | Apache-2.0 | 04_deploy_model/04_deploy_model.ipynb | Niobiumkey/amazon-sagemaker-build-train-deploy |
Please take note of the endpoint name, since it will be used in the next workshop module. Getting inferences Finally we can try invoking our pipeline of models and get some inferences: | from sagemaker.serializers import CSVSerializer
from sagemaker.deserializers import JSONDeserializer
from sagemaker.predictor import Predictor
predictor = Predictor(
endpoint_name=endpoint_name,
sagemaker_session=sagemaker_session,
serializer=CSVSerializer(),
deserializer=JSONDeserializer())
#'Type', ... | _____no_output_____ | Apache-2.0 | 04_deploy_model/04_deploy_model.ipynb | Niobiumkey/amazon-sagemaker-build-train-deploy |
Preprocessing | # Import our dependencies
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import pandas as pd
import tensorflow as tf
from keras.callbacks import ModelCheckpoint
# Import and read the charity_data.csv.
import pandas as pd
application_df = pd.read_csv("charity_da... | _____no_output_____ | ADSL | Starter_Code.ipynb | tritchlin/deep_learning |
Compile, Train and Evaluate the Model | # Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer.
number_input_features = len(X_train[0])
hidden_nodes_layer1 = 80
hidden_nodes_layer2 = 30
nn = tf.keras.models.Sequential()
# First hidden layer
nn.add(
tf.keras.layers.Dense(units=hidden_nodes_layer1, input... | 268/268 - 0s - loss: 0.5578 - accuracy: 0.7256
Loss: 0.5577850937843323, Accuracy: 0.7255976796150208
| ADSL | Starter_Code.ipynb | tritchlin/deep_learning |
Goal of this notebook to test several classifiers on the data set with different features And beforehand i want to thank Jose Portilla for his magnificent "Python for Data Science and Machine Learning" course on Udemy , which helped me to dive into ML =) Let's begin First of all neccesary imports | import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import string
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from nltk.stem import SnowballStemmer
from nltk.corpus import stopwords
%ma... | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Let's read the data from csv file | sms = pd.read_csv('../input/spam.csv', encoding='latin-1')
sms.head() | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Now drop "unnamed" columns and rename v1 and v2 to "label" and "message" | sms = sms.drop(['Unnamed: 2','Unnamed: 3','Unnamed: 4'],axis=1)
sms = sms.rename(columns = {'v1':'label','v2':'message'}) | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Let's look into our data | sms.groupby('label').describe() | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Intresting that "Sorry, I'll call later" appears only 30 times here =) Now let's create new feature "message length" and plot it to see if it's of any interest | sms['length'] = sms['message'].apply(len)
sms.head()
mpl.rcParams['patch.force_edgecolor'] = True
plt.style.use('seaborn-bright')
sms.hist(column='length', by='label', bins=50,figsize=(11,5)) | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Looks like the lengthy is the message, more likely it is a spam. Let's not forget this Text processing and vectorizing our meddages Let's create new data frame. We'll need a copy later on | text_feat = sms['message'].copy() | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Now define our tex precessing function. It will remove any punctuation and stopwords aswell. | def text_process(text):
text = text.translate(str.maketrans('', '', string.punctuation))
text = [word for word in text.split() if word.lower() not in stopwords.words('english')]
return " ".join(text)
text_feat = text_feat.apply(text_process)
vectorizer = TfidfVectorizer("english")
features = vecto... | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Classifiers and predictions First of all let's split our features to test and train set | features_train, features_test, labels_train, labels_test = train_test_split(features, sms['label'], test_size=0.3, random_state=111) | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Now let's import bunch of classifiers, initialize them and make a dictionary to itereate through | from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassi... | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Parametres are based on notebook:[Spam detection Classifiers hyperparameter tuning][1] [1]: https://www.kaggle.com/muzzzdy/d/uciml/sms-spam-collection-dataset/spam-detection-classifiers-hyperparameter-tuning/ | clfs = {'SVC' : svc,'KN' : knc, 'NB': mnb, 'DT': dtc, 'LR': lrc, 'RF': rfc, 'AdaBoost': abc, 'BgC': bc, 'ETC': etc} | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Let's make functions to fit our classifiers and make predictions | def train_classifier(clf, feature_train, labels_train):
clf.fit(feature_train, labels_train)
def predict_labels(clf, features):
return (clf.predict(features)) | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Now iterate through classifiers and save the results | pred_scores = []
for k,v in clfs.items():
train_classifier(v, features_train, labels_train)
pred = predict_labels(v,features_test)
pred_scores.append((k, [accuracy_score(labels_test,pred)]))
df = pd.DataFrame.from_items(pred_scores,orient='index', columns=['Score'])
df
df.plot(kind='bar', ylim=(0.9,1.0), fi... | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Looks like ensemble classifiers are not doing as good as expected. Stemmer It is said that stemming short messages does no goot or even harm predictions. Let's try this out. Define our stemmer function | def stemmer (text):
text = text.split()
words = ""
for i in text:
stemmer = SnowballStemmer("english")
words += (stemmer.stem(i))+" "
return words | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Stem, split, fit - repeat... Predict! | text_feat = text_feat.apply(stemmer)
features = vectorizer.fit_transform(text_feat)
features_train, features_test, labels_train, labels_test = train_test_split(features, sms['label'], test_size=0.3, random_state=111)
pred_scores = []
for k,v in clfs.items():
train_classifier(v, features_train, labels_train)
pre... | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
Looks like mostly the same . Ensemble classifiers doing a little bit better, NB still got the lead. What have we forgotten? Message length! Let's append our message length feature to the matrix we fit into our classifiers | lf = sms['length'].as_matrix()
newfeat = np.hstack((features.todense(),lf[:, None]))
features_train, features_test, labels_train, labels_test = train_test_split(newfeat, sms['label'], test_size=0.3, random_state=111)
pred_scores = []
for k,v in clfs.items():
train_classifier(v, features_train, labels_train)
pre... | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
This time everyone are doing a little bit worse, except for LinearRegression and RandomForest. But the winner is still MultinominalNaiveBayes. Voting classifier We are using ensemble algorithms here, but what about ensemble of ensembles? Will it beat NB? | from sklearn.ensemble import VotingClassifier
eclf = VotingClassifier(estimators=[('BgC', bc), ('ETC', etc), ('RF', rfc), ('Ada', abc)], voting='soft')
eclf.fit(features_train,labels_train)
pred = eclf.predict(features_test)
print(accuracy_score(labels_test,pred)) | _____no_output_____ | MIT | sms-spam-detection-with-various-classifiers.ipynb | pruthiviraj71/Spam-and-Fraudulent-Activites-Detection |
SimFin Test All DatasetsThis Notebook performs automated testing of all the bulk datasets from SimFin. The datasets are first downloaded from the SimFin server and then various tests are performed on the data. An exception is raised if any problems are found.This Notebook can be run as usual if you have `simfin` insta... | # Set this to 0 to force a new download of all datasets.
refresh_days = 30 | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Imports | import pandas as pd
import numpy as np
import warnings
import sys
import os
from IPython.display import display
import simfin as sf
from simfin.names import *
from simfin.datasets import * | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Are We Running Pytest? | # Boolean whether this is being run under pytest.
# This is useful when printing examples of errors
# if they take a long time to compute, because it
# is not necessary when running pytest.
running_pytest = ('PYTEST_CURRENT_TEST' in os.environ) | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Configure SimFin | sf.set_data_dir('~/simfin_data/')
sf.load_api_key(path='~/simfin_api_key.txt', default_key='free') | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Load All Datasets | %%time
data = AllDatasets(refresh_days=refresh_days)
# Example for annual Income Statements.
data.get(dataset='income', variant='annual', market='us').head() | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Lists of DatasetsThese are in addition to the lists of datasets from `datasets.py`. | # Datasets that have a column named TICKER.
# Some tests are probably only necessary for 'companies'
# but we might as well test all datasets that use tickers.
datasets_tickers = ['companies'] + datasets_fundamental() + datasets_shareprices() | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Function for Testing Datasets | def test_datasets(test_name, datasets=None, variants=None,
markets=None,
test_func=None,
test_func_rows=None,
test_func_groups=None,
group_index=SIMFIN_ID,
process_df_none=False, raise_exception=True):
"""
... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Function for Getting Rows with ProblemsWhen a test has found problems in a dataset, it does not show which specific rows have the problem. You can get all the problematic rows using this function: | def get_problem_rows(df, test_func_rows):
"""
Perform the given test on all rows of the given DataFrame
and return a DataFrame with only the problematic rows.
:param df:
Pandas DataFrame.
:param test_func_rows:
Function used for testing each row. This takes
a Pandas Dat... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Function for Getting Rows with Missing Data | def get_missing_data_rows(df, column):
"""
Return the rows of `df` where the data for the given
column is missing i.e. it is either NaN, None, or Null.
:param df:
Pandas DataFrame.
:param column:
Name of the column.
:return:
Pandas Series with the rows where th... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Function for Getting Problematic Groups | def get_problem_groups(df, test_func_groups, group_index):
"""
Perform the given test on the given DataFrame grouped by
the given index, and return a DataFrame with only the
problematic groups.
This is used to perform tests on a DataFrame on a per-group
basis, e.g. per-stock or per-company,... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Function for Testing Equality with ToleranceThis function is useful when comparing floating point numbers, or when comparing accounting numbers that are supposed to have a strict relationship (e.g. Assets = Liabilities + Equity) but we might tolerate a small degree of error in the data e.g. 1%. | def isclose(x, y, tolerance=0.01):
"""
Compare whether x and y are approximately equal within
the given tolerance, which is a ratio so tolerance=0.01
means that we tolerate max 1% difference between x and y.
This is similar to numpy.isclose() but is a more efficient
implementation for Panda... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Tests Dataset could not be loaded | test_name = "Dataset could not be loaded"
test_func = lambda df: df is None
test_datasets(datasets=datasets_all(),
test_name=test_name, test_func=test_func,
process_df_none=True) | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Dataset is empty | test_name = "Dataset is empty"
test_func = lambda df: len(df) == 0
# Test for all markets. This only raises a warning,
# because some markets do have some of their datasets empty.
test_datasets(datasets=datasets_all(),
test_name=test_name, test_func=test_func,
raise_exception=False)
# Test ... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Shares Basic is None or <= 0 | test_name = "SHARES_BASIC is None or <= 0"
test_func_rows = lambda df: (df[SHARES_BASIC] is None or
df[SHARES_BASIC] <= 0)
test_datasets(datasets=datasets_fundamental(),
test_name=test_name, test_func_rows=test_func_rows)
# Show the problematic rows for a dataset.
df = data.ge... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Shares Diluted is None or <= 0 | test_name = "SHARES_DILUTED is None or <= 0"
test_func_rows = lambda df: (df[SHARES_DILUTED] is None or
df[SHARES_DILUTED] <= 0)
test_datasets(datasets=datasets_fundamental(),
test_name=test_name, test_func_rows=test_func_rows)
# Show the problematic rows for a dataset.
df = d... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Shares Basic or Diluted looks strange | # List of SimFin-Id's to ignore in this test.
# Use this list when a company's share-counts look strange,
# but after manual inspection of the financial reports, the
# share-counts are actually correct.
ignore_simfin_ids = \
[ 53151, 61372, 82753, 99062, 148380, 166965, 258731, 378110,
498391, 520475, 54342... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Share-Prices are Zero or Negative | test_name = "Share-prices are zero"
def test_func_rows(df):
return (df[OPEN] <= 0.0) & (df[LOW] <= 0.0) & \
(df[HIGH] <= 0.0) & (df[CLOSE] <= 0.0) & \
(df[VOLUME] <= 0.0)
test_datasets(datasets=['shareprices'],
test_name=test_name, test_func_rows=test_func_rows)
# Show the probl... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Revenue is negative | test_name = "REVENUE < 0"
test_func_rows = lambda df: (df[REVENUE] < 0)
# It is possible that Revenue is negative for banks and
# insurance companies, so we only test it for "normal" companies
# in the 'income' dataset.
test_datasets(datasets=['income'],
test_name=test_name, test_func_rows=test_func_rows... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Assets != Liabilities + Equity (Exact Comparison)This only generates a warning, because sometimes there are tiny rounding errors. | test_name = "Assets != Liabilities + Equity (Exact Comparison)"
test_func_rows = lambda df: (df[TOTAL_ASSETS] != df[TOTAL_LIABILITIES] + df[TOTAL_EQUITY])
test_datasets(datasets=datasets_balance(),
test_name=test_name, test_func_rows=test_func_rows,
raise_exception=False)
# Get the problemat... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Assets != Liabilities + Equity (1% Tolerance)The above test used exact comparison. We now allow for 1% error. This raises an exception. | def test_func_rows(df):
x = df[TOTAL_ASSETS]
y = df[TOTAL_LIABILITIES] + df[TOTAL_EQUITY]
# Compare x and y within 1% tolerance. Note the resulting
# boolean array is negated because we want to indicate
# which rows are problematic so x and y are not close.
return ~isclose(x=x, y=y, toleran... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Dates are invalid (Fundamentals) | # Lambda function for converting strings to dates. Format: YYYY-MM-DD
# This will raise an exception if invalid dates are encountered.
date_parser = lambda column: pd.to_datetime(column, yearfirst=True, dayfirst=False)
# Test function for the entire DataFrame.
# This cannot show which individual rows have problems.
def... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Dates are invalid (Share-Prices) | # Test function for the entire DataFrame.
# This cannot show which individual rows have problems.
def test_func(df):
result1 = date_parser(df[DATE])
# We only get to this point if date_parser() does not
# raise any exceptions, in which case we assume the
# data did not have any problems.
return... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Duplicate Tickers | def get_duplicate_tickers(df):
"""
Return the rows of `df` where multiple SIMFIN_ID
have the same TICKER.
:param df: Pandas DataFrame with TICKER column.
:return: Pandas DataFrame.
"""
# Remove duplicate rows of [TICKER, SIMFIN_ID] pairs.
# For the 'companies' dataset this is not n... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Missing Tickers | # Test-function whether a DataFrame has missing tickers.
test_func = lambda df: (len(get_missing_data_rows(df=df, column=TICKER)) > 0)
test_name = "Missing Tickers"
test_datasets(datasets=datasets_tickers,
test_name=test_name, test_func=test_func)
# Show missing tickers in the 'companies' dataset.
df = da... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Missing Company Names | # Test-function whether a DataFrame has missing company names.
test_func = lambda df: (len(get_missing_data_rows(df=df, column=COMPANY_NAME)) > 0)
test_name = "Missing Company Name"
test_datasets(datasets=['companies'],
test_name=test_name, test_func=test_func)
# Show missing company names in the 'compani... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Missing Annual Reports | def missing_annual_reports(df):
"""
Return a list of the SIMFIN_ID's from the given DataFrame
that have missing annual reports.
:param df:
Pandas DataFrame with a dataset e.g. 'income-annual'.
It must have columns SIMFIN_ID and FISCAL_YEAR.
:return:
List of integers wit... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Missing Quarterly Reports | def missing_quarterly_reports(df):
"""
Return a list of the SIMFIN_ID's from the given DataFrame
that have missing quarterly or ttm reports.
:param df:
Pandas DataFrame with a dataset e.g. 'income-annual'.
It must have columns SIMFIN_ID, FISCAL_YEAR, FISCAL_PERIOD.
:return:
... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Missing TTM ReportsTrailing-Twelve-Months (TTM) data is also quarterly so we can use the same helper-functions from above. | test_name = "Missing ttm reports"
test_func = lambda df: len(missing_quarterly_reports(df=df)) > 0
test_datasets(datasets=datasets_fundamental(),
variants=['ttm'],
test_name=test_name, test_func=test_func)
# Get list of SIMFIN_ID's that have missing reports for a dataset.
if not running_pyte... | _____no_output_____ | MIT | tests/test_bulk_data.ipynb | Carmelsalad/hackathon |
Importing required stuff | import time
import math
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from datetime import timedelta
import scipy.misc
import glob
import sys
%matplotlib inline | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Helper files to load data | # Helper functions, DO NOT modify this
def get_img_array(path):
"""
Given path of image, returns it's numpy array
"""
return scipy.misc.imread(path)
def get_files(folder):
"""
Given path to folder, returns list of files in it
"""
filenames = [file for file in glob.glob(folder+'*/*')]
... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Load test data from using the helper code from HW1 | # Load the data
data_root_path = 'cifar10-hw2/'
X_train, Y_train = get_train_data(data_root_path) # this may take a few minutes
X_test_format = get_images(data_root_path + 'test')
X_test_format = X_test_format.T
#print('Data loading done')
X_train = X_train.T
Y_train = Y_train.T | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Load all the data | def unpickle(file):
import pickle
with open(file, 'rb') as fo:
data_dict = pickle.load(fo, encoding='bytes')
return data_dict
path = 'cifar-10-batches-py'
file = []
file.append('data_batch_1')
file.append('data_batch_2')
file.append('data_batch_3')
file.append('data_batch_4')
file.append('data_batc... | b'training batch 1 of 5'
b'training batch 2 of 5'
b'training batch 3 of 5'
b'training batch 4 of 5'
b'training batch 5 of 5'
b'testing batch 1 of 1'
(50000, 3072) (50000,) (10000, 3072) (10000,)
| MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Defining Hyperparameters | # Convolutional Layer 1.
filter_size1 = 3
num_filters1 = 64
# Convolutional Layer 2.
filter_size2 = 3
num_filters2 = 64
# Fully-connected layer.
fc_1 = 256 # Number of neurons in fully-connected layer.
fc_2 = 128 # Number of neurons in fc layer
# Number of color channels for the imag... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Helper-function for plotting imagesFunction used to plot 9 images in a 3x3 grid (or fewer, depending on how many images are passed), and writing the true and predicted classes below each image. | def plot_images(images, cls_true, cls_pred=None):
if len(images) == 0:
print("no images to show")
return
else:
random_indices = random.sample(range(len(images)), min(len(images), 9))
print(images.shape)
images, cls_true = zip(*[(images[i], cls_true[i]) for i in... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Plot a few images to see if data is correct | # Plot the images and labels using our helper-function above.
plot_images(X_train, Y_train) | (50000, 3072)
| MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Normalize | mean = np.mean(X_train, axis = 0)
stdDev = np.std(X_train, axis = 0)
X_train -= mean
X_train /= stdDev
X_test -= mean
X_test /= stdDev
X_test_format -= mean
X_test_format /= stdDev | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Tensorflow graph Regularizer | regularizer = tf.contrib.layers.l2_regularizer(scale=0.1) | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Weights and Bias | def new_weights(shape):
return tf.get_variable(name='weights',shape=shape,regularizer=regularizer)
def new_biases(length):
return tf.Variable(tf.constant(0.05, shape=[length])) | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Batch Norm | def batch_norm(x, n_out, phase_train):
"""
Batch normalization on convolutional maps.
Ref.: http://stackoverflow.com/questions/33949786/how-could-i-use-batch-normalization-in-tensorflow
Args:
x: Tensor, 4D BHWD input maps
n_out: integer, depth of input maps
phase_... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Helper function for summaries: | def variable_summaries(var):
"""Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
with tf.name_scope('summaries'):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - ... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Convolutional Layer | def new_conv_layer(input, # The previous layer.
num_input_channels, # Num. channels in prev. layer.
filter_size, # Width and height of each filter.
num_filters, # Number of filters.
use_pooling=True, normalize=True, p... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Flatten Layer | def flatten_layer(layer):
# Get the shape of the input layer.
layer_shape = layer.get_shape()
# The shape of the input layer is assumed to be:
# layer_shape == [num_images, img_height, img_width, num_channels]
# The number of features is: img_height * img_width * num_channels
# We can use a fu... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
FC Layer | def new_fc_layer(input, # The previous layer.
num_inputs, # Num. inputs from prev. layer.
num_outputs, # Num. outputs.
use_relu=True): # Use Rectified Linear Unit (ReLU)?
# Create new weights and biases.
with tf.variable_scope('weights'):
... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Placeholder variables | x = tf.placeholder(tf.float32, shape=[None, img_size_flat], name='x')
x_image = tf.reshape(x, [-1, img_size, img_size, num_channels])
y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true')
y_true_cls = tf.argmax(y_true, axis=1)
phase = tf.placeholder(tf.int32, name='phase')
keep_prob = tf.pl... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Convolutional Layers | with tf.variable_scope('Layer-1'):
layer_conv1, weights_conv1 = \
new_conv_layer(input=x_image,
num_input_channels=num_channels,
filter_size=filter_size1,
num_filters=num_filters1,
use_pooling=True, phase=phase, batc... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Flatten Layer | with tf.variable_scope('Flatten'):
layer_flat, num_features = flatten_layer(layer_conv2)
print(layer_flat,num_features) | Tensor("Flatten/Reshape:0", shape=(?, 16384), dtype=float32) 16384
| MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
FC Layers | with tf.variable_scope('Fully-Connected-1'):
layer_fc1, weights_fc1 = new_fc_layer(input=layer_flat,
num_inputs=num_features,
num_outputs=fc_1,
use_relu=True)
with tf.variable_scope('Fully-Connected-2'):
layer_fc2, weigh... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Softmax and argmax functions | with tf.variable_scope('Softmax'):
y_pred = tf.nn.softmax(layer_fc3)
y_pred_cls = tf.argmax(y_pred, axis=1) | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Cost-Function: | with tf.variable_scope('cross_entropy_loss'):
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=layer_fc3,
labels=y_true)
loss = tf.reduce_mean(cross_entropy)
tf.summary.scalar('cross_entropy', loss)
#with tf.variable_scope('Regu... | _____no_output_____ | MIT | CNN-Keras-Tensorflow/q1-ck2840.ipynb | Chandra-S-Narain-Kappera/Image-Classification |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.