<?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 Priyanka Kumari on Medium]]></title>
        <description><![CDATA[Stories by Priyanka Kumari on Medium]]></description>
        <link>https://medium.com/@kumari01priyanka?source=rss-cf9524f470e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f8PJUdO7rhp-dJhyZYsK1Q.png</url>
            <title>Stories by Priyanka Kumari on Medium</title>
            <link>https://medium.com/@kumari01priyanka?source=rss-cf9524f470e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:40:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kumari01priyanka/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[BERT and DistilBERT Models for NLP]]></title>
            <link>https://medium.com/@kumari01priyanka/bert-and-distilbert-model-for-nlp-7352eb16915e?source=rss-cf9524f470e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7352eb16915e</guid>
            <category><![CDATA[distilbert]]></category>
            <category><![CDATA[best-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Priyanka Kumari]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 03:08:57 GMT</pubDate>
            <atom:updated>2023-06-23T03:10:04.998Z</atom:updated>
            <content:encoded><![CDATA[<ol><li><strong>BERT Architecture</strong></li></ol><p>Google developed BERT (Bidirectional Encoder Representations from Transformers) in 2018 as a powerful natural language processing model. It is a deep neural network that uses self-supervised learning to pre-train on a large corpus of text data, allowing it to learn contextual relations between words in a text [1, 2]. The transformer architecture is the foundation of BERT, which is designed to handle sequential data, such as text. It has multiple layers of self-attention mechanisms that enable it to capture longrange dependencies between words in a text. BERT is a bidirectional model that can consider both left and right context when making predictions. This helps BERT understand the context and meaning of words in a sentence. BERT can be fine-tuned on specific downstream NLP tasks, such as sentiment analysis or named entity recognition, by training on a smaller, labeled dataset. Fine-tuning allows BERT to achieve state-of-the-art performance on a wide range of NLP tasks, even when training data is limited.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtIGJvuGPQLKUs1AqKEHwA.png" /><figcaption><strong>Fig 1: BERT</strong></figcaption></figure><p>In Figure 1 BERT model is pre-trained on a large corpus of Amazon Negative Product Review data and can be fine-tuned for various NLP tasks [3]. The BERT Model consists of several layers:</p><ul><li><strong>Input Layer:</strong> The BERT Model takes inputs: ids, and mask. These inputs are encoded representations of the input text obtained using a tokenizer.</li><li><strong>pre-trained Layer:</strong> The pre-trained layer refers to a neural network pre-trained on large amounts of text data. When input text is fed into the Roberta model, the pretrained layer processes it and produces a sequence of hidden states for each input token. The RoBERTa model has a deep architecture comprising multiple selfattention layers and feed-forward neural networks.</li><li><strong>Fully connected Layer:</strong> The fully connected layer is a linear layer that takes the output of the pre-trained Layer and maps it to the desired output dimensionality</li></ul><p>During the forward pass, the input ids, and mask are passed through the pre-trained layer, generating a hidden state sequence. Finally, the output of the dropout layer is passed through the linear output layer to produce the final output of the model, which is a vector of size two representing the probabilities of the two classes in the topic tagging task.</p><p><strong>2. BERT Code</strong></p><p>Here is an example of BERT code using Python and the popular deep learning library Pytorch for NLP:</p><p><a href="https://github.com/priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview/blob/main/Model/BERT/Topic/BERT_topic.ipynb">ReviewTag_TaggingAmazonNegReview/Model/BERT/Topic/BERT_topic.ipynb at main · priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview</a></p><p><strong>3. DistilBERT Architecture</strong></p><p>Hugging Face introduced DistilBERT in 2019 as a smaller and faster alternative to BERT, a powerful natural language processing model developed by Google. DistilBERT uses a distillation technique to train a smaller model to replicate BERT’s behavior, resulting in a model with fewer parameters while maintaining high accuracy and performance [4, 5, 6]. DistilBERT still uses the transformer architecture and is pre-trained using selfsupervised learning on a large corpus of text data, making it a bidirectional model that considers both the left and right context of each word in a sentence when making predictions.</p><p>DistilBERT performs well on various NLP tasks such as text classification, question answering, and named entity recognition. Many researchers and practitioners in the NLP community have adopted DistilBERT due to its smaller size and faster training and inference times, without sacrificing much accuracy or performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rBOd_LyR41CSCdVWLA7RA.png" /><figcaption><strong>Figure 2: DistilBERT</strong></figcaption></figure><p>Figure 2 DistilBERT model is pre-trained on a large corpus of Amazon Negative Product Review data and can be fine-tuned for various NLP tasks. DistilBERT Model consists of several layers:</p><ul><li><strong>Input Layer:</strong> The DistilBERT Model takes inputs: ids, and mask. These inputs are encoded representations of the input text obtained using a tokenizer.</li><li><strong>pre-trained Layer:</strong> The pre-trained “distilbert-base-uncased” weights are used to initialize the DistilBERT model. It processes the input tensors to obtain the hidden state output. The first token of the sequence is used to obtain a pooled representation of the input sequence from the hidden_state tensor.</li><li><strong>Linear Layer pre-classifier:</strong> Linear layer pre-classifier is responsible for extracting features from data by taking the output of the pre-trained layer and passing it to a fully connected layer.</li><li><strong>Fully connected Layer:</strong> The fully connected layer is a linear layer that takes the output of linear layer pre-classifier and maps it to the desired output dimensionality. In this case, the output dimensionality is two, corresponding to topic tagging.</li></ul><p>During the forward pass, the input ids, and mask are passed through the pre-trained layer, generating a hidden state sequence. Finally, the output of the dropout layer is passed through the linear output layer to produce the final output of the model, which is a vector of size two representing the probabilities of the two classes in the topic tagging task.</p><p><strong>4. DistilBERT Code</strong></p><p><a href="https://github.com/priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview/blob/main/Model/DistilBERT/Topic/Topic.ipynb">ReviewTag_TaggingAmazonNegReview/Model/DistilBERT/Topic/Topic.ipynb at main · priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview</a></p><h3>Reference</h3><p>[1] “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” by Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies (NAACL-HLT), pages 4171–4186, 2019.</p><p>[2] Devlin, J., Chang, M. W., Lee, K., &amp; Toutanova, K. (2018). Bert: Pre-training of deep bidirectional transformers for language understanding. arXiv preprint arXiv:1810.04805.</p><p>[3] “BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding” by Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. In Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies (NAACL-HLT), pages 4171–4186, 2019.</p><p>[4] Sanh, V., Debut, L., Chaumond, J., &amp; Wolf, T. (2019). DistilBERT, a distilled version of BERT: smaller, faster, cheaper, and lighter. arXiv preprint arXiv:1910.01108. Link: <a href="https://arxiv.org/abs/1910.01108">https://arxiv.org/abs/1910.01108</a></p><p>[5] Sun, Y., Wang, S., Li, Z., Feng, Y., Chen, X., &amp; Zhang, H. (2021). DistilBERT for Question Answering. In Proceedings of the 2021 International Conference on Education Technology Management (ICETM 2021) (pp. 420–424). Atlantis Press. Link: <a href="https://www.atlantis-press.com/proceedings/icetm-21/125957688">https://www.atlantis-press.com/proceedings/icetm-21/125957688</a></p><p>[6] Tariq, U., Naseem, I., &amp; Razzak, I. (2021). A Comparative Study of BERT and DistilBERT on Text Classification. Journal of Data Science and Applications, 4(2), 79–88. Link: <a href="http://www.jdsap.org/jdsap/article/view/123">http://www.jdsap.org/jdsap/article/view/123</a></p><p>[7] ReviewTag — Analyzing Amazon Negative Product Reviews using Deep Learning by Priyanka Kumari thesis under University of Houston Clear Lake.</p><p>[8] Figure created by the author of this post, adapted from the provided code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7352eb16915e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LSTM & RNN Models for NLP]]></title>
            <link>https://medium.com/@kumari01priyanka/lstm-rnn-models-ac23603b014b?source=rss-cf9524f470e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac23603b014b</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[rnn-architecture]]></category>
            <dc:creator><![CDATA[Priyanka Kumari]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 02:45:40 GMT</pubDate>
            <atom:updated>2023-06-23T03:09:46.211Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>1. LSTM Architecture</strong></p><p>LSTM is a type of RNN type that overcomes the vanishing gradient problem in traditional RNNs [1, 2]. The vanishing gradient problem arises when the gradients used to update the network’s weights become very small during backpropagation, making it difficult for the network to learn long-term dependencies. A set of gates that control the flow of information through the network is introduced by LSTMs to solve this issue. These gates, including an input gate, an output gate, and a forget gate, enable the network to selectively update, output, or forget information at each time step.</p><p>At each time step, the input gate determines which information from the current input should be used to update the memory state. Meanwhile, the forget gate decides which information from the previous memory state should be forgotten. The output gate then determines which information from the updated memory state should be outputted to the next layer or as the final prediction. The cell state is the memory state in an LSTM, which can retain information for extended periods. The input and forget gates enable the network to selectively update or forget information in the cell state. LSTMs have been shown to be effective at modeling sequential data and have achieved state-of-the-art results on many tasks in natural language processing, speech recognition, machine translation, and image captioning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6voHI5QyRKr0HN-XOdjgOA.png" /><figcaption><strong><em>Fig 1: LSTM </em>Architecture</strong></figcaption></figure><p>Figure 1 illustrates the architecture of the LSTM model [3], which is composed of multiple layers:</p><ul><li><strong>Input layer:</strong> The input layer receives the input data through token IDs and their lengths. The token IDs represent the index of the words in the vocabulary, and their lengths indicate how many tokens are in each sequence.</li><li><strong>Embedding layer:</strong> The embedding layer converts the token IDs into dense vectors of fixed size (embedding dimension) that capture the semantic meaning of the words in the input sequence.</li><li><strong>LSTM layer:</strong> The LSTM layer processes the embedded input sequences using the LSTM algorithm. The LSTM layer has a certain number of hidden units (hidden_dim) and can be stacked in multiple layers (n_layers) to increase the model’s capacity.</li><li><strong>Fully Connected Layer:</strong> The fully connected layer is a linear layer that takes the output of the pre-trained layer and maps it to the desired output dimensionality. In this case, the output dimensionality is two, corresponding to topic tagging.</li></ul><p><strong>2. LSTM Code</strong></p><p>Here is an example of LSTM code using Python and the popular deep learning library Pytorch for NLP:</p><p><a href="https://github.com/priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview/blob/main/Model/LSTM/Topic/Topic.ipynb">ReviewTag_TaggingAmazonNegReview/Model/LSTM/Topic/Topic.ipynb at main · priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview</a></p><p><strong>3. RNN Architecture</strong></p><p>RNN is a type of neural network designed for handling sequential data, such as time series or natural language. RNNs can process sequences of inputs by maintaining an internal state that depends on the previous inputs, and they can share weights across different time steps. This allows them to learn and model temporal dependencies in the data using recurrent connections [4, 5]. The LSTM network is the most common type of RNN that addresses the problem of vanishing gradients in traditional RNNs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qdoJz5K7SZtfGzMOWsJJQ.png" /><figcaption><strong>Fig 2: RNN</strong></figcaption></figure><p>Figure 2 illustrates the architecture of the RNN model [3], which is composed of multiple layers:</p><ul><li><strong>Input layer:</strong> The input layer receives the input data through token IDs and their lengths. The token IDs represent the index of the words in the vocabulary, and their lengths indicate how many tokens are in each sequence.</li><li><strong>Embedding layer:</strong> The embedding layer converts the token IDs into dense vectors of fixed size (embedding dimension) that capture the semantic meaning of the words in the input sequence.</li><li><strong>RNN layer:</strong> RNN layer takes the embedded sequences as input and produces a sequence of hidden states. The RNN layer used in this implementation is an instance of the nn.RNN class. The layer can be configured to have multiple layers and be bidirectional.</li><li><strong>Fully Connected Layer:</strong> The fully connected layer is a linear layer that takes the output of the pre-trained layer and maps it to the desired output dimensionality. In this case, the output dimensionality is two, corresponding to topic tagging.</li></ul><p><strong>4. RNN Code</strong></p><p>Here is an example of RNN code using Python and the popular deep learning library Pytorch for NLP:</p><p><a href="https://github.com/priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview/blob/main/Model/RNN/Topic/Topic.ipynb">ReviewTag_TaggingAmazonNegReview/Model/RNN/Topic/Topic.ipynb at main · priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview</a></p><h3>Reference</h3><p>[1] S. Hu, G. Zou, S. Lin, L. Wu, C. Zhou, B. Zhang, and Y. Chen, “Recurrent Transformer for Dynamic Graph Representation Learning with Edge Temporal States”, Washington University in St. Louis, 2023</p><p>[2] [Hochreiter and Schmidhuber, 1997] Sepp Hochreiter and Ju ̈rgen Schmidhuber. Long short-term memory. Neural Computation, 9(8):1735–1780, 1997</p><p>[3] Dieng, A. B., Ruiz, F. J., &amp; Blei, D. M. (2020). Topic modeling in embedding spaces. Transactions of the Association for Computational Linguistics, 8, 439–453.</p><p>[4] Liu, P., Qiu, X., &amp; Huang, X. (2016). Recurrent neural network for text classification with multi-task learning. arXiv preprint arXiv:1605.05101.</p><p>[5] Zulqarnain, M., Ghazali, R., Hassim, Y. M. M., &amp; Rehan, M. (2020). A comparative review on deep learning models for text classification. Indones. J. Electr. Eng. Comput. Sci, 19(1), 325–335.</p><p>[6] ReviewTag — Analyzing Amazon Negative Product Reviews using Deep Learning by Priyanka Kumari thesis under University of Houston Clear Lake.</p><p>[8] Figure created by the author of this post based on [3]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac23603b014b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CNN Model for NLP]]></title>
            <link>https://medium.com/@kumari01priyanka/cnn-model-6f0d125b6ece?source=rss-cf9524f470e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f0d125b6ece</guid>
            <category><![CDATA[cnn-model]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Priyanka Kumari]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 02:16:27 GMT</pubDate>
            <atom:updated>2023-06-23T03:09:22.033Z</atom:updated>
            <content:encoded><![CDATA[<p>CNN for Sentence Classification is a NLP technique that uses convolutional neural networks to classify sentences into different categories or labels. The technique involves training a CNN on a large dataset of sentences, where each sentence is assigned a label or category [1, 2].</p><h4>1. CNN Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSQFP27DvHMSOFDB-8AEJg.png" /><figcaption><strong>CNN Architecture</strong></figcaption></figure><p>Figure shows the architecture of the CNN model [3], which is composed of multiple layers:</p><ul><li><strong>Input layer: </strong>The input layer receives the input data through token IDs and their lengths. <em>The token IDs represent the index of the words in the vocabulary, and their lengths indicate how many tokens are in each sequence</em>.</li><li><strong>Embedding layer:</strong> <em>The embedding layer converts the token IDs into dense vectors of fixed size</em> (embedding dimension) that capture the semantic meaning of the words in the input sequence of each sequence (batch_size, max_len, embedding_dim) of (64, 256,300). The input sequence is reshaped to have dimensions (batch_size, embedding_dim, max_len) of (64, 300, 256) and then fed into the convolutional layers.</li><li><strong>Convolutional Layers:</strong> The next layer consists of multiple parallel convolutional layers with different filter sizes (filter_sizes) and the number of filters (num_filters). Each convolutional layer applies a set of filters with the same kernel size to the input embeddings, producing a feature map for each filter. The output shape of each feature map is (batch_size, num_filters[i], L_out), where L_out is the output length after applying the convolution operation.</li><li><strong>Max Pooling:</strong> Max pooling is applied to each feature map over the time dimension (L_out) to obtain a fixed-length representation of the most important features. This operation reduces the feature maps’ dimensionality and helps extract the most relevant features in the data. The output shape of each pooled feature map is (batch_size, num_filters[i], 1).</li><li><strong>Flatten Layer:</strong> A flatten layer (nn.Flatten) is added to convert the 3D tensor output of the pooling layers into a 2D tensor that can be fed into the fully connected layer.</li><li><strong>Fully Connected Layer:</strong> The fully connected layer is a linear layer that takes the output of the pre-trained layer and maps it to the desired output dimensionality. In this case, the output dimensionality is two, corresponding to topic tagging.</li></ul><h4>2. CNN Code:</h4><p>Here is an example of CNN code using Python and the popular deep learning library Pytorch for NLP:</p><p><a href="https://github.com/priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview/blob/main/Model/CNN/Topic/Topic.ipynb">ReviewTag_TaggingAmazonNegReview/Model/CNN/Topic/Topic.ipynb at main · priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview</a></p><h4>Reference</h4><p>[1] Kim, Y. (2014). Convolutional neural networks for sentence classification. In Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP) (pp. 1746–1751).</p><p>[2] Chen, Y . (2015). Convolutional neural network for sentence classification (Master’s thesis, University of Waterloo).</p><p>[3] Zhang, Y., &amp; Wallace, B. (2016). A Sensitivity Analysis of (and Practitioners’ Guide to) Convolutional Neural Networks for Sentence Classification. arXiv preprint arXiv:1510.03820.</p><p>[4] ReviewTag — Analyzing Amazon Negative Product Reviews using Deep Learning by Priyanka Kumari thesis under University of Houston Clear Lake.</p><p>[5] Figure created by the author of this post, adapted from the <a href="https://github.com/priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview/blob/main/Model/CNN/Topic/Topic.ipynb">provided code.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f0d125b6ece" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedded Layer]]></title>
            <link>https://medium.com/@kumari01priyanka/embedded-layer-12cccb9a5def?source=rss-cf9524f470e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/12cccb9a5def</guid>
            <category><![CDATA[embedded]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[common-crawl]]></category>
            <category><![CDATA[fasttext]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <dc:creator><![CDATA[Priyanka Kumari]]></dc:creator>
            <pubDate>Mon, 29 May 2023 16:00:15 GMT</pubDate>
            <atom:updated>2023-06-23T02:47:33.973Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1moCNFltpuRE9Cg8w4Jw3g.png" /></figure><p>In NLP, a neural network uses an embedding layer to convert <a href="https://medium.com/@kumari01priyanka/amazon-review-data-transformation-64fa38f9fd53">text data into a numerical format</a> it can process. The network learns dense embeddings and vector text representations with a fixed length and are continuous-valued. These embeddings can capture complex relationships between words and be used for various NLP tasks, such as sentiment analysis and named entity recognition [1].</p><p><strong>1. Input-Output Embedded Layer</strong></p><p>The embedding layer is an essential component of many deep learning models, including CNN, LSTM, and RNN, and its primary function is to convert word tokens into dense vector representations. The input to the embedding layer is typically a sequence of integer-encoded word tokens mapped to high-dimensional vectors. In reviewText1, like “The gloves are very poor quality” and tokenize each word into an integer, we could generate the input token sequence [2, 3, 4, 5, 6, 7, 8]. These tokens would then be passed as input to the embedding layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*57WGig6H9PcoaGtKjoTvyw.png" /><figcaption><strong><em>Figure 1: Embedded Layer</em></strong></figcaption></figure><p>The output of the embedding layer is a sequence of dense vector representations, with each vector corresponding to a specific word in the input sequence. Each vector has a fixed length, and the dimensionality of the vectors is typically a hyperparameter that can be tuned during model training. The embedding layer aims to learn a set of vector representations that capture the semantic relationships between words in the input sequence. In Figure 1, the embedding layer is configured with a batch size of 64 and a maximum input length of 256 [2]. Each input consists of a 1x300 vector, where the dimensions represent related words. For instance, the word “gloves” is associated with 300 related words, including hand, leather, finger, mittens, winter, sports, fashion, latex, motorcycle, and work. These words are assigned a vector representation at position 2 with a shape of 1x300.</p><p><strong>2. fastText</strong></p><p>fastText is an open-source library developed by Facebook AI Research, designed to process and classify text data efficiently, particularly in natural language processing (NLP) [3]. It uses a neural network-based approach to learn the embeddings of words or short phrases, called n-grams, in a continuous vector space. The embeddings represent words semantic and syntactic meanings and can be used as input features for various downstream NLP tasks, such as topic tagging. fastText can handle out-of-vocabulary words by breaking them down into smaller sub word units or character n-grams, which are then represented with their embeddings, enabling the model to generalize better to unseen words and improve overall classification accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXCWc3hTiQhLmLqyckwIKg.png" /><figcaption><strong><em>Figure 2: fastText (FT)</em></strong></figcaption></figure><p>The fastText model is a pre-trained word embedding model that learns embeddings of words or n-grams in a continuous vector space. It is trained on a massive dataset of text, Common Crawl, consisting of over 600 billion tokens from various sources, including web pages, news articles, and social media posts [4]. The model outputs 2 million word vectors, each with a dimensionality of 300, because of this pre-training process. These pre-trained word vectors can be used as an embedding layer in neural networks for various NLP tasks, such as topic tagging. They are a great starting point for training deep learning models on other tasks, as they allow for improved performance with less training data and time. Figure 2 illustrates the output of the fastText model, which consists of 2 million word vectors with a dimensionality of 300, called fastText embedding. The word is represented by FTWord1, and its corresponding vector is represented by FT vector1, FT vector2, FT vector3, … FT vector300. The original website represented “ FastText “ as “fastText”.</p><p>The vector comprises 300 dimensions, each representing a unique aspect of a word’s meaning. The first dimension may indicate the word’s part of speech, the second its semantic representation, and the third its sentiment. The values assigned to each dimension are real numbers, representing the degree of the word’s association with that particular aspect of meaning. For instance, the value in the first dimension might be -0.038194, indicating that “fastText” is slightly more likely to be a noun than a verb based on the vector’s analysis.</p><p><strong>3 fastText Embeddings Layer</strong></p><p>Figure 3 provides an overview of the three primary components of the system: Vocab, fastText, and embedding. The vocabulary was created using a text tokenizer, resulting in a size of 4773 for the training dataset. Additionally, fastText as a 2 million by 300 word vector.</p><p>To initialize the embedding matrix, a random matrix of size (4777, 300) is created, matching the vocabulary size and fastText dimensionality. The matrix is initialized with all zeros. Next, the fastText embedding is read line by line, extracting each word from FT Word and FT Vector representation. The function checks if the word is present in Vocab and updates its FT vector in the initialized embedding matrix. The resulting embedding matrix has each row representing the embedding vector for the corresponding word in fastText.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41tWWSnacI7kriOmqXxKlg.png" /><figcaption><strong><em>Figure 3: Vocab and Fast Text to Embedding</em></strong></figcaption></figure><h3>Reference</h3><p>[1] Mikolov, T., Chen, K., Corrado, G., &amp; Dean, J. (2013). Efficient estimation of word representations in vector space. Proceedings of the International Conference on Learning Representations (ICLR).</p><p>[2] E. Tighe, O. Aran, and C. Cheng, “Exploring Neural Network Approaches in Automatic Personality Recognition of Filipino Twitter Users,” De La Salle University Manila, 2023.</p><p>[3] Bojanowski, P., Grave, E., Joulin, A., &amp; Mikolov, T. (2017). Enriching word vectors with subword information. Transactions of the association for computational linguistics, 5, 135–146.</p><p>[4] T. Mikolov, E. Grave, P. Bojanowski, C. Puhrsch, and A. Joulin. Advances in Pre-Training Distributed Word Representations. Facebook AI Research, 2018.</p><p>[5] ReviewTag — Analyzing Amazon Negative Product Reviews using Deep Learning by Priyanka Kumari thesis under University of Houston Clear Lake.</p><p>[6] Figure created by the author of this post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12cccb9a5def" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon Review Data Transformation(Code) Part-2]]></title>
            <link>https://medium.com/@kumari01priyanka/amazon-review-data-transformation-code-part-2-e441af2f2c79?source=rss-cf9524f470e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e441af2f2c79</guid>
            <category><![CDATA[review]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Priyanka Kumari]]></dc:creator>
            <pubDate>Thu, 25 May 2023 19:55:43 GMT</pubDate>
            <atom:updated>2023-06-23T02:48:02.340Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdOmqG7Tx-S3udKWNbtEAw.png" /></figure><p><a href="https://medium.com/@kumari01priyanka/amazon-review-data-transformation-64fa38f9fd53">Amazon Review Data Transformation </a>in <a href="https://medium.com/@kumari01priyanka/amazon-review-data-transformation-64fa38f9fd53"><em>part-1</em></a> we learn about the theory in this post we will learn the coding.</p><p>The <a href="https://medium.com/@kumari01priyanka/ucsd-amazon-product-dataset-2018-e7613d5145b0"><em>UCSD Amazon product manually labeled dataset</em></a>, available on <a href="https://github.com/priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview/tree/main/Dataset/encoded_data">github link</a> below, dividing it into 9,637 entries for training and 2,416 entries for testing purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*tZwg7JJrLY2Aiwvkoxr1yw.png" /><figcaption>Dataset</figcaption></figure><h4>1. Vocab Tokenization</h4><p>Vocab Tokenization is basically used as CNN, LSTM, and RNN models input. The tokenizer function takes two arguments: the tokenizer and the maximum length of each tokenized sequence. The tokenizer function then uses the tokenizer to tokenize the reviewText column and returns a DataFrame with the tokenized sequences. The concat function then concatenates the tokenized sequences DataFrame with the original DataFrame, adding a new column called tokens and length of each tokenized sequence called length. Shown in figure Output of Tokenizer.</p><pre># Define the tokenizer to be used<br>tokenizer = torchtext.data.utils.get_tokenizer(&#39;basic_english&#39;)<br><br># Tokenize the reviewText column using a tokenizer function<br>df_train = pd.concat([df_train, df_train[&#39;reviewText&#39;].apply(tokenize_data, tokenizer=tokenizer, max_length=256).apply(pd.Series)], axis=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hq5EfK7UrfcLSJRtOLEcrA.png" /><figcaption>Output of Tokenizer</figcaption></figure><p>The numericalize_data function converts a tokenized example to a list of IDs. The special_tokens variable is a list of special tokens that are added to the vocabulary. The tokens variable is a list of all the tokens in the dataset. The vocab variable is a vocabulary object that maps tokens to IDs. The unk_index variable is the index of the &lt;unk&gt; token in the vocabulary. The pad_index variable is the index of the &lt;pad&gt; token in the vocabulary. The vocab.set_default_index(unk_index) line sets the default index for the vocabulary to the &lt;unk&gt; token. The df_train = pd.concat([df_train, df_train.apply(numericalize_data, vocab=vocab, axis=1).apply(pd.Series)], axis=1) line concatenates the ids column to the df_train DataFrame. This results in a DataFrame with a column for each token in the vocabulary and shown in figure numericalize_data.</p><pre>def numericalize_data(example, vocab):<br>    # Convert each token in the example to its corresponding ID from the vocabulary<br>    ids = [vocab[token] for token in example[&#39;tokens&#39;]]<br>    return {&#39;ids&#39;: ids}<br><br>special_tokens = [&#39;&lt;unk&gt;&#39;, &#39;&lt;pad&gt;&#39;]<br>tokens = df_train[&#39;tokens&#39;].tolist()<br><br># Build a vocabulary from the tokenized data with a minimum frequency and special tokens<br>vocab = torchtext.vocab.build_vocab_from_iterator(tokens, min_freq=5, specials=special_tokens)<br>unk_index = vocab[&#39;&lt;unk&gt;&#39;]<br>pad_index = vocab[&#39;&lt;pad&gt;&#39;]<br>vocab.set_default_index(unk_index)<br><br># Numericalize the tokenized data using the vocabulary<br>df_train = pd.concat([df_train, df_train.apply(numericalize_data, vocab=vocab, axis=1).apply(pd.Series)], axis=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bopz8zNdW0AP-1410I5ldQ.png" /><figcaption>numericalize_data</figcaption></figure><p>The train variable contains a list of dictionaries, each representing a single review. The ids key in each dictionary is the ID of the review, the length key is the length of the review, the target_list key is the value of the target_list column, and the reviewText key is the text of the review and shown in figure Vocab Tokenization Output. The df_train variable can then be used to train a natural language processing model such as CNN, LSTM, and RNN.</p><pre># Assign the value &#39;encoded_topic&#39; to the variable target_list<br>target_list = &#39;encoded_topic&#39;<br><br># Select specific columns from the df_train DataFrame<br>df_train = df_train[[&#39;ids&#39;, target_list, &#39;length&#39;, &#39;reviewText&#39;]]<br><br># Calculate the vocabulary size by getting the length of the vocab list<br>vocab_size = len(vocab)<br>output_dim = df_train[target_list].nunique()<br><br># Prepare data for training<br>train = df_train.apply(lambda row: {<br>    &#39;ids&#39;: row[&#39;ids&#39;],<br>    &#39;length&#39;: row[&#39;length&#39;],<br>    target_list: row[target_list],<br>    &#39;reviewText&#39;: row[&#39;reviewText&#39;]<br>}, axis=1).tolist()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRoaCR7CGN-7qq9r9p-eYA.png" /><figcaption>Vocab Tokenization Output</figcaption></figure><p>The batch_size variable is set to 64, meaning each batch will contain 64 examples. The collate_fn variable is set to a function that converts the batch dictionary into a format the model can use. The collate_fn function is created using the functools.partial function. The functools.partial function allows us to pass in the pad_index and target_list variables to the collate function. The collate function converts the data into a format the model can use. The DataLoader class creates a data loader to load the data in batches to help prevent the model from overfitting to the data.</p><pre>def collate(batch, pad_index,target_list):<br>    batch_ids = [torch.tensor(i[&#39;ids&#39;]) for i in batch]  # Convert ids list to tensor<br>    batch_ids = pad_sequence(batch_ids, padding_value=torch.tensor(pad_index), batch_first=True)<br>    batch_length = [torch.tensor(i[&#39;length&#39;]) for i in batch]  # Convert length list to tensor<br>    batch_length = torch.stack(batch_length)<br>    batch_label = [torch.tensor(i[target_list]) for i in batch]  # Convert reviewText list to tensor<br>    batch_label = torch.stack(batch_label)<br>    batch_text = [(i[&#39;reviewText&#39;]) for i in batch]<br>    batch = {&#39;ids&#39;: batch_ids,<br>             &#39;length&#39;: batch_length,<br>             target_list: batch_label,<br>             &#39;text&#39;: batch_text}<br>    return batch<br><br>batch_size = 64<br>collate_fn = functools.partial(collate, pad_index=pad_index, target_list=target_list)<br><br># Create data loaders for training and validation<br>train_dataloader = DataLoader(train, batch_size=batch_size, collate_fn=collate_fn, shuffle=True)</pre><h4>2. Ids and Masks Tokenizers</h4><p>Ids and Masks Tokenizers is basically used as for transformer models like DistilBERT and BERT. The pre-trained model is distillery-base-cased and provides a DistilBertTokenizer object. This tokenizer is created explicitly for DistilBert models and offers a smaller and faster alternative to the BERT tokenizer. Despite its smaller size, the DistilBertTokenizer can still deliver state-of-the-art performance on various natural language processing tasks.</p><p>Similarly, the pre-trained model roberta-base provides a BERT tokenizer. This tokenizer is designed for BERT models and is larger and more intricate than the DistilBertTokenizer. However, it also offers superior performance on various natural language processing tasks.</p><p>To efficiently load the data for training and inference, we utilize a DataLoader object for the training set and another DataLoader object for the test set. This DataLoader objects ensure that the data is efficiently loaded into memory. The train_batch_size and valid_batch_size parameters control the batch size, determining the number of samples loaded into memory.</p><pre>tokenizer = DistilBertTokenizer.from_pretrained(&#39;distilbert-base-cased&#39;)<br>train_loader, valid_loader = get_data_loaders(df_train, df_test, tokenizer, train_batch_size = 8, valid_batch_size = 8)</pre><p>The CustomDataset class is a PyTorch class that can be used to load and process custom datasets. The __init__ method of the class initializes the class variables. The __len__ method returns the length of the dataset. The __getitem__ method first uses the tokenizer to encode the text data. The tokenizer returns a dictionary containing the token IDs, attention mask, and token type IDs for the input sequence. The __getitem__ method then converts the token IDs, attention mask, and token type IDs to PyTorch tensors. The __getitem__ method also returns the original text of the input sequence.</p><pre>class CustomDataset(Dataset):<br>    def __init__(self, df, tokenizer, max_len):<br>        self.df = df<br>        self.max_len = max_len<br>        self.text = df.reviewText<br>        self.tokenizer = tokenizer<br>        self.targets = df[target_list].values<br><br>    def __len__(self):<br>        return len(self.df)<br>    <br>    def __getitem__(self, index):<br>        text = self.text[index]<br>        inputs = self.tokenizer.encode_plus(<br>            text,<br>            truncation=True,<br>            add_special_tokens=True,<br>            max_length=self.max_len,<br>            padding=&#39;max_length&#39;,<br>            return_token_type_ids=True<br>        )<br>        #the attention_masks and token type ids, everything is returned in a dictionary format<br>        ids = inputs[&#39;input_ids&#39;]<br>        mask = inputs[&#39;attention_mask&#39;]<br>        token_type_ids = inputs[&quot;token_type_ids&quot;]<br>        return {<br>            &#39;ids&#39;: torch.tensor(ids, dtype=torch.long),<br>            &#39;mask&#39;: torch.tensor(mask, dtype=torch.long),<br>            &#39;token_type_ids&#39;: torch.tensor(token_type_ids, dtype=torch.long),<br>            &#39;targets&#39;: torch.tensor(self.targets[index], dtype=torch.long),<br>            &#39;text&#39; : text<br>        }</pre><p>The get_data_loaders function takes in a train and validation dataframe, a tokenizer, and some hyperparameters, and returns a train and validation DataLoader. The DataLoaders are used to load the data in batches for training and evaluation.</p><p>The function first reads the train and validation dataframes into Pandas DataFrames. Then, it creates a CustomDataset object for each DataFrame. The CustomDataset object takes in the DataFrame, the tokenizer, and the max length, and creates a dataset that can be used to load the data in batches.</p><p>The function creates a DataLoader object for each CustomDataset object. The DataLoader objects take in the dataset, the batch size, the number of workers, the shuffle flag, and the pin memory flag. The shuffle flag controls whether the data is shuffled in the DataLoader, and the pin memory flag controls whether the data is loaded into GPU memory.</p><pre>def get_data_loaders(train_dataframe, valid_dataframe, tokenizer, max_len=512, train_batch_size=16, valid_batch_size=16, learning_rate=2e-5):<br><br>    Train_Dataframe = pd.read_csv(train_dataframe)<br>    Validation_Dataframe = pd.read_csv(valid_dataframe)<br>    train_dataset = CustomDataset(Train_Dataframe, tokenizer, max_len)<br>    valid_dataset = CustomDataset(Validation_Dataframe, tokenizer, max_len)<br>    train_loader = DataLoader(train_dataset, batch_size=train_batch_size,<br>                              num_workers=1, shuffle=True, pin_memory=True)<br>    valid_loader = DataLoader(valid_dataset, batch_size=valid_batch_size,<br>                              num_workers=1, shuffle=False, pin_memory=True)<br><br>    return train_loader, valid_loader</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTcuB5SnznT7_yVIg8UOMg.png" /><figcaption>Ids and Masks Tokenizers Output</figcaption></figure><h3>Reference</h3><p>[1] NLTK 3.6.3 documentation. (2021). Tokenization. Retrieved from <a href="https://www.nltk.org/api/nltk.tokenize.html#module-nltk.tokenize.">https://www.nltk.org/api/nltk.tokenize.html#module-nltk.tokenize.</a></p><p>[2] Transformer Tokenizer, Hugging Face, 2019: <a href="https://huggingface.co/tokenizers/">https://huggingface.co/tokenizers/</a></p><p>[3] Wolf, T., Debut, L., Sanh, V., Chaumond, J., Delangue, C., Moi, A., … &amp; Brew, J. (2019). HuggingFace’s transformers: State-of-the-art natural language processing. arXiv preprint arXiv:1910.03771.</p><p>[4] Loper, E., &amp; Bird, S. (2002). Nltk: The natural language toolkit. arXiv preprint cs/0205028</p><p>[5] ReviewTag — Analyzing Amazon Negative Product Reviews using Deep Learning by Priyanka Kumari thesis under University of Houston Clear Lake.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e441af2f2c79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Amazon Review Data Transformation Part-1]]></title>
            <link>https://medium.com/@kumari01priyanka/amazon-review-data-transformation-64fa38f9fd53?source=rss-cf9524f470e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/64fa38f9fd53</guid>
            <category><![CDATA[review]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[token]]></category>
            <dc:creator><![CDATA[Priyanka Kumari]]></dc:creator>
            <pubDate>Sun, 21 May 2023 03:24:45 GMT</pubDate>
            <atom:updated>2023-06-23T02:48:34.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fdOmqG7Tx-S3udKWNbtEAw.png" /></figure><p>The <a href="https://medium.com/@kumari01priyanka/ucsd-amazon-product-dataset-2018-e7613d5145b0"><em>UCSD Amazon product dataset</em></a> includes review text that has been manually tagged and categorized based on two main issues: Seller Issues and Product Issues. Each category is assigned a numerical label for easy identification, where label “0” represents Seller Issues, and label “1” corresponds to Product Issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hETDd8jx-ITT0updzTP5-w.png" /><figcaption><strong>Amazon review manually tag</strong></figcaption></figure><p>Manual tagging is preferred over automated tagging techniques because it allows human analysts to read and understand each review carefully, considering the overall sentiment, raised issues, and relevant topics. This approach ensures accurate and comprehensive tagging, considering the context and nuances of natural language.</p><p>Unlike automated tagging, which relies on algorithms that may struggle to grasp the complexities of language fully, manual tagging allows for a more thorough analysis of each review. Although manually tagging the data may take longer, the result is a more reliable and precise categorization of reviews based on specific criteria, such as product or seller issues.</p><h4><strong>Data Transformation</strong></h4><p>The Amazon product review manual tagged dataset has two columns: reviewText and tags, where reviewText includes the textual content of Amazon product reviews. However, deep learning algorithms require numerical inputs, so we must convert the reviewText data into a numerical format through tokenization.</p><p>Tokenization breaks down the text data into individual tokens or words and assigns each token a numerical value that can be used as input for deep learning models. There are two commonly used tokenizer libraries for natural language processing: NLTK Word Tokenizer [1] for Vocab Tokenization and Hugging Face Tokenizer [2, 3] for Ids and Masks Tokenization.</p><p>Vocab Tokenization is typically employed for LSTM, RNN, and CNN models, while Ids and Masks Tokenizers are used for BERT and DistilBERT models. Both tokenizers aim to capture as much information as possible from the input review text, ensuring effective processing for the respective deep-learning models.</p><ol><li>Vocab Tokenization</li><li>Ids and Masks Tokenizers</li></ol><p><strong>1. Vocab Tokenization:</strong></p><p>The NLTK Word Tokenizer is a Python module in the Natural Language Toolkit (NLTK) library that provides functionality for tokenizing text into individual words [4]. The NLTK Word Tokenizer is a natural language processing tool that leverages “basic English” to break down raw text data into individual words, phrases, and sentences [1]. The primary objective of a tokenizer is to convert unstructured text data into structured data that can be readily analyzed and processed by machine learning models. The tokenizer typically removes punctuation marks and special characters and segments the text into individual words. This process helps to organize the text data and make it more manageable and structured for efficient analysis by machine learning models. In the upcoming section, we will perform text tokenization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hu70fhM4EEmjoTFuP_ADhQ.png" /><figcaption><strong>Figure<em> 1: Text Tokenization</em></strong></figcaption></figure><p>The process of tokenizing text involves several steps, as shown in Figure 1. The four main steps involved in creating a tokenized text are reviewText, tokenizer, vocab, and ids. First, to analyze text data, we need to use a tokenizer to break it down into smaller units of meaning, such as words or parts of words. Tokenization involves taking the text and dividing it into individual tokens. Figure 1depicts the tokenization process, where the sentence “The gloves are of very poor quality.” is transformed into individual tokens, [‘The’, ‘gloves’, ‘are’, ‘of’, ‘very’, ‘poor’, ‘quality’, ‘.’]. The figure also shows reviewText1, reviewText2, … reviewText9642, passed through a tokenizer to generate tokenizer1, tokenizer2…tokenizer9642.</p><p>Once we have broken down the text into individual tokens, we can generate a vocabulary or vocab comprising all the unique tokens. Figure 1 shows an example vocab that consists of eleven words, including two special reserved words. The first reserved word, “&lt;unk&gt;”, is a placeholder for unknown words that the tokenizer cannot include in the vocab. The second reserved word, “&lt;pad&gt;”, is used to pad token sequences to a fixed length. The remaining nine words represent the actual tokens in the text. Our task is to tokenize the reviewText, which contains 9642 instances, likely to have repeated words, making the overall vocab smaller than the total number of tokens. In this example, the vocab has 4773 words, with the first few reserved for special purposes, such as unknown and padding words. These special reserved words have specific identifiers that enable us to represent the text as a sequence of integers.</p><p>Finally, each token is assigned a unique identifier or id to represent the text as a sequence of integers. In this figure 1, we have assigned the Ids [2, 3, 4, 5, 6, 7, 8] to the tokens in our vocab, starting from the third word, “The”, which has an id of 2, and ending with the token “fake”, which has an id of 10. These ids represent the reviewText data, such as reviewText1, reviewText2, … reviewText9642, which is converted into a sequence of ids1, ids2… ids9642.</p><p>We focus is on padding input ids and creating batches, as shown in Figure 2, which illustrates the flow from input ids to batches. Deep learning models require inputs to be of equal length, while naturally, input ids can have varying lengths as different texts may have different lengths. To address this, we will pad the input ids with zeros to make them uniform, with a maximum length of 256. If an id is shorter than 256, we add zeros; if it is longer, we truncate it. This process is called padding, and we will apply it to all 9642 input ids, resulting in a padded dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGQ-h99ebKPOKomon9IuQw.png" /><figcaption><strong>Figure<em> 2: Padding Ids and batch</em></strong></figcaption></figure><p>In the previous section, we discussed the importance of padding input ids and creating batches for deep learning models. In Figure 2, we divide the padded ids into 150 batches, with each batch consisting of 64 padded ids. Batches offer several advantages:</p><p>• It efficiently uses memory during training by avoiding loading the entire dataset simultaneously.</p><p>• It speeds up the learning process by enabling the model to update parameters more frequently by simultaneously processing smaller subsets of data.</p><p>• It helps to avoid overfitting by exposing the model to a more diverse set of examples in each iteration.</p><p><strong>2. Ids and Masks Tokenizers</strong></p><p>Tokenization is critical in preparing text data for machine learning models in NLP. It involves breaking down a text into its constituent words or sub words to enable the model to analyze it. The Hugging Face Tokenizer is a Python package for natural language processing that provides tokenization functionality for various state-of-the-art transformer models, including BERT and DistilBERT [2, 3]. The library that offers state-of-the-art tokenization techniques based on transformer models. One of its critical features is the ability to fine-tune the techniques to perform topic tagging, a crucial capability for deep learning models. We can explore customer issues and preferences by applying Tokenizers to Amazon’s Negative Product Reviews and identify recurring patterns or concerns.</p><p>Ids and Masks is dedicated to discussing input ids and masks for transformer models, such as BERT and DistilBERT batches. Figure 3 illustrates the primary components involved, which include reviewText, ids, and masks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-OZvonWM0B2uvtQrTAqIoQ.png" /><figcaption><strong>Figure 3: <em>Ids and Masks</em></strong></figcaption></figure><p>The mask tokenizer adds a special “mask” token to the input sequence, instructing the model to ignore specific input tokens during training. Transformer models require inputs to have equal length, thus we use a tokenizer such as Roberta-base or DistilBERT-base-uncased to convert reviewText into ids and masks. The total number of reviewText is 9642, resulting in 9642 ids and masks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6JSbew_ki2yaWBLnwIp2g.png" /><figcaption><strong><em>Figure 4: Ids Batches(left) and Masks Batches(right)</em></strong></figcaption></figure><p>Figure 4, the left-hand side, illustrates the input ID batches, an ID matrix, and ID batches. The tokenizer assigns each token in the input text a unique ID, enabling the model to comprehend the text. The right-hand side displays the Masks batches, which consist of input masks, a mask matrix, and mask batches. A unique mask token is appended to the input sequence during tokenization, indicating the model ignores specific input tokens during training.</p><p>The 9642 input IDs and masks into 150 batches, each comprising 64 masks. Batch processing offers several advantages, such as efficient memory utilization, faster learning, and a reduced risk of overfitting. We can train our deep learning models effectively and achieve more accurate results by utilizing batch processing.</p><p>For code refere to <a href="https://medium.com/@kumari01priyanka/amazon-review-data-transformation-code-part-2-e441af2f2c79">Amazon Review Data Transformation(Code) Part-2</a>.</p><h4>Reference</h4><p>[1] NLTK 3.6.3 documentation. (2021). Tokenization. Retrieved from <a href="https://www.nltk.org/api/nltk.tokenize.html#module-nltk.tokenize.">https://www.nltk.org/api/nltk.tokenize.html#module-nltk.tokenize.</a></p><p>[2] Transformer Tokenizer, Hugging Face, 2019: <a href="https://huggingface.co/tokenizers/">https://huggingface.co/tokenizers/</a></p><p>[3] Wolf, T., Debut, L., Sanh, V., Chaumond, J., Delangue, C., Moi, A., … &amp; Brew, J. (2019). HuggingFace’s transformers: State-of-the-art natural language processing. arXiv preprint arXiv:1910.03771.</p><p>[4] Loper, E., &amp; Bird, S. (2002). Nltk: The natural language toolkit. arXiv preprint cs/0205028</p><p>[5] ReviewTag — Analyzing Amazon Negative Product Reviews using Deep Learning by Priyanka Kumari thesis under University of Houston Clear Lake.</p><p>[6] Figure created by the author of this post, adapted from the <a href="https://medium.com/@kumari01priyanka/amazon-review-data-transformation-code-part-2-e441af2f2c79">provided code.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64fa38f9fd53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UCSD Amazon Product Dataset(2018)]]></title>
            <link>https://medium.com/@kumari01priyanka/ucsd-amazon-product-dataset-2018-e7613d5145b0?source=rss-cf9524f470e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7613d5145b0</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[text-review]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[review]]></category>
            <category><![CDATA[amazon-reviews]]></category>
            <dc:creator><![CDATA[Priyanka Kumari]]></dc:creator>
            <pubDate>Wed, 17 May 2023 15:22:13 GMT</pubDate>
            <atom:updated>2023-06-23T02:49:03.256Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dO7yxdzNXkpOSKdcC9X64A.png" /></figure><ol><li>Amazon Product Data</li><li>Dataset Source</li><li>Dataset Download</li></ol><h3>1. Amazon product data:</h3><p>Amazon product data refers to the information and details associated with products listed and sold on the Amazon marketplace. It includes various attributes and data points such as reviews, overall ratings, and so on, providing a comprehensive product description.</p><p>The USCD Dataset is an updated version of the Amazon review dataset initially released in 2014. This revised version of Amazon product data for 2018 offers several enhancements and additional features compared to its predecessor [1]. Here are the key improvements:</p><ol><li><strong>Increased Review Count:</strong> The dataset now includes 233.1 million reviews, a significant increase from the 142.8 million reviews in 2014.</li><li><strong>Extended Time Range:</strong> The dataset covers a broader time range, incorporating reviews from May 1996 to October 2018, allowing for more comprehensive analysis across different periods.</li><li><strong>Enriched Metadata:</strong> Transaction metadata has been added for each review, providing valuable information about the product, which includes details such as product color (e.g., white or black), size (e.g., large or small), package type (e.g., hardcover or electronics), and more.</li><li><strong>Enhanced Product Information:</strong> The dataset now includes bullet-point descriptions under the product title, a technical details table with attribute-value pairs, and a table displaying similar products.</li></ol><p>The data is formatted as one review per line in JSON (JavaScript Object Notation). This format allows for easy parsing and processing of the data. Here is an example of a sample review in JSON format:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VMpvbAq9ENOHM2Qzgyr-g.png" /><figcaption>Sample Review (<a href="https://nijianmo.github.io/amazon/index.html">source</a>)</figcaption></figure><h3>2. Source:</h3><p>Access the UCSD Amazon dataset through the provided <a href="https://nijianmo.github.io/amazon/index.html">link</a>, which contains 29 categories across different industries and products, such as Clothing Shoes and Jewelry, Books, CDs and Vinyl, Toys and Games, and Video Games [1].</p><p>To obtain the data download link:</p><ol><li>Click on the “reviews” link next to the category name.</li><li>Fill out the form and click on the “Submit” button.</li><li>A page will appear with a link to download the data for the category.</li></ol><h3>3. Download:</h3><p>The Amazon product data of the USCD download by using the <a href="https://github.com/priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview/blob/main/Dataset/Dataset.ipynb">Colab link</a>.</p><p><a href="https://github.com/priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview/blob/main/Dataset/Dataset.ipynb">ReviewTag_TaggingAmazonNegReview/Dataset.ipynb at main · priyanka-kumari-01/ReviewTag_TaggingAmazonNegReview</a></p><h4><strong>3.1 Downloading Dataset from UCSD:</strong></h4><p>The Clothing Shoes and Jewelry dataset was downloaded using SSL and saved in Gzip format.</p><ul><li><strong>SSL:</strong> Secure Sockets Layer (SSL) is a cryptographic protocol that provides communication security over the Internet. It protects data from being intercepted and read by unauthorized parties.</li><li><strong>Gzip:</strong> Gzip is a lossless compression format that is commonly used to reduce the size of files. It works by identifying and removing redundant data from the file.</li></ul><pre>import urllib.request<br>import ssl<br><br>url = &#39;https://datarepo.eng.ucsd.edu/mcauley_group/data/amazon_v2/categoryFiles/Clothing_Shoes_and_Jewelry.json.gz&#39;<br><br># Create a context with SSL certificate verification disabled<br>context = ssl.create_default_context()<br>context.check_hostname = False<br>context.verify_mode = ssl.CERT_NONE<br><br># Download the file with SSL certificate verification disabled<br>with urllib.request.urlopen(url, context=context) as u, open(&#39;Clothing_Shoes_and_Jewelry.json.gz&#39;, &#39;wb&#39;) as f:<br>    f.write(u.read())</pre><h4>3.2 Converting UCSD Dataset (Gzip) to JSON:</h4><p>The code reads a gzipped JSON file, extracts specific fields, and writes the extracted data to a new JSON file.</p><pre>import os<br>import json<br>import gzip<br>import pandas as pd<br>from urllib.request import urlopen<br><br>### load the meta data<br>array= []<br>count = 1<br><br># Create a JSON file to store the extracted data<br>jsonFile = open(&quot;/content/Clothing_Shoes_and_Jewelry_Rating_catergory.json&quot;, &quot;w&quot;)<br>jsonFile.write(&quot;[&quot;) # Opening bracket to denote a list of JSON objects<br><br># Open the gzipped file and extract the required fields<br>with gzip.open(&#39;/content/Clothing_Shoes_and_Jewelry.json.gz&#39;) as f:<br>    for l in f:   <br>        # Load each line as a JSON object<br>        d = json.loads(l.strip())  <br><br>        # Check if the required fields are present in the JSON object    <br>        if &#39;reviewText&#39; in d and &#39;asin&#39; in d and &#39;overall&#39; in d and &#39;reviewerID&#39; in d and &#39;summary&#39; in d:<br>            et_dict = {&quot;asin&quot;:  d[&quot;asin&quot;], <br>                        &quot;overall&quot; : d[&quot;overall&quot;],<br>                        &quot;reviewText&quot; : d[&quot;reviewText&quot;],<br>                        &quot;reviewerID&quot; : d[&quot;reviewerID&quot;],<br>                        &quot;summary&quot; : d[&quot;summary&quot;],}<br>            # Append the extracted fields to the array            <br>            array.append(et_dict)<br>            # Convert the dictionary to a JSON string<br>            jsonString = json.dumps(et_dict)+&quot;,\n&quot;<br>            # Write the JSON string to the file<br>            jsonFile.write(jsonString)<br><br># Closing bracket to denote the end of the list of JSON objects<br>jsonFile.write(&quot;]&quot;)<br># Close the JSON file<br>jsonFile.close()</pre><h4>Reference:</h4><p>[1] J. McAuley, “Amazon product data,” University of California San Diego (UCSD).</p><p>[2] McAuley, J., Shi, Q., Targett, C., &amp; van den Hengel, A. (2015). Image-based recommendations on styles and substitutes. In Proceedings of the 38th International ACM SIGIR Conference on Research and Development in Information Retrieval (pp. 43–52).</p><p>[3] He, R., &amp; McAuley, J. (2016). Ups and downs: Modeling the visual evolution of fashion trends with one-class collaborative filtering. In Proceedings of the 25th International Conference on World Wide Web (pp. 507–517).</p><p>[4] ReviewTag — Analyzing Amazon Negative Product Reviews using Deep Learning by Priyanka Kumari thesis under University of Houston Clear Lake.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7613d5145b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>