import streamlit as st # Custom CSS for better styling st.markdown(""" """, unsafe_allow_html=True) # Introduction to BERT Annotators in Spark NLP st.markdown('
Introduction to BERT Annotators in Spark NLP
', unsafe_allow_html=True) st.markdown("""

Spark NLP provides a range of BERT-based annotators that leverage the power of Bidirectional Encoder Representations from Transformers (BERT) for various natural language processing tasks. These annotators are designed to deliver high performance and scalability in production environments. Below, we provide a detailed overview of four key BERT-based annotators available in Spark NLP:

""", unsafe_allow_html=True) st.write("") tab1, tab2, tab3, tab4 = st.tabs(["BERT for Token Classification", "BERT for Zero-Shot Classification", "BERT for Sequence Classification", "BERT for Question Answering"]) with tab1: st.markdown("""

BERT for Token Classification

The BertForTokenClassification annotator is fine-tuned for Named Entity Recognition (NER) tasks. Token classification involves labeling tokens, which are the smallest units of meaning in a text, with tags that represent specific entities. This process is crucial for understanding and extracting valuable information from text data. By identifying entities like names of people, organizations, locations, and more, token classification enables a wide range of applications, including:

This annotator is highly effective for applications requiring precise entity recognition, ensuring that the identified entities are accurate and contextually relevant.

Entity Label
Apple ORGANIZATION
Steve Jobs PERSON
California LOCATION
""", unsafe_allow_html=True) # BERT Token Classification - NER CoNLL st.markdown('
BERT Token Classification - NER CoNLL
', unsafe_allow_html=True) st.markdown("""

The bert_base_token_classifier_conll03 is a fine-tuned BERT model ready to use for Named Entity Recognition (NER) tasks. This model recognizes four types of entities: location (LOC), organizations (ORG), person (PER), and Miscellaneous (MISC).

