TrainOnlyDense
In [1]:
import cv2
import numpy as np
import matplotlib.pyplot as plt
In [2]:
from kerasy.layers.convolutional import Conv2D
from kerasy.layers.pool import MaxPooling2D
from kerasy.layers.core import Input, Dense, Flatten
from kerasy.engine.sequential import Sequential
In [3]:
cv_path = "/Users/iwasakishuto/Github/portfolio/Kerasy/doc/theme/img/MNIST-sample/0.png"
In [4]:
image = np.expand_dims(cv2.imread(cv_path, 0), axis=2)/255
In [5]:
plt.imshow(cv2.cvtColor(cv2.imread(cv_path), cv2.COLOR_BGR2RGB))
plt.show()
In [6]:
model = Sequential()
model.add(Input(input_shape=(28,28,1)))
model.add(Conv2D(filters=32, kernel_size=(3, 3), activation='linear', padding="same"))
model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='linear', padding="same"))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='tanh'))
model.add(Dense(10, activation='softmax'))
In [7]:
model.compile(optimizer='sgd', loss="categorical_crossentropy")
In [8]:
for layer in model.layers:
print(f"== {layer.name} ==")
print(f"output shape: {layer.output_shape}")
print(f"kernel shape: {layer._losses.get('kernel', np.zeros(shape=())).shape}")
print(f"bias shape : {layer._losses.get('bias', np.zeros(shape=())).shape}")
In [9]:
#=== Train Only Dense Layer ===
model.layers[1].trainable = False
model.layers[2].trainable = False
In [10]:
# #=== Train Only Convolutional Layer ===
# model.layers[-1].trainable = False
# model.layers[-2].trainable = False
In [11]:
x_train = np.expand_dims(image, axis=0)
In [12]:
original_pred = model.predict(x_train)
print(f"original prediction: {np.argmax(original_pred)}\n{original_pred}")
In [13]:
ans_label = np.argmin(original_pred)
print(f"ans_label: {ans_label}")
In [14]:
y_true = np.zeros(shape=(10,))
y_true[ans_label] = 1
y_true = y_true.reshape(1,-1)
In [15]:
model.fit(x=x_train, y=y_true, epochs=30)
In [16]:
final_pred = model.predict(x_train)
print(f" Answer: {ans_label}")
print(f" original prediction: {np.argmax(original_pred)}\n{original_pred}")
print(f" final prediction: {np.argmax(final_pred)}\n{final_pred}")
print(f" Difference:\n{np.where((final_pred-original_pred)>0, '+', '-')}")
In [17]:
from Functions.TexWriter import CNNbackprop2tex
In [18]:
kh, kw = (3,3)
sh, sw = (1,1)
IH, IW = (5,5)
OH, OW = (3,3)
In [19]:
CNNbackprop2tex(IH,IW,OH,OW,kh,kw,sh,sw, path="sample.tex")
! platex /Users/iwasakishuto/Github/portfolio/Kerasy/pelican/pelican-src/DeepLearning/sample.tex
! dvipdfmx /Users/iwasakishuto/Github/portfolio/Kerasy/pelican/pelican-src/DeepLearning/sample.dvi