# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import logging
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.ERROR)

import keras
from keras import models
from keras import layers
from keras import optimizers
from keras.models import Sequential, Model
from keras.layers import Conv2D, MaxPool2D, Flatten, Dense, Activation, Input
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix
import time
# -

# ## Creating a Keras Model

# +
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(MaxPool2D())
model.add(Conv2D(16, (3, 3), activation='relu'))
model.add(MaxPool2D())
model.add(Flatten())
model.add(Dense(10, activation='softmax'))

model.summary()
# -

# ## 2'nd way to create a Keras model

# +
input_layer = Input(shape=(32, 32, 3))
conv2d_1 = Conv2D(32, (3, 3), activation='relu')(input_layer)
maxpool_1 = MaxPool2D()(conv2d_1)
conv2d_2 = Conv2D(16, (3, 3), activation='relu')(maxpool_1)
maxpool_2 = MaxPool2D()(conv2d_2)
flatten = Flatten()(maxpool_2)
dense = Dense(10, activation='softmax')(flatten)

model = Model(inputs=input_layer, outputs=dense)
model.summary()
# -

# ## Creating a toy data

data = []
for i in range(1000):
    x1 = np.random.randint(low=1, high=200)
    x2 = np.random.randint(low=1, high=200)
    if x1 < x2:
        data.append([x1,x2,1])
    else:
        data.append([x1,x2,0])

data_f = pd.DataFrame(data, columns = ['x1', 'x2', 'y'])
data_f.head()

plt.plot(data_f[data_f.y==0].x1, data_f[data_f.y==0].x2, 'o')
plt.plot(data_f[data_f.y==1].x1, data_f[data_f.y==1].x2, 'x')

M = data_f.values
X = M[:,:-1]
y = M[:,-1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

X_train.shape

# ## Creating the model

# +
# Network Architecture
model = models.Sequential()

# Layer id the building block for Neural Networks
model.add(layers.Dense(2, activation='sigmoid', input_shape = (2,)))
model.add(layers.Dense(8, activation='sigmoid'))
model.add(layers.Dense(16,activation='sigmoid'))
model.add(layers.Dense(8, activation='sigmoid'))
model.add(layers.Dense(2, activation='sigmoid'))
model.add(layers.Dense(1, activation='sigmoid'))

# Compilation Step
model.compile(optimizer=optimizers.RMSprop(lr=0.01),
              loss='binary_crossentropy', 
              metrics=['accuracy'])

model.summary()
# -

X_train

# ## Evaluating model

# %%time
model.fit(X_train, y_train, batch_size=1, epochs=10, verbose = 0)

y_pred = 1 * (model.predict(X_test) > 0.5)
print("Confusion Matrix: \n {}".format(confusion_matrix(y_test, y_pred)))
print('Accuracy on Test Data:{:.3}'.format(accuracy_score(y_test, y_pred)))

51.1/10

StarcoderdataJupyterScriptsDedupFiltered