""", unsafe_allow_html=True) # How to Use the Model - Token Classification st.markdown('
How to Use the Model
', unsafe_allow_html=True) st.code(''' from sparknlp.base import * from sparknlp.annotator import * from pyspark.ml import Pipeline from pyspark.sql.functions import col, expr document_assembler = DocumentAssembler() \\ .setInputCol('text') \\ .setOutputCol('document') sentence_detector = SentenceDetector() \\ .setInputCols(['document']) \\ .setOutputCol('sentence') tokenizer = Tokenizer() \\ .setInputCols(['sentence']) \\ .setOutputCol('token') tokenClassifier = BertForTokenClassification \\ .pretrained('bert_base_token_classifier_conll03', 'en') \\ .setInputCols(['token', 'sentence']) \\ .setOutputCol('ner') \\ .setCaseSensitive(True) \\ .setMaxSentenceLength(512) ner_converter = NerConverter() \\ .setInputCols(['sentence', 'token', 'ner']) \\ .setOutputCol('entities') pipeline = Pipeline(stages=[ document_assembler, sentence_detector, tokenizer, tokenClassifier, ner_converter ]) example = spark.createDataFrame([["""Apple Inc. is planning to open a new headquarters in Cupertino, California. The CEO, Tim Cook, announced this during the company's annual event on March 25th, 2023. Barack Obama, the 44th President of the United States, was born on August 4th, 1961, in Honolulu, Hawaii. He attended Harvard Law School and later became a community organizer in Chicago. Amazon reported a net revenue of $125.6 billion in Q4 of 2022, an increase of 9% compared to the previous year. Jeff Bezos, the founder of Amazon, mentioned that the company's growth in cloud computing has significantly contributed to this rise. Paris, the capital city of France, is renowned for its art, fashion, and culture. Key attractions include the Eiffel Tower, the Louvre Museum, and the Notre-Dame Cathedral. Visitors often enjoy a stroll along the Seine River and dining at local bistros. The study, conducted at the Mayo Clinic in Rochester, Minnesota, examined the effects of a new drug on patients with Type 2 diabetes. Results showed a significant reduction in blood sugar levels over a 12-month period. Serena Williams won her 24th Grand Slam title at the Wimbledon Championships in London, England. She defeated Naomi Osaka in a thrilling final match on July 13th, 2023. Google's latest smartphone, the Pixel 6, was unveiled at an event in New York City. Sundar Pichai, the CEO of Google, highlighted the phone's advanced AI capabilities and improved camera features. The Declaration of Independence was signed on July 4th, 1776, in Philadelphia, Pennsylvania. Thomas Jefferson, Benjamin Franklin, and John Adams were among the key figures who drafted this historic document."""]]).toDF("text") result = pipeline.fit(example).transform(example) result.select( expr("explode(entities) as ner_chunk") ).select( col("ner_chunk.result").alias("chunk"), col("ner_chunk.metadata.entity").alias("ner_label") ).show(truncate=False) ''', language='python') st.text(""" +--------------------+---------+ |chunk |ner_label| +--------------------+---------+ |Apple Inc. |ORG | |Cupertino |LOC | |California |LOC | |Tim Cook |PER | |Barack Obama |PER | |United States |LOC | |Honolulu |LOC | |Hawaii |LOC | |Harvard Law School |ORG | |Chicago |LOC | |Amazon |ORG | |Jeff Bezos |PER | |Amazon |ORG | |Paris |LOC | |France |LOC | |Eiffel Tower |LOC | |Louvre Museum |LOC | |Notre-Dame Cathedral|LOC | |Seine River |LOC | |Mayo Clinic |ORG | +--------------------+---------+ """) # Model Information - Token Classification st.markdown('
Model Information
', unsafe_allow_html=True) st.markdown("""
Attribute Description
Model Name bert_base_token_classifier_conll03
Compatibility Spark NLP 3.2.0+
License Open Source
Edition Official
Input Labels [token, document]
Output Labels [ner]
Language en
Size 404.3 MB
Case sensitive true
Max sentence length 512
""", unsafe_allow_html=True) # References - Token Classification st.markdown('
References
', unsafe_allow_html=True) st.markdown("""
""", unsafe_allow_html=True) with tab2: st.markdown("""

BERT for Zero-Shot Classification

The BertForZeroShotClassification annotator is designed to classify text into labels it has not seen during training. This is achieved using natural language inference (NLI) to determine the relationship between input text and potential labels. This capability is essential for applications where predefined categories are either unavailable or frequently change. Zero-shot classification is particularly useful for:

By leveraging this annotator, you can ensure flexibility and adaptability in text classification tasks, making it suitable for ever-changing data environments.

Text Predicted Category
"The new iPhone has amazing features" Technology
"The economic growth has been significant this year" Finance
""", unsafe_allow_html=True) # BERT Zero-Shot Classification Base - MNLI st.markdown('
BERT Zero-Shot Classification Base - MNLI
', unsafe_allow_html=True) st.markdown("""

The bert_zero_shot_classifier_mnli model is designed for zero-shot text classification, making it suitable for scenarios where predefined categories are not available or frequently change. This model is fine-tuned on the MNLI dataset and leverages natural language inference (NLI) to determine relationships between input text and candidate labels. It allows for dynamic classification without a fixed number of classes, providing flexibility and adaptability for various applications.

