lukas / ml-class

Machine learning lessons and teaching projects designed for engineers
https://www.youtube.com/channel/UCBp3w4DCEC64FZr4k9ROxig
GNU General Public License v2.0
2.34k stars 1.17k forks source link

request for guidance #47

Closed UNIcodeX closed 4 years ago

UNIcodeX commented 4 years ago

I've run the training with your code on the mnist dataset and am trying to figure out how to check / predict a value from an image of a number six I created. I'm sure there's a whole lot wrong with this code. Could you help me understand this a bit more? I'm new to ML.

I had saved the h5 file using model.save at the end of training. but seems I have to load it using load_weights and not just load. I'd like to load everything including the ??model state??

please advise.

import random
import numpy as np
import keras
import sys
# import wandb
# from wandb.keras import WandbCallback
from keras.models import Sequential, Model
from keras.layers import Flatten, Dense, Concatenate, Dot, Lambda, Input
from keras.datasets import mnist
from keras.optimizers import Adam
import matplotlib.pyplot as plt
from keras import backend as K
import scipy
import cv2

def debug(*args):
  for arg in args:
    print(arg)
  sys.exit()

def euclidean_distance(vects):
  x, y = vects
  sum_square = K.sum(K.square(x - y), axis=1, keepdims=True)
  return K.sqrt(K.maximum(sum_square, K.epsilon()))

# 3 channel images of arbitrary shape
inp = Input(shape=(3, None, None))
try:
  out = Lambda(lambda image: K.resize_images(image, (28, 28), "channels_first"))(inp)
except :
  # if you have older version of tensorflow
  out = Lambda(lambda image: K.resize_images(image, 28, 28, "channels_first"))(inp)

model = Model(input=inp, output=out)

input = Input((28,28))
x = Flatten()(input)
x = Dense(128, activation='relu')(x)
dense = Model(input, x)

input1 = Input((28,28))
input2 = Input((28,28))

dense1 = dense(input1)
dense2 = dense(input2)

merge_layer = Lambda(euclidean_distance)([dense1,dense2])
dense_layer = Dense(1, activation="sigmoid")(merge_layer)
model = Model(inputs=[input1, input2], outputs=dense_layer)

model.load_weights("mnist.h5")

model.summary()

X = cv2.imread('six.png')
X = cv2.resize(X, (28, 28))
X.shape = (3, 28, 28)

out = model.predict(X[np.newaxis, ...])

fig, Axes = plt.subplots(nrows=1, ncols=2)
Axes[0].imshow(X)
Axes[1].imshow(np.int8(out[0,...]))

plt.show()
charlesfrye commented 4 years ago

Hey there! We use the Issues on this repo to track bugs in the class code itself. If you want to get some help with ML code you're writing, I recommend you ask it on our Slack forum for ML engineers and enthusiasts: bit.ly/slack-forum.