{"id":14958837,"url":"https://github.com/perseus784/bvs","last_synced_at":"2025-05-02T13:30:23.766Z","repository":{"id":132218873,"uuid":"100732951","full_name":"perseus784/BvS","owner":"perseus784","description":"An Image classifier to identify whether the given image is Batman or Superman using a CNN with high accuracy. (From getting images from google to saving our trained model for reuse.)","archived":false,"fork":false,"pushed_at":"2019-12-08T23:08:04.000Z","size":25378,"stargazers_count":51,"open_issues_count":0,"forks_count":21,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-25T14:55:43.947Z","etag":null,"topics":["batman","bvs","cnn-architecture","cnn-classifier","cnn-model","cnn-tensorflow","convolutional-neural-networks","deeplearning","dnn","gradient-descent","image-classification","image-classifier","neural-networks","python","tensorflow","tensorflow-models","tensorflow-tutorials"],"latest_commit_sha":null,"homepage":"https://medium.com/@ipaar3/how-i-built-a-convolutional-image-classifier-using-tensorflow-from-scratch-f852c34e1c95","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/perseus784.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-08-18T16:55:04.000Z","updated_at":"2024-10-31T03:01:05.000Z","dependencies_parsed_at":null,"dependency_job_id":"5aaaef62-296b-4ca6-a746-ae137769a532","html_url":"https://github.com/perseus784/BvS","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/perseus784%2FBvS","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/perseus784%2FBvS/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/perseus784%2FBvS/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/perseus784%2FBvS/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/perseus784","download_url":"https://codeload.github.com/perseus784/BvS/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252045982,"owners_count":21685931,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["batman","bvs","cnn-architecture","cnn-classifier","cnn-model","cnn-tensorflow","convolutional-neural-networks","deeplearning","dnn","gradient-descent","image-classification","image-classifier","neural-networks","python","tensorflow","tensorflow-models","tensorflow-tutorials"],"created_at":"2024-09-24T13:18:22.855Z","updated_at":"2025-05-02T13:30:21.825Z","avatar_url":"https://github.com/perseus784.png","language":"Python","readme":"# BvS\n**Dawn of AI**  \nAn Image classifier to identify whether the given image is Batman or Superman using a CNN with high accuracy. \n(Without using Dogs Vs Cats, From getting images from google to saving our trained model for reuse.)  \n\n# What are we gonna do:  \n* We will build a 3 layered **Community Standard CNN Image classifier** to classify whether the given image is a image of Batman or Superman.\n* Learn how to build a model from scratch in Tensoflow which is accurate.\n* How to train and test it.\n* How to save and use it further.  \n\n**Setup:**\n* Python 3.5\n* Tensorflow 1.5.0\n* CUDA 9.0\n* CUDANN 7.0.5\n\nIndepth explanation of each section:  \n[Medium post with detailed step by step explanation](https://medium.com/@ipaar3/how-i-built-a-convolutional-image-classifier-using-tensorflow-from-scratch-f852c34e1c95) for deeper understanding of CNNs and architecture of the network.\n\n# Data:\n\n### Collect data:\n* [Google Images Downloader](https://github.com/hardikvasa/google-images-download).It's fast, easy, simple and efficient.\n* I've collected 300 images each for Supes and Batsy respectively, But more data is highly preferable. Try to collect as much clean data as possible.  \n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/image_collection.png\" width=\"800\" height=\"400\"\u003e\n\u003c/p\u003e  \n\n### Augmentation:\n* 300 is not a number at all in Deep learning. So, we must Augment the images to get more images from whatever we collected.  \n* You can use the following to do it easily, [Augmentor](https://github.com/mdbloice/Augmentor).  \n* [This](https://github.com/perseus784/BvS/blob/master/augment.py) is the code I've used for augmenting my images.   \n* Same image, augmented using various transformations. I had 3500 images each after augmentation for each class.  \n*Careful: While Augmenting, be careful about what kind of transformation you use. You can mirror flip a Bat Logo but cannot make it upside down.*  \n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/augment.png\" width=\"800\" height=\"400\"\u003e\n\u003c/p\u003e \n\n### Standardize:\n* After Augmentation, Make a folder named rawdata in the current working directory.\n* Create folders with their respective class names and put all the images in their respective folders.\n* Run [this](https://github.com/perseus784/BvS/blob/master/preprocessing.py) file in the same directory as rawdata.\n* This will resize all the images to a standard resolution and same format and put it in a new folder named data.  \n**Note:** As I embedded it in *trainer.py*, it is unnecessary to run it explicitly.  \n**Update** :You can get the **data** folder itself from [here(50mb)](https://drive.google.com/open?id=1GUPBBdLlqStnxjhISkxT1qOf1XPnmRcF). Just download and extract!.\n\n\u003cp align=\"left\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/convert.png\" width=\"400\" height=\"200\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/file_structure.png\" width=\"300\" height=\"400\"\u003e\n\u003c/p\u003e  \n\n\n# Architecture:\n### A Simple Architecture: \n\u003e For detailed explanation of Architecture and CNNs please read the medium [post](https://medium.com/@ipaar3/how-i-built-a-convolutional-image-classifier-using-tensorflow-from-scratch-f852c34e1c95).  \nI've explained CNNs in depth over there, I highly recommend reading it.  \n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/convolution_nn_medium_post.png\" width=\"800\" height=\"400\"\u003e\n\u003c/p\u003e  \n\nIn code:\n\n          #level 1 convolution\n          network=model.conv_layer(images_ph,5,3,16,1)\n          network=model.pooling_layer(network,5,2)\n          network=model.activation_layer(network)\n\n          #level 2 convolution\n          network=model.conv_layer(network,4,16,32,1)\n          network=model.pooling_layer(network,4,2)\n          network=model.activation_layer(network)\n\n          #level 3 convolution\n          network=model.conv_layer(network,3,32,64,1)\n          network=model.pooling_layer(network,3,2)\n          network=model.activation_layer(network)\n\n          #flattening layer\n          network,features=model.flattening_layer(network)\n\n          #fully connected layer\n          network=model.fully_connected_layer(network,features,1024)\n          network=model.activation_layer(network)\n          \n          #output layer      \n          network=model.fully_connected_layer(network,1024,no_of_classes)\n\n### A Brief Architecture:\nWith dimentional informations:  \n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/brief_architecture.png\" width=\"800\" height=\"400\"\u003e\n\u003c/p\u003e\n\n# Training:\n* Clone this repo.\n* Do the Augmentation.\n* Put the images in thier respective folders in *rawdata*. \n  \n       rawdata/batman: 3810 images\n       rawdata/superman: 3810 images\n\n**Update** :You can get the **data** folder itself from [here(50mb)](https://drive.google.com/open?id=1GUPBBdLlqStnxjhISkxT1qOf1XPnmRcF). Just download and extract!.  \n\nOur file structure should look like this,  \n\u003cp align=\"left\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/file_placement.png\" width=\"500\" height=\"400\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/fstr.png\" width=\"300\" height=\"400\"\u003e\n\u003c/p\u003e  \n\n***data*** folder will be generated automatically by trainer.py from raw_data if *data* folder does not exist. \n\n* **Configuration:**  If you want to edit something, you can do it using [this](https://github.com/perseus784/BvS/blob/master/config.py) file. \n\n          raw_data='rawdata'\n          data_path='data'\n          height=100\n          width=100\n          all_classes = os.listdir(data_path)\n          number_of_classes = len(all_classes)\n          color_channels=3\n          epochs=300\n          batch_size=10\n          model_save_name='checkpoints\\\\'\n\n\n* **Run** [trainer.py](https://github.com/perseus784/BvS/blob/master/trainer.py).\n* Wait for few hours.\n* For me it took **8 hrs for 300 epochs**. I did it in my laptop which has **i5 processors, 8 Gigabytes of RAM, Nvidia geforce 930M 2GB setup**. You can end the process anytime if saturated, as the model will be saved frequently.  \n  \n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/train_info.png\" width=\"800\" height=\"400\"\u003e\n\u003c/p\u003e  \n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/training_loss.png\" width=\"800\" height=\"400\"\u003e\n\u003c/p\u003e  \n\n### Saving our model:  \nOnce training is over, we can see a folder named checkpoints is created which contains our model for which we trained. These two simple lines does that for us in tensorflow:  \n\n          saver = tf.train.Saver(max_to_keep=4)\n          saver.save(session, model_save_name)  \n          \nYou can get my pretrained model [here.](https://drive.google.com/file/d/1l9_ByLxtGqRMJxWvNr9Ls7XDFRxsqywN/view?usp=sharing)  \n\nWe have three files in our checkpoints folder,\n* .meta file - it has your graph structure saved.\n* .index - it identifies the respective checkpoint file.\n* .data - it stores the values of all the variables.\n\nHow to use it?\nTensorflow is so well built that, it does all the heavy lifting for us. We just have to write four simple lines to load and infer our model.  \n\n          #Create a saver object to load the model\n          saver = tf.train.import_meta_graph\n                                          (os.path.join(model_folder,'.meta'))\n          #restore the model from our checkpoints folder\n          saver.restore(session,os.path.join('checkpoints','.\\\\'))\n          #Create graph object for getting the same network architecture\n          graph = tf.get_default_graph()\n          #Get the last layer of the network by it's name which includes all the previous layers too\n          network = graph.get_tensor_by_name(\"add_4:0\")\nYeah, simple. Now that we got our network as well as the tuned values, we have to pass an image to it using the same placeholders(Image, labels).  \n\n    im_ph= graph.get_tensor_by_name(\"Placeholder:0\")\n    label_ph = graph.get_tensor_by_name(\"Placeholder_1:0\")\n    \nIf you run it now, you can see the output as [1234,-4322] like that. While this is right as the maximum value index represents the class, this is not as convenient as representing it in 1 and 0. Like this [1,0]. For that we should include a line of code before running it,   \n\n    network=tf.nn.sigmoid(network)\n    \nWhile we could have done this in our training architecture itself and nothing would have changed, I want to show you that, you can add layers to our model even now, even in prediction stage. Flexibility.  \n\n# Inference time:  \n\u003e Your training is nothing, If you don't have the will to act - Ra's Al Ghul.  \n\nTo run a simple prediction,\n* Edit the image name in [predict.py](https://github.com/perseus784/BvS/blob/master/predict.py).\n* Download the model files and extract in the same folder.\n* Run [predict.py](https://github.com/perseus784/BvS/blob/master/predict.py).  \n\n          image='sup.jpg'\n          img=cv2.imread(image)\n          session=tf.Session()\n          img=cv2.resize(img,(100,100))\n          img=img.reshape(1,100,100,3)\n          labels = np.zeros((1, 2))\n          # Creating the feed_dict that is required to be feed the io:\n          feed_dict_testing = {im_ph: img, label_ph: labels}\n          result=session.run(network, feed_dict=feed_dict_testing)\n          print(result)  \n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/output_screeenshot.png\" width=\"800\" height=\"300\"\u003e\n\u003c/p\u003e   \n\nYou can see the results as [1,0]{Batman}, [0,1]{Superman} corresponding to the index.  \n*Please note that this is not one-hot encoding.*  \n\n# Accuracy:\nIt is actually pretty good. It is almost right all the time. I even gave it an image with both Batman and Superman, it actually gave me values which are almost of same magnitude(after removing the sigmoid layer that we added just before).  \n\n*Comment out **network=tf.nn.sigmoid(network)** in predict.py to see the real magnitudes as this will only give squashed outputs.*  \n\nFrom here on you can do whatever you want with those values.  \nInitially loading the model will take some time(70 seconds) but once the model is loaded, you can put a for loop or something to throw in images and *get output in a second or two!*\n\n# Tensorboard:\nI have added some additional lines in the training code for tensorboard options. Using tensorboard we can track progress of our training even while training and after. You can also see your network structure and all the other components inside it.*It is very useful for visualizing the things happening.*\nTo start it, just go to the directory and open command line,  \n\n    tensorboard --logdir checkpoints\n    \nYou should see the following,\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/Inkedtensorboard_start_LI.jpg\" width=\"800\" height=\"300\"\u003e\n\u003c/p\u003e\n\nNow type the same address in in your browser. Your tensorboard is now started. Play with it.\n\n# Graph Structure Visualization:  \nYeah, you can see our entire model with dimensions in each layer and operations here!\n\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/tensorboard_graph.png\" width=\"800\" height=\"400\"\u003e\n\u003c/p\u003e\n\n# Future Implementations:\nWhile this works for Binary classification, it will also work for Multiclass classification but not as well. We might need to alter architecture and build a larger model depending on the number of classes we want.\n\n\u003e So, that's how Batman wins!\n\u003cp align=\"center\"\u003e\n\u003cimg src=\"https://github.com/perseus784/BvS/blob/master/media/lego-batman-movie-tuxedo.jpg\" alt=\"Batwin\" width=\"800\" height=\"400\"\u003e\n\u003c/p\u003e  \n\nPlease Star the repo if you like it.  \nFor any suggestions, doubts, clarifications please mail: ipaar3@gmail.com or raise an issue!.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fperseus784%2Fbvs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fperseus784%2Fbvs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fperseus784%2Fbvs/lists"}