<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Suraj Kumar on Medium]]></title>
        <description><![CDATA[Stories by Suraj Kumar on Medium]]></description>
        <link>https://medium.com/@surajx42?source=rss-c8aae123e353------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*8fgouvz-4iCWWkmMFA6RKA.jpeg</url>
            <title>Stories by Suraj Kumar on Medium</title>
            <link>https://medium.com/@surajx42?source=rss-c8aae123e353------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:57:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@surajx42/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Fine Tuning Sentence Transformer Vectors without Model Training]]></title>
            <link>https://medium.com/@surajx42/fine-tuning-sentence-transformer-vectors-without-model-training-19fb7061134d?source=rss-c8aae123e353------2</link>
            <guid isPermaLink="false">https://medium.com/p/19fb7061134d</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[sentence-embedding]]></category>
            <category><![CDATA[sentence-transformers]]></category>
            <dc:creator><![CDATA[Suraj Kumar]]></dc:creator>
            <pubDate>Sun, 02 Oct 2022 09:30:22 GMT</pubDate>
            <atom:updated>2022-10-19T17:35:25.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*Uuix1_doHabPkjvvq6ACsg.png" /></figure><p>In this tutorial , We will learn how we can fine tune Sentence Transformer without model training.</p><p><strong>What we are trying to achieve?:</strong></p><ol><li>Modify Existing Embeddings to adapt it for our use case.</li><li>Add new words to the vocabulary</li></ol><p>For this tutorial we are going to use “<a href="https://huggingface.co/sentence-transformers/paraphrase-MiniLM-L6-v2">sentence-transformers/paraphrase-MiniLM-L6-v2</a>” model</p><p><strong>What are sentence-Transformers?</strong></p><p>Sentence Transformers is a Python framework for state-of-the-art sentence, text embeddings. It maps sentences &amp; paragraphs to a 384 dimensional dense vector space and can be used for tasks like semantic search , paraphrase mining.</p><p><strong>Paraphrase-MiniLM-L6-v2 : </strong>is based on BERT with 6 Transformer Encoder Layers , <br>it can handle 512 tokens and return dense vector representation with 384 features.</p><p>Let’s Load the pretrained Sentence Transformer Model and the tokenizer</p><pre>tokenizer <strong>=</strong> AutoTokenizer<strong>.</strong>from_pretrained(&#39;./sentence-transformer-paraphrase-MiniLM-L6-v2&#39;)<br>model <strong>=</strong> TFAutoModel<strong>.</strong>from_pretrained(&#39;./sentence-transformer-paraphrase-MiniLM-L6-v2&#39;)</pre><h4>Vocabulary Exploration</h4><pre>vocab_wrd2idx <strong>=</strong> tokenizer<strong>.</strong>vocab<br>vocab_idx2wrd <strong>=</strong> {v:k <strong>for</strong> k,v <strong>in</strong> vocab_wrd2idx<strong>.</strong>items()}<br><br>print(len(vocab_wrd2idx))<br><br>sorted(vocab_wrd2idx<strong>.</strong>items(),key<strong>=lambda</strong> x:x[1])[0:10]</pre><pre>#30522</pre><pre>[(&#39;[PAD]&#39;, 0),<br> (&#39;[unused0]&#39;, 1),<br> (&#39;[unused1]&#39;, 2),<br> (&#39;[unused2]&#39;, 3),<br> (&#39;[unused3]&#39;, 4),<br> (&#39;[unused4]&#39;, 5),<br> (&#39;[unused5]&#39;, 6),<br> (&#39;[unused6]&#39;, 7),<br> (&#39;[unused7]&#39;, 8),<br> (&#39;[unused8]&#39;, 9)]</pre><p>We have 30,522 tokens in our vocab for paraphrase-MiniLM-l6-v2 model. It has 993 tokens which are not used, represented by [unusedXXX], These are the token which we can replace to add new tokens to our vocab.</p><pre><em>#extracting model weights</em><br>model_weights <strong>=</strong> model<strong>.</strong>get_weights()</pre><pre><em>#getting vocab weights</em><br>vocab_weights <strong>=</strong> model_weights[0]</pre><p>We are Extracting the model weight and selecting the first layer which contains the token embeddings.</p><h3>1. Modify Existing word embeddings to adapt it for our use case</h3><p>Based on your use case, same word can have different meaning in different contexts, although transformers are capable of handling such scenarios but a lot of places:</p><ul><li>It wouldn’t have that much context to work with</li><li>The degree to which it’s considering the closeness is not satisfactory</li></ul><p>That’s why fine-tuning is required on the data you are working with, but if you are not able to do it due to any reason , the following can help.</p><p>Eg: In Finance domain, statements and bills are used synonymously, but since you are using a pretrained model there is high possibility that your model is not considering it to a degree which you would like it to</p><p>Let’s understand the distribution of words close to statement</p><pre><em>#Function to find top_k similar words</em><br><strong>def</strong> most_similar(search_word,top_k<strong>=</strong>5):<br>    &quot;&quot;&quot;This function takes a word and compute cosine similarity between the given word<br>       and all other words and return top_k most similar words&quot;&quot;&quot;<br>    search_idx <strong>=</strong> vocab_wrd2idx[search_word]<br>    similarity_ls<strong>=</strong>[]<br>    <strong>for</strong> word_idx,word_embed <strong>in</strong> enumerate(vocab_weights):<br>        similarity_score <strong>=</strong> cosine_similarity(vocab_weights[search_idx],word_embed)<br>        similarity_ls<strong>.</strong>append((word_idx,vocab_idx2wrd[word_idx],similarity_score))<br>    <br>    <strong>return</strong> pd<strong>.</strong>DataFrame(similarity_ls,columns<strong>=</strong>[&#39;word_index&#39;,&#39;word&#39;,&#39;score&#39;])<strong>.</strong>sort_values(by<strong>=</strong>&#39;score&#39;,ascending<strong>=False</strong>)[0:top_k]</pre><pre>most_similar(&#39;statement&#39;,top_k<strong>=</strong>10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*bmtEjOAJmrNH5WxFfQgkLA.png" /></figure><p>From the above output we see that the general context for the word “statement” is considered as the data distribution of the corpus used, is fairly broad in terms of domains/categories, so a general model of language is attained.</p><p>Let’s understand the vector closeness between statement and bill</p><pre>cosine_similarity(vocab_weights[vocab_wrd2idx[&#39;statement&#39;]],vocab_weights[vocab_wrd2idx[&#39;bill&#39;]])</pre><pre>#output<br>0.1263842135667801</pre><p>From the above result, we can see that the similarity between the word “statement” and “bill” is substantially less than we would like it to be, now with transformer model this comparison technique is not completely accurate, as we are just taking the embeddings from the first layer where no context modelling is done.</p><p>Let’s look at the similarity between encoded sentences with the model</p><pre>text1 = &#39;please send me the statement&#39;<br>text2 = &#39;please transfer the statement&#39;</pre><pre>vector1 = encode(tokenizer,text1)<br>vector2 = encode(tokenizer,text2)</pre><pre>cosine_similarity(vector1,vector2)</pre><pre>#Output:<br>0.7034520506858826</pre><p>Both sentences are similar, and we are getting a similarity score of 0.70 which is reasonable</p><p><strong>Example 0:</strong></p><pre>text1 = &#39;please send me the bill&#39;<br>text2 = &#39;please transfer the statement&#39;</pre><pre>vector1 = encode(tokenizer,text1)<br>vector2 = encode(tokenizer,text2)</pre><pre>cosine_similarity(vector1,vector2)</pre><pre>#Output:<br>0.3917175233364105</pre><p>Now with statement replaced in one sentence the score is dropping by a lot, Ideally, we would like it to be greater than 50% at least.</p><h3>Let’s understand the role of context here</h3><p><strong>Example 1:</strong> Without proper context</p><pre>text1 = &#39;i did not recieve any bill&#39; #from the bank<br>text2 = &quot;i did&#39;nt got any statement&quot; #from the bank</pre><pre>vector1 = encode(tokenizer,text1)<br>vector2 = encode(tokenizer,text2)</pre><pre>cosine_similarity(vector1,vector2)</pre><pre>#Output:<br>0.3873918354511261</pre><p><strong>Result: </strong>Similarity Score is very low as general meaning of bill is considered here.</p><p><strong>Example 2:</strong> With Added Context</p><pre>text1 = &#39;i did not recieve any bill from the bank&#39;<br>text2 = &quot;i did&#39;nt got any statement from the bank&quot;</pre><pre>vector1 = encode(tokenizer,text1)<br>vector2 = encode(tokenizer,text2)</pre><pre>cosine_similarity(vector1,vector2)</pre><pre>#Output:<br>0.6437106728553772</pre><p><strong>Result:</strong> just by adding “from the bank”, we can observe a significant improvement from 0.38 to 0.64 in the similarity score.</p><p>But while working with the data it’s not necessary that a proper context will be always present.</p><p>Let’s go back to our previous example and try to modify the embeddings to get reasonable similarity score.</p><pre><strong>def</strong> weighted_average_of_vectors(word_wghts):<br>    &quot;&quot;&quot;This Function takes words and thier weights and creates a new vector taking weighted avg of the vectors&quot;&quot;&quot;<br>    <br>    vector <strong>=</strong> np<strong>.</strong>zeros(384, dtype<strong>=</strong>np<strong>.</strong>float64)<br>    <br>    <strong>for</strong> key,value <strong>in</strong> word_wghts<strong>.</strong>items():<br>        vector <strong>+=</strong> (1 <strong>-</strong> value) <strong>*</strong> vocab_weights[vocab_wrd2idx[key]]<br>    <br>    vector <strong>=</strong> normalize(vector<strong>.</strong>reshape(1,<strong>-</strong>1))[0]<br>    <br>    <strong>return</strong> vector</pre><pre><em>#modifying the embedding of statement to incorporate meaning of bill as well in the vector</em><br><br>stmt_wghts <strong>=</strong> {<br>    &#39;statement&#39;:0.5,<br>    &#39;bill&#39;:0.5<br>}<br><br>vocab_weights[vocab_wrd2idx[&#39;statement&#39;]] <strong>=</strong> weighted_average_of_vectors(stmt_wghts)</pre><pre><em>#settings updated weights</em><br>model_weights[0] <strong>=</strong> vocab_weights<br>model<strong>.</strong>set_weights(model_weights)</pre><pre>most_similar(&#39;statement&#39;,top_k<strong>=</strong>10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vacu3UJ37QAK7kY_C5nsTA.png" /></figure><p><strong>Result</strong>: From the above result we can observe that now bill and statement vectors are nearby in the vector space.</p><p><strong>Example 3:</strong> After Updating the Embedding</p><pre>text1 <strong>=</strong> &#39;please send me the bill&#39;<br>text2 <strong>=</strong> &#39;please transfer the statement&#39;<br><br>vector1 <strong>=</strong> encode(tokenizer,text1)<br>vector2 <strong>=</strong> encode(tokenizer,text2)<br><br>cosine_similarity(vector1,vector2)</pre><pre>#Output:<br>0.5900149941444397</pre><p><strong>Result:</strong> Now with the embeddings modified we see a significant jump in similarity score from 0.39(Example 0) to 0.59.</p><h3>2. Add New Words to Vocabulary</h3><p>Suppose you have trained your model or you are using a pretrained model but you observe that some important words are missing from the vocabulary, and you don’t want to retrain the model with new data, you can follow the below method to add new word/tokens to your model.</p><pre><em>#checking if words are in vocab</em><br><br>words_to_add <strong>=</strong> [&quot;stmt&quot;,&quot;ftp&quot;,&#39;http&#39;]<br><br>[wrd <strong>in</strong> tokenizer<strong>.</strong>vocab <strong>for</strong> wrd <strong>in</strong> words_to_add]</pre><pre>#Output:<br>[False, False, True]</pre><p><strong>Result:</strong> only http is present in the vocab. ftp and stmt (short for stament) is not present (you can always replace the word at preprocessing,this is just for demonstration)</p><p>Let’s try to add the words ‘ftp’ and ‘stmt’ to the vocabulary.</p><pre><strong>def</strong> add_word(word_to_replace,word_to_add,word_wghts):<br>    &#39;&#39;&#39;This Function takes the token to replace , word to add and word weights,<br>       and replaces the word and it&#39;s embedding.<br>    &#39;&#39;&#39;<br>    <em>#editing the dictionary </em><br>    vocab_index <strong>=</strong> vocab_wrd2idx[word_to_replace]<br>    vocab_wrd2idx[word_to_add] <strong>=</strong> vocab_index<br>    <strong>del</strong> vocab_wrd2idx[vocab_idx2wrd[vocab_index]]<br>    vocab_idx2wrd[vocab_index] <strong>=</strong> word_to_add<br>    <br>    <em>#add the vector</em><br>    vocab_weights[vocab_index] <strong>=</strong> weighted_average_of_vectors(word_wghts)<br>    <br>    <em>#settings weights</em><br>    model_weights[0] <strong>=</strong> vocab_weights<br>    model<strong>.</strong>set_weights(model_weights)</pre><pre><em>#defining weights for new words</em><br><br>ftp_wghts <strong>=</strong> {<br>    &#39;file&#39;:0.3,<br>    &#39;transfer&#39;:0.3,<br>    &#39;protocol&#39;:0.4,<br>}<br><br>stmt_wghts <strong>=</strong> {<br>    &#39;statement&#39;:0.5,<br>    &#39;bill&#39;:0.5<br>}<br><br><em>#adding words</em><br>add_word(&#39;[unused900]&#39;,&#39;ftp&#39;,ftp_wghts)<br>add_word(&#39;[unused902]&#39;,&#39;stmt&#39;,stmt_wghts)</pre><p>Let’s check the most similar words to the newly added words</p><pre>most_similar(&#39;stmt&#39;)<br>most_similar(&#39;ftp&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*43K9A5v54tVUAC1-3qdjmw.png" /></figure><p><strong>Inference: </strong>From the above table we can infer that the new words added have a proper vector representation and are close to similar meaning words.</p><p>We have successfully added the new word and the embeddings, but the tokenizer vocab is not updated, it cannot be directly updated, so, we will write our vocab dictionary to the tokenizer.json and then load the updated tokenizer.</p><pre><em>#Updating the tokenizer</em><br><strong>with</strong> open(&#39;./sentence-transformer-paraphrase-MiniLM-L6-v2/tokenizer.json&#39;,&#39;r&#39;,encoding<strong>=</strong>&#39;utf-8&#39;) <strong>as</strong> f:<br>    tokenizer_json <strong>=</strong> json<strong>.</strong>load(f)<br>    <br>tokenizer_json[&#39;model&#39;][&#39;vocab&#39;]<strong>=</strong>dict(sorted(vocab_wrd2idx<strong>.</strong>items(),key<strong>=lambda</strong> x:x[1]))<br><br><em>#renaming vocab file </em><br><br>os<strong>.</strong>chdir(&#39;./sentence-transformer-paraphrase-MiniLM-L6-v2&#39;)<br><br><em>#renaming old vocab file</em><br><strong>!</strong>ren tokenizer.json tokenizer_old.json<br><br>os<strong>.</strong>chdir(&#39;../&#39;)<br><br><strong>with</strong> open(&#39;./sentence-transformer-paraphrase-MiniLM-L6-v2/tokenizer.json&#39;,&#39;w&#39;,encoding<strong>=</strong>&#39;utf-8&#39;) <strong>as</strong> f:<br>    json<strong>.</strong>dump(tokenizer_json,f)</pre><p>Loading the updated Tokenizer:</p><pre>updated_tokenizer <strong>=</strong> AutoTokenizer<strong>.</strong>from_pretrained(&#39;./sentence-transformer-paraphrase-MiniLM-L6-v2&#39;)</pre><pre><em>#checking if words are in vocab</em><br><br>words_to_add <strong>=</strong> [&quot;stmt&quot;,&quot;ftp&quot;,&#39;http&#39;]<br><br>[wrd <strong>in</strong> updated_tokenizer<strong>.</strong>vocab <strong>for</strong> wrd <strong>in</strong> words_to_add]</pre><pre>#Output:</pre><pre>[True, True, True]</pre><p><strong>Inference: </strong>The New Tokenizer has all the updated words</p><p>Now, Let’s compare the similarity between the sentences before and after adding the missing words.</p><h3>Sample 1:</h3><p>With Old Tokenizer without the word stmt added</p><pre>text1 <strong>=</strong> &#39;the statement is incorrect&#39;<br>text2 <strong>=</strong> &#39;the stmt is wrong&#39;<br><br>vector1 <strong>=</strong> encode(tokenizer,text1)<br>vector2 <strong>=</strong> encode(tokenizer,text2)<br><br>cosine_similarity(vector1,vector2)</pre><pre>#Output<br>0.3759283423423767</pre><p>With Updated Tokenizer containing the word stmt</p><pre>text1 <strong>=</strong> &#39;the statement is incorrect&#39;<br>text2 <strong>=</strong> &#39;the stmt is wrong&#39;<br><br>vector1 <strong>=</strong> encode(updated_tokenizer,text1)<br>vector2 <strong>=</strong> encode(updated_tokenizer,text2)<br><br>cosine_similarity(vector1,vector2)</pre><pre>#Output<br>0.8123685717582703</pre><p><strong>Result:</strong> From the above Example we observe a significant improvement on Similarity Score, as the model now has an understanding of the word stmt, Earlier the old Tokenizer was breaking the word <em>“stmt”</em> into <em>‘st’</em> and <em>‘##mt’</em> as it couldn’t find stmt in the vocab.</p><h3>Sample 2:</h3><p>With Old Tokenizer without the word ftp added</p><pre>text1 <strong>=</strong> &#39;unable to upload the data through ftp&#39;<br>text2 <strong>=</strong> &#39;file transfer protocol upload is not working&#39;<br><br>vector1 <strong>=</strong> encode(tokenizer,text1)<br>vector2 <strong>=</strong> encode(tokenizer,text2)<br><br>cosine_similarity(vector1,vector2)</pre><pre>#Output:<br>0.6022258400917053</pre><p>With Updated Tokenizer containing the word ftp</p><pre>text1 <strong>=</strong> &#39;unable to upload the data through ftp&#39;<br>text2 <strong>=</strong> &#39;file transfer protocol upload is not working&#39;<br><br>vector1 <strong>=</strong> encode(updated_tokenizer,text1)<br>vector2 <strong>=</strong> encode(updated_tokenizer,text2)<br><br>cosine_similarity(vector1,vector2)</pre><pre>#Output:<br>0.766219437122345</pre><p><strong>Result:</strong> In this case as well, we can observe a good increase in Similarity Score</p><p><strong>Conclusion: From the above experiments</strong></p><ul><li>We learnt how we can add new tokens and modify the existing vectors manually to Increase the model Performance</li><li>We understood the model Architecture, and understood why there are so many [unused0] tokens available in the vocabulary</li><li>Understood the importance of context for Embeddings</li><li>Built Functions like:</li></ul><blockquote>most_similar to understand the words similarity in vector space,</blockquote><blockquote>add_words,weighted_average_of_vectors to add new words to our vocab</blockquote><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p><strong>Code Link:</strong> <a href="https://github.com/SJ-Ray/Manual_Fine_Tune_Vectors">https://github.com/SJ-Ray/Manual_Fine_Tune_Vectors</a></p><p><strong>Connect On: </strong><a href="https://www.linkedin.com/in/suraj-kumar-710382a7/"><strong>LinkedIn: Suraj Kumar</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19fb7061134d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use CNN With Machine Learning]]></title>
            <link>https://medium.com/@surajx42/use-cnn-with-machine-learning-a8310b76fb96?source=rss-c8aae123e353------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8310b76fb96</guid>
            <category><![CDATA[using-pretrained-model]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Suraj Kumar]]></dc:creator>
            <pubDate>Sat, 14 Dec 2019 14:42:12 GMT</pubDate>
            <atom:updated>2019-12-29T12:04:52.892Z</atom:updated>
            <content:encoded><![CDATA[<h3>Objective:</h3><p>Learn to use Keras’s pre-trained model to extract features from images and train a Machine Learning model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*_Lg1i7wv1pLpzp2F4MLrvw.png" /></figure><h3>Problem Statement:</h3><p>Classify Fish and People from the CIFAR-100 dataset.</p><h3>Dataset</h3><p>CIFAR-100: This dataset has 100 classes containing 600 images each. There are 500 training images and 100 testing images per class. The 100 classes in the CIFAR-100 are grouped into 20 superclasses. Each image comes with a “fine” label (the class to which it belongs) and a “coarse” label (the superclass to which it belongs).</p><p>Link: <a href="https://www.cs.toronto.edu/~kriz/cifar.html">https://www.cs.toronto.edu/~kriz/cifar.html</a></p><h3>Steps</h3><ol><li>Load the dataset.</li></ol><pre><em>#code to unpickle cifar 100 dataset and return dataframe</em><br><strong>def</strong> unpickle_load_df(file):<br>    <strong>with</strong> open(file, &#39;rb&#39;) <strong>as</strong> fo:<br>        dict_ = pickle.load(fo, encoding=&#39;bytes&#39;)<br>        <br>    df=pd.DataFrame(dict_[ b&#39;data&#39;])<br>    columns=list(dict_.keys())<br>    columns.remove(b&#39;data&#39;)<br>    <strong>for</strong> col <strong>in</strong> columns:<br>        df[col]=dict_[col]<br>        <br>    <strong>return</strong> df</pre><pre><em>#load train and test dataset</em><br>train=unpickle_load_df(&#39;cifar-100-python/train&#39;)<br>test=unpickle_load_df(&#39;cifar-100-python/test&#39;)</pre><p>2. Extract People and Fish data from the dataset.</p><pre>#selecting only fish and people records from dataframe<br>#1 : Fish, 14 : People<br>train=train[train[b’coarse_labels’].isin([1,14])]<br>test=test[test[b’coarse_labels’].isin([1,14])</pre><p>3. Split, Reshape and Preprocess the images.</p><pre>X_train,y_train=train.iloc[:,:-4],train.iloc[:,-1]<br>X_test,y_test=test.iloc[:,:-4],test.iloc[:,-1]</pre><pre><em>#reshaping images</em><br>X_train=X_train.values.reshape(-1,3,32,32).transpose(0,2,3,1)<br>X_test=X_test.values.reshape(-1,3,32,32).transpose(0,2,3,1)</pre><pre><em>#preprocessing images</em><br><strong>def</strong> prepocess_images(X):<br>    image_list=[]<br>    <br>    <strong>for</strong> x <strong>in</strong> X:<br>        image_list.append(preprocess_input(x))<br>        <br>    <strong>return</strong> np.array(image_list)<br><br>X_train=prepocess_images(X_train)<br>X_test=prepocess_images(X_test)</pre><p>4. Load VGG16 model from Keras using “imagenet” weights.</p><pre><em>#loading VGG16 with imagenet weigths</em><br>image_size=32<br>num_class=2<br>model=VGG16(weights=&#39;imagenet&#39;,include_top=<strong>False</strong>,input_shape=(image_size,image_size,3))</pre><p>5. Extract Features from VGG16.</p><pre><em>#get Feautre vectors from complete VGG16 network</em><br>X_train_features=model.predict(X_train).reshape(-1,512)<br>X_test_features=model.predict(X_test).reshape(-1,512)</pre><p>6. Train a Machine Learning model (we are using LogisticRegression here)</p><pre><em>#Training logistic regression  </em><br>lr=LogisticRegression()<br>lr.fit(X_train_features,y_train)<br>predictions=lr.predict(X_test_features)<br>print(&quot;Accuracy Score :&quot;,accuracy_score(predictions,y_test))</pre><p>Accuracy Score: 0.871</p><p>We got 87.1 % accuracy using the VGG16 directly.</p><p>Let’s modify it to improve the results</p><p>Reduce the number of layers in the VGG16 Model.</p><pre>#reducing the size of vgg16 network to extract low level features<br>reduced_model=Sequential()<br>for layer in model.layers[:-8]:<br> reduced_model.add(layer)<br>reduced_model.add(Flatten())<br>reduced_model.summary()</pre><p>Model summary:-</p><pre>Model: &quot;sequential_1&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>block1_conv1 (Conv2D)        (None, 32, 32, 64)        1792      <br>_________________________________________________________________<br>block1_conv2 (Conv2D)        (None, 32, 32, 64)        36928     <br>_________________________________________________________________<br>block1_pool (MaxPooling2D)   (None, 16, 16, 64)        0         <br>_________________________________________________________________<br>block2_conv1 (Conv2D)        (None, 16, 16, 128)       73856     <br>_________________________________________________________________<br>block2_conv2 (Conv2D)        (None, 16, 16, 128)       147584    <br>_________________________________________________________________<br>block2_pool (MaxPooling2D)   (None, 8, 8, 128)         0         <br>_________________________________________________________________<br>block3_conv1 (Conv2D)        (None, 8, 8, 256)         295168    <br>_________________________________________________________________<br>block3_conv2 (Conv2D)        (None, 8, 8, 256)         590080    <br>_________________________________________________________________<br>block3_conv3 (Conv2D)        (None, 8, 8, 256)         590080    <br>_________________________________________________________________<br>block3_pool (MaxPooling2D)   (None, 4, 4, 256)         0         <br>_________________________________________________________________<br>flatten_1 (Flatten)          (None, 4096)              0         <br>=================================================================<br>Total params: 1,735,488<br>Trainable params: 1,735,488<br>Non-trainable params: 0<br>_________________________________________________________________</pre><p>Extract Features from the reduced model</p><pre>#get Feautre vectors from complete VGG16 network<br>X_train_features=reduced_model.predict(X_train)<br>X_test_features=reduced_model.predict(X_test)</pre><p>Train using the Extracted Features</p><pre>#Training logistic regression <br>lr=LogisticRegression()<br>lr.fit(X_train_features,y_train)<br>predictions=lr.predict(X_test_features)<br>print(“Accuracy Score :”,accuracy_score(predictions,y_test))</pre><p>Accuracy Score: 0.93<strong>1</strong></p><p><strong>Conclusion:</strong></p><p>We learned how to use pre-trained CNN models to extract features from images.</p><p>Also found out that removing the last few layers can help improve results as the last convolution layers usually capture complex high-level feature for the categories which the model was trained on (here “imagenet” with more than 20K categories).</p><p>The first few layers capture universal features like curves and edges that are also relevant to our new problem. Hence, the reduced model performed better for our dataset.</p><p>References and Resources:</p><p>Dataset:- <a href="https://www.cs.toronto.edu/~kriz/cifar.html">https://www.cs.toronto.edu/~kriz/cifar.html</a></p><p>Github Link: <a href="https://github.com/SJ-Ray/CNN-with-Machine-Learning">https://github.com/SJ-Ray/CNN-with-Machine-Learning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8310b76fb96" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>