""", unsafe_allow_html=True) # How to Use the Model - Zero-Shot Classification st.markdown('
How to Use the Model
', unsafe_allow_html=True) st.code(''' from sparknlp.base import * from sparknlp.annotator import * from pyspark.ml import Pipeline document_assembler = DocumentAssembler() \\ .setInputCol('text') \\ .setOutputCol('document') tokenizer = Tokenizer() \\ .setInputCols(['document']) \\ .setOutputCol('token') zeroShotClassifier = BertForZeroShotClassification \\ .pretrained('bert_zero_shot_classifier_mnli', 'xx') \\ .setInputCols(['token', 'document']) \\ .setOutputCol('class') \\ .setCaseSensitive(True) \\ .setMaxSentenceLength(512) \\ .setCandidateLabels(["urgent", "mobile", "travel", "movie", "music", "sport", "weather", "technology"]) pipeline = Pipeline(stages=[ document_assembler, tokenizer, zeroShotClassifier ]) example = spark.createDataFrame([['In today’s world, staying updated with urgent information is crucial as events can unfold rapidly and require immediate attention.']]).toDF("text") result = pipeline.fit(example).transform(example) result.select('document.result', 'class.result').show(truncate=False) ''', language='python') st.text(""" +------------------------------------------------------------------------------------------------------------------------------------+--------+ |result |result | +------------------------------------------------------------------------------------------------------------------------------------+--------+ |[In today’s world, staying updated with urgent information is crucial as events can unfold rapidly and require immediate attention.]|[urgent]| +------------------------------------------------------------------------------------------------------------------------------------+--------+ """) # Model Information - Zero-Shot Classification st.markdown('
Model Information
', unsafe_allow_html=True) st.markdown("""
Attribute Description
Model Name bert_zero_shot_classifier_mnli
Compatibility Spark NLP 5.2.4+
License Open Source
Edition Official
Input Labels [token, document]
Output Labels [label]
Language xx
Size 409.1 MB
Case sensitive true
""", unsafe_allow_html=True) # References - Zero-Shot Classification st.markdown('
References
', unsafe_allow_html=True) st.markdown("""
""", unsafe_allow_html=True) with tab3: st.markdown("""

BERT for Sequence Classification

The BertForSequenceClassification annotator is fine-tuned to classify entire sequences of text. This involves understanding the context of the entire sequence, which is crucial for tasks that require a holistic view of the input text. Sequence classification is highly effective for:

With its ability to deliver accurate classification results, this annotator is widely used in various text analysis applications.

Text Predicted Sentiment
"I love this product, it's fantastic!" Positive
"The service was terrible, I'm very disappointed." Negative
""", unsafe_allow_html=True) # English BertForSequenceClassification Cased model (from yonichi) st.markdown('
English BertForSequenceClassification Cased model (from yonichi)
', unsafe_allow_html=True) st.markdown("""

The bert_classifier_cbert model is a pretrained BertForSequenceClassification model. Adapted from Hugging Face and curated for scalability and production-readiness using Spark NLP, this model is designed for sequence classification tasks such as sentiment analysis. It is capable of classifying text into positive, negative, and neutral sentiments, providing valuable insights for various applications.

