-
Notifications
You must be signed in to change notification settings - Fork 2
Highway network Predict.py #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Quan030994
wants to merge
4
commits into
main
Choose a base branch
from
highway_networks_data
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Binary file not shown.
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,53 +1,72 @@ | ||
| # TODO 2: | ||
| # TODO 2: | ||
| import os | ||
|
|
||
| os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" | ||
| import tensorflow as tf | ||
|
|
||
| class HighwayMLP(tf.keras.Model): | ||
| """ | ||
| Highway MLP Layer | ||
| """ | ||
| def __init__(self, input_size, t_bias=-2, acti_h = tf.nn.relu, acti_t = tf.nn.tanh): | ||
| super(HighwayMLP, self).__init__() | ||
| self.acti_h = acti_h | ||
| self.acti_t = acti_t | ||
|
|
||
| # TODO | ||
| # Dense H | ||
| self.h = None | ||
|
|
||
| # Dense T | ||
|
|
||
| self.t = None | ||
|
|
||
|
|
||
| pass | ||
|
|
||
| def call(self, x): | ||
| # Do Highway: y = H(x,WH)· T(x,WT) + x · C(x,WC). | ||
|
|
||
| y = None | ||
|
|
||
|
|
||
| class HighwayNetwork(tf.keras.Model): | ||
| """ | ||
| Highway Network with several layers | ||
| """ | ||
| def __init__(self, input_size, output_size): | ||
| super(HighwayNetwork, self).__init__() | ||
| self.mlplayers = [ | ||
| # TO DO | ||
| ] | ||
|
|
||
| # Classification layer | ||
|
|
||
| def call(self, x): | ||
| # Run input on these mlp layers | ||
|
|
||
| # pass output to classification layer | ||
| pass | ||
|
|
||
|
|
||
| model = HighwayNetwork(784, 10) | ||
|
|
||
|
|
||
|
|
||
| from tensorflow import keras | ||
| from tensorflow.keras import layers | ||
| from tensorflow.python.keras import activations | ||
|
|
||
|
|
||
| class HighwayBlock(layers.Layer): | ||
| def __init__(self, units, t_bias, acti_h, acti_t): | ||
| super(HighwayBlock, self).__init__() | ||
| self.units = units | ||
| self.t_bias = t_bias | ||
| self.acti_t = acti_t | ||
| self.acti_h = acti_h | ||
|
|
||
| def build(self, input_shape): | ||
| self.W = self.add_weight( | ||
| name="w", | ||
| shape=(input_shape[-1], self.units), | ||
| initializer="random_normal", | ||
| trainable=True, | ||
| ) | ||
| self.W_T = self.add_weight( | ||
| name="w_T", | ||
| shape=(input_shape[-1], self.units), | ||
| initializer="random_normal", | ||
| trainable=True, | ||
| ) | ||
|
|
||
| self.b = self.add_weight( | ||
| name="b", shape=(self.units,), initializer="random_normal", trainable=True, | ||
| ) | ||
|
|
||
| self.b_T = tf.Variable(tf.constant(self.t_bias, shape=self.units), name='bias', trainable=True) | ||
| # assert self.b_T.shape == (50,), 'b.shape: {}'.format(self.b.shape) | ||
|
|
||
| def call(self, inputs): | ||
| h = self.acti_h(tf.matmul(inputs, self.W) + self.b) | ||
| t = self.acti_t(tf.matmul(inputs, self.W_T) + self.b_T) | ||
| y = tf.add(tf.multiply(h, t), tf.multiply(inputs, (1 - t))) | ||
| return y | ||
|
|
||
|
|
||
| class HighwayNetwork(tf.keras.Model): | ||
| """ | ||
| Highway Network with several layers | ||
| """ | ||
|
|
||
| def __init__(self, t_bias=-9.0, acti_h=tf.nn.relu, acti_t=tf.nn.sigmoid, num_classes=10, num_of_layers=3): | ||
| super(HighwayNetwork, self).__init__() | ||
| self.projection = keras.Sequential([ | ||
| layers.Conv2D(16, 3, padding='same', activation='relu', input_shape=(28, 28, 1)), | ||
| layers.MaxPooling2D(), | ||
| layers.Conv2D(32, 3, padding='same', activation='relu'), | ||
| layers.MaxPooling2D(), | ||
| layers.Conv2D(64, 3, padding='same', activation='relu'), | ||
| layers.MaxPooling2D(), | ||
| layers.Flatten(), | ||
| layers.Dense(50)]) | ||
| self.mlplayers = [HighwayBlock(50, t_bias=t_bias, acti_h=acti_h, acti_t=acti_t) for _ in range(num_of_layers)] | ||
|
|
||
| self.classifier = layers.Dense(num_classes, activation='softmax') | ||
|
|
||
| def call(self, x): | ||
| X = self.projection(x) | ||
| for layer in self.mlplayers: | ||
| X = layer(X) | ||
| y = self.classifier(X) | ||
| return y |
Binary file not shown.
Binary file not shown.
Binary file not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,24 +1,57 @@ | ||
| import os | ||
| import tensorflow as tf | ||
| from model import HighwayNetwork | ||
| from argparse import ArgumentParser | ||
| import os | ||
| import matplotlib.pyplot as plt | ||
| import numpy as np | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| home_dir = os.getcwd() | ||
| parser = ArgumentParser() | ||
| parser.add_argument("--batch-size", default=64, type=int) | ||
| parser.add_argument("--epochs", default=1000, type=int) | ||
| #parser.add_argument("--test-file-path", default='{}/data/test'.format(home_dir), type=str, required=True) | ||
| parser.add_argument("--image-size", default=28, type=int) | ||
| parser.add_argument("--image-index", default=0, type=int) | ||
| parser.add_argument("--model-folder", default='{}/model/highway_network/'.format(home_dir), type=str) | ||
|
|
||
| # FIXME | ||
| args = parser.parse_args() | ||
|
|
||
| # FIXME | ||
| # Project Description | ||
|
|
||
| print('---------------------Welcome to ${name}-------------------') | ||
| print('---------------------Welcome to Highway Network-------------------') | ||
| print('Github: ${accout}') | ||
| print('Email: ${email}') | ||
| print('---------------------------------------------------------------------') | ||
| print('Training ${name} model with hyper-params:') # FIXME | ||
| print('Predict using Highway Network for image') | ||
| print('===========================') | ||
|
|
||
| # FIXME | ||
| # Do Training | ||
| # Loading Model | ||
| highway_network = tf.keras.models.load_model(args.model_folder) | ||
|
|
||
|
|
||
| # Load data mnist | ||
| mnist = tf.keras.datasets.mnist | ||
| (train_images, train_labels), (test_images, test_labels) = mnist.load_data() | ||
|
|
||
| # Load test images from folder | ||
| # image = tf.keras.preprocessing.image.load_img(args.test_file_path, target_size=(args.image_size, args.image_size)) | ||
| # image = tf.image.rgb_to_grayscale( | ||
| # image, name=None | ||
| # ) | ||
| # input_arr = tf.keras.preprocessing.image.img_to_array(image) | ||
| # img = input_arr.reshape(-1,28,28,1).astype("float32") / 255 | ||
|
|
||
| # Normalize data | ||
|
|
||
| # x_train = train_images.reshape(60000, 784).astype("float32") / 255 | ||
| img = test_images.reshape(-1, 28, 28, 1).astype("float32") / 255 | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @Quan030994 dùng tham số |
||
|
|
||
| predictions = highway_network.predict(img) | ||
| print('---------------------Prediction Result: -------------------') | ||
| print('Output Softmax: {}'.format(predictions[args.image_index])) | ||
| print('This image belongs to class: {}'.format(np.argmax(predictions[args.image_index]), axis=1)) | ||
|
|
||
| plt.imshow(img[args.image_index]) | ||
| plt.show() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ủa sao chỗ này nhiều comment thế em nếu không dùng thì remove nhé @Quan030994
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
dạ vâng anh, có gì anh xem giúp em file predict nếu cần sửa thì em sửa lại luôn và push lại ạ.