""", unsafe_allow_html=True) # How to Use the Model - Sequence Classification st.markdown('
How to Use the Model
', unsafe_allow_html=True) st.code(''' from sparknlp.base import * from sparknlp.annotator import * from pyspark.ml import Pipeline from pyspark.sql.functions import col, expr # Document Assembler document_assembler = DocumentAssembler() \\ .setInputCol('text') \\ .setOutputCol('document') # Sentence Detector sentence_detector = SentenceDetector() \\ .setInputCols(['document']) \\ .setOutputCol('sentence') # Tokenizer tokenizer = Tokenizer() \\ .setInputCols(['sentence']) \\ .setOutputCol('token') # Sequence Classifier sequence_classifier = BertForSequenceClassification.pretrained("bert_classifier_cbert", "en") \\ .setInputCols(['sentence', 'token']) \\ .setOutputCol('class') # Pipeline pipeline = Pipeline(stages=[ document_assembler, sentence_detector, tokenizer, sequence_classifier ]) # Create example DataFrame example = spark.createDataFrame([("Apple Inc. is planning to open a new headquarters in Cupertino, California. The CEO, Tim Cook, announced this during the company's annual event on March 25th, 2023. Barack Obama, the 44th President of the United States, was born on August 4th, 1961, in Honolulu, Hawaii. He attended Harvard Law School and later became a community organizer in Chicago. Amazon reported a net revenue of $125.6 billion in Q4 of 2022, an increase of 9% compared to the previous year. Jeff Bezos, the founder of Amazon, mentioned that the company's growth in cloud computing has significantly contributed to this rise. Paris, the capital city of France, is renowned for its art, fashion, and culture. Key attractions include the Eiffel Tower, the Louvre Museum, and the Notre-Dame Cathedral. Visitors often enjoy a stroll along the Seine River and dining at local bistros. The study, conducted at the Mayo Clinic in Rochester, Minnesota, examined the effects of a new drug on patients with Type 2 diabetes. Results showed a significant reduction in blood sugar levels over a 12-month period. Serena Williams won her 24th Grand Slam title at the Wimbledon Championships in London, England. She defeated Naomi Osaka in a thrilling final match on July 13th, 2023. Google's latest smartphone, the Pixel 6, was unveiled at an event in New York City. Sundar Pichai, the CEO of Google, highlighted the phone's advanced AI capabilities and improved camera features. The Declaration of Independence was signed on July 4th, 1776, in Philadelphia, Pennsylvania. Thomas Jefferson, Benjamin Franklin, and John Adams were among the key figures who drafted this historic document.",)], ["text"]) # Fit and transform the data model = pipeline.fit(example) result = model.transform(example) from pyspark.sql.functions import col # Show results in a structured format for sentence-based classification result.select( col('sentence.result').alias('sentences'), col('class.result').alias('classifications') ).rdd.flatMap(lambda row: list(zip(row['sentences'], row['classifications']))).toDF(['sentence', 'classification']).show(truncate=False) ''', language='python') st.text(""" +-------------------------------------------------------------------------------------------------------------------------------------+--------------+ |sentence |classification| +-------------------------------------------------------------------------------------------------------------------------------------+--------------+ |Apple Inc. is planning to open a new headquarters in Cupertino, California. |Neutral | |The CEO, Tim Cook, announced this during the company's annual event on March 25th, 2023. |Dovish | |Barack Obama, the 44th President of the United States, was born on August 4th, 1961, in Honolulu, Hawaii. |Neutral | |He attended Harvard Law School and later became a community organizer in Chicago. |Neutral | |Amazon reported a net revenue of $125.6 billion in Q4 of 2022, an increase of 9% compared to the previous year. |Neutral | |Jeff Bezos, the founder of Amazon, mentioned that the company's growth in cloud computing has significantly contributed to this rise.|Dovish | |Paris, the capital city of France, is renowned for its art, fashion, and culture. |Neutral | |Key attractions include the Eiffel Tower, the Louvre Museum, and the Notre-Dame Cathedral. |Neutral | |Visitors often enjoy a stroll along the Seine River and dining at local bistros. |Neutral | |The study, conducted at the Mayo Clinic in Rochester, Minnesota, examined the effects of a new drug on patients with Type 2 diabetes.|Dovish | |Results showed a significant reduction in blood sugar levels over a 12-month period. |Neutral | |Serena Williams won her 24th Grand Slam title at the Wimbledon Championships in London, England. |Hawkish | |She defeated Naomi Osaka in a thrilling final match on July 13th, 2023. |Neutral | |Google's latest smartphone, the Pixel 6, was unveiled at an event in New York City. |Dovish | |Sundar Pichai, the CEO of Google, highlighted the phone's advanced AI capabilities and improved camera features. |Dovish | |The Declaration of Independence was signed on July 4th, 1776, in Philadelphia, Pennsylvania. |Hawkish | |Thomas Jefferson, Benjamin Franklin, and John Adams were among the key figures who drafted this historic document. |Neutral | +-------------------------------------------------------------------------------------------------------------------------------------+--------------+ """) # Model Information - Sequence Classification st.markdown('
Model Information
', unsafe_allow_html=True) st.markdown("""
Attribute Description
Model Name bert_classifier_cbert
Compatibility Spark NLP 4.2.0+
License Open Source
Edition Official
Input Labels [document, token]
Output Labels [class]
Language en
Size 412.2 MB
Case sensitive true
Max sentence length 256
""", unsafe_allow_html=True) # References - Sequence Classification st.markdown('
References
', unsafe_allow_html=True) st.markdown("""
""", unsafe_allow_html=True) with tab4: st.markdown("""

BERT for Question Answering

The BertForQuestionAnswering annotator is fine-tuned to provide answers to questions based on a given context. This involves extracting relevant information from a passage of text in response to a specific query, making it ideal for applications requiring precise information retrieval. Question answering is particularly useful for:

By leveraging this annotator, you can enhance the ability to extract and deliver accurate information from text data.

Context Question Predicted Answer
"The Eiffel Tower is one of the most recognizable structures in the world. It was constructed in 1889 as the entrance arch to the 1889 World's Fair held in Paris, France." "When was the Eiffel Tower constructed?" 1889
"The Amazon rainforest, also known as Amazonia, is a vast tropical rainforest in South America. It is home to an incredible diversity of flora and fauna." "What is the Amazon rainforest also known as?" Amazonia
""", unsafe_allow_html=True) # English BertForQuestionAnswering Large Uncased Model st.markdown('
bert_qa_large_uncased_whole_word_masking_finetuned_squad
', unsafe_allow_html=True) st.markdown("""

This model is a pretrained BERT model, adapted from Hugging Face, curated to provide scalability and production-readiness using Spark NLP. It is designed to handle question-answering tasks effectively.

""", unsafe_allow_html=True) # How to Use the Model - Question Answering st.markdown('
How to Use the Model
', unsafe_allow_html=True) st.code(''' from sparknlp.base import * from sparknlp.annotator import * from pyspark.ml import Pipeline from pyspark.sql.functions import col, expr # Document Assembler document_assembler = MultiDocumentAssembler()\\ .setInputCols(["question", "context"]) \\ .setOutputCols(["document_question", "document_context"]) # BertForQuestionAnswering spanClassifier = BertForQuestionAnswering.pretrained("bert_qa_large_uncased_whole_word_masking_finetuned_squad","en") \\ .setInputCols(["document_question", "document_context"]) \\ .setOutputCol("answer") \\ .setCaseSensitive(True) # Pipeline pipeline = Pipeline().setStages([ document_assembler, spanClassifier ]) # Create example DataFrame example = spark.createDataFrame([["What's my name?", "My name is Clara and I live in Berkeley."]]).toDF("question", "context") # Fit and transform the data model = pipeline.fit(example) result = model.transform(example) # Show results result.select('document_question.result', 'answer.result').show(truncate=False) ''', language='python') st.text(""" +-----------------+-------+ |result |result | +-----------------+-------+ |[What's my name?]|[Clara]| +-----------------+-------+ """) # Model Information - Question Answering st.markdown('
Model Information
', unsafe_allow_html=True) st.markdown("""
Attribute Description
Model Name bert_qa_large_uncased_whole_word_masking_finetuned_squad
Compatibility Spark NLP 4.4.0+
License Open Source
Edition Official
Input Labels [document_question, document_context]
Output Labels [answer]
Language en
Size 1.3 GB
Case sensitive false
Max sentence length 512
""", unsafe_allow_html=True) # References - Question Answering st.markdown('
References
', unsafe_allow_html=True) st.markdown("""
""", unsafe_allow_html=True) st.markdown("""

Conclusion

In this guide, we've explored a range of BERT-based annotators and models available in Spark NLP, each tailored to specific natural language processing tasks. Here's a summary of the four key BERT annotators and their respective models:

Each of these models and annotators demonstrates the versatility and power of BERT-based approaches in natural language processing. Whether you need to classify sequences, identify entities, handle zero-shot classification, or answer questions, Spark NLP provides robust tools to enhance your text analysis capabilities. Leveraging these models allows for scalable and production-ready solutions in various applications, from sentiment analysis to dynamic content tagging.

""", unsafe_allow_html=True) # Community & Support st.markdown('
Community & Support
', unsafe_allow_html=True) st.markdown("""
""", unsafe_allow_html=True)