File size: 13,368 Bytes
1086b7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
import streamlit as st

# Custom CSS for better styling
st.markdown("""
    <style>
        .main-title {
            font-size: 36px;
            color: #4A90E2;
            font-weight: bold;
            text-align: center;
        }
        .sub-title {
            font-size: 24px;
            color: #4A90E2;
            margin-top: 20px;
        }
        .section {
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: 10px;
            margin-top: 20px;
        }
        .section h2 {
            font-size: 22px;
            color: #4A90E2;
        }
        .section p, .section ul {
            color: #666666;
        }
        .link {
            color: #4A90E2;
            text-decoration: none;
        }
    </style>
""", unsafe_allow_html=True)

# Main Title
st.markdown('<div class="main-title">State-of-the-Art Named Entity Recognition with Spark NLP (Portuguese)</div>', unsafe_allow_html=True)

# Introduction
st.markdown("""
<div class="section">
    <p>Named Entity Recognition (NER) is the task of identifying important words in a text and associating them with a category. For example, we may be interested in finding all the personal names in documents, or company names in news articles. Other examples include domain-specific uses such as identifying all disease names in a clinical text, or company trading codes in financial ones.</p>
    <p>NER can be implemented with many approaches. In this post, we introduce a deep learning-based method using the NerDL model. This approach leverages the scalability of Spark NLP with Python.</p>
</div>
""", unsafe_allow_html=True)

# Introduction to Spark NLP
st.markdown('<div class="sub-title">Introduction to Spark NLP</div>', unsafe_allow_html=True)
st.markdown("""
<div class="section">
    <p>Spark NLP is an open-source library maintained by John Snow Labs. It is built on top of Apache Spark and Spark ML and provides simple, performant & accurate NLP annotations for machine learning pipelines that can scale easily in a distributed environment.</p>
    <p>To install Spark NLP, you can simply use any package manager like conda or pip. For example, using pip you can simply run <code>pip install spark-nlp</code>. For different installation options, check the official <a href="https://nlp.johnsnowlabs.com/docs/en/install" target="_blank" class="link">documentation</a>.</p>
</div>
""", unsafe_allow_html=True)

# Using NerDL Model
st.markdown('<div class="sub-title">Using NerDL Model</div>', unsafe_allow_html=True)
st.markdown("""
<div class="section">
    <p>The NerDL model in Spark NLP is a deep learning-based approach for NER tasks. It uses a Char CNNs - BiLSTM - CRF architecture that achieves state-of-the-art results in most datasets. The training data should be a labeled Spark DataFrame in the format of CoNLL 2003 IOB with annotation type columns.</p>
</div>
""", unsafe_allow_html=True)

# Setup Instructions
st.markdown('<div class="sub-title">Setup</div>', unsafe_allow_html=True)
st.markdown('<p>To install Spark NLP in Python, use your favorite package manager (conda, pip, etc.). For example:</p>', unsafe_allow_html=True)
st.code("""
pip install spark-nlp
pip install pyspark
""", language="bash")

st.markdown("<p>Then, import Spark NLP and start a Spark session:</p>", unsafe_allow_html=True)
st.code("""
import sparknlp

# Start Spark Session
spark = sparknlp.start()
""", language='python')

# Example Usage with NerDL Model in Italian
st.markdown('<div class="sub-title">Example Usage with NerDL Model in portuguese</div>', unsafe_allow_html=True)
st.markdown("""
<div class="section">
    <p>Below is an example of how to set up and use the NerDL model for named entity recognition in portuguese:</p>
</div>
""", 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, round, concat, lit

# Document Assembler
document_assembler = DocumentAssembler() \\
    .setInputCol("text") \\
    .setOutputCol("document")

# Tokenizer
tokenizer = Tokenizer() \\
    .setInputCols(["document"]) \\
    .setOutputCol("token")

# Word Embeddings
embeddings = WordEmbeddingsModel.pretrained('glove_840B_300', lang='xx') \\
    .setInputCols(["document", "token"]) \\
    .setOutputCol("embeddings")

# NerDL Model
ner_model = NerDLModel.pretrained('ner_wikiner_glove_840B_300', 'xx') \\
    .setInputCols(["document", "token", "embeddings"]) \\
    .setOutputCol("ner")

# NER Converter
ner_converter = NerConverter() \\
    .setInputCols(["document", "token", "ner"]) \\
    .setOutputCol("ner_chunk")

# Pipeline
pipeline = Pipeline(stages=[
    document_assembler,
    tokenizer,
    embeddings,
    ner_model,
    ner_converter
])

# Example sentence
example = """
A cidade de Lisboa, capital de Portugal, é uma das mais antigas do mundo. Com uma história rica que remonta a mais de três mil anos, Lisboa tem sido um importante centro cultural, econômico e político na Europa. A cidade é famosa por seus bairros históricos, como Alfama, Bairro Alto e Belém.
Fernando Pessoa, um dos maiores poetas da língua portuguesa, nasceu em Lisboa em 1888. Sua obra é amplamente estudada e apreciada tanto em Portugal quanto internacionalmente. Outro escritor famoso, José Saramago, vencedor do Prêmio Nobel de Literatura, também tem fortes ligações com a cidade.
O Rio Tejo atravessa Lisboa, criando uma bela paisagem que atrai turistas de todo o mundo. Perto do rio, encontra-se a Torre de Belém, uma das atrações turísticas mais visitadas da cidade. Este monumento é um símbolo da Era dos Descobrimentos de Portugal.
Em termos econômicos, Lisboa é o maior centro financeiro de Portugal. Muitas empresas multinacionais têm escritórios na cidade, como a Microsoft, a Google e a Nestlé. Além disso, Lisboa é sede de várias startups de tecnologia, beneficiando-se de um ambiente empreendedor vibrante.
A educação também é uma área importante em Lisboa. A cidade abriga algumas das melhores universidades do país, incluindo a Universidade de Lisboa e a Universidade Nova de Lisboa. Estas instituições são conhecidas por sua pesquisa de ponta e por formar alguns dos profissionais mais qualificados de Portugal.
No mundo do esporte, o Sport Lisboa e Benfica e o Sporting Clube de Portugal são os dois principais clubes de futebol da cidade. Ambos têm uma longa história de sucesso em competições nacionais e internacionais. O estádio do Benfica, o Estádio da Luz, é um dos maiores e mais modernos de Portugal.
Lisboa também é conhecida por sua gastronomia. Pratos tradicionais como o bacalhau à brás e os pastéis de nata são famosos em todo o país e no mundo. Os mercados de alimentos, como o Mercado da Ribeira, oferecem uma variedade de produtos frescos e pratos típicos que refletem a rica cultura culinária da cidade.
Além disso, eventos culturais, como o Festival de Fado e a Festa de Santo António, atraem milhares de visitantes todos os anos. Estes eventos celebram a música, a dança e as tradições populares de Lisboa, reforçando o papel da cidade como um importante centro cultural.
Recentemente, Lisboa tem se destacado como um destino turístico de primeira linha. A cidade foi eleita várias vezes como o "Melhor Destino Europeu" pelos World Travel Awards. Suas belas paisagens, clima agradável e rica herança cultural fazem de Lisboa um destino imperdível para viajantes de todo o mundo.
"""
data = spark.createDataFrame([[example]]).toDF("text")

# Transforming data
result = pipeline.fit(data).transform(data)

# Select the result, entity, and confidence columns
result.select(
    expr("explode(ner_chunk) as ner_chunk")
).select(
    col("ner_chunk.result").alias("result"),
    col("ner_chunk.metadata").getItem("entity").alias("entity"),
    concat(
        round((col("ner_chunk.metadata").getItem("confidence").cast("float") * 100), 2),
        lit("%")
    ).alias("confidence")
).show(truncate=False)
''', language="python")

st.text("""
+--------------------------+------+----------+
|result                    |entity|confidence|
+--------------------------+------+----------+
|Lisboa                    |LOC   |88.48%    |
|Portugal                  |LOC   |90.64%    |
|Lisboa                    |LOC   |99.55%    |
|Europa                    |LOC   |97.55%    |
|Alfama                    |LOC   |96.97%    |
|Bairro Alto               |LOC   |76.44%    |
|Belém                     |LOC   |95.85%    |
|Fernando Pessoa           |LOC   |77.32%    |
|Lisboa                    |LOC   |94.97%    |
|Portugal                  |LOC   |90.94%    |
|José Saramago             |PER   |73.39%    |
|Prêmio Nobel de Literatura|MISC  |47.64%    |
|Rio Tejo                  |LOC   |73.64%    |
|Lisboa                    |LOC   |96.04%    |
|Perto                     |LOC   |88.33%    |
|Torre de Belém            |LOC   |80.21%    |
|Era dos Descobrimentos    |LOC   |63.05%    |
|Portugal                  |LOC   |72.65%    |
|Lisboa                    |LOC   |99.28%    |
|Portugal                  |LOC   |88.78%    |
+--------------------------+------+----------+
""")

# Benchmark Section
st.markdown('<div class="sub-title">Benchmark</div>', unsafe_allow_html=True)
st.markdown("""
<div class="section">
    <p>Evaluating the performance of NER models is crucial to understanding their effectiveness in real-world applications. Below are the benchmark results for the "ner_wikiner_glove_840B_300" model on <strong>portuguese</strong> text, focusing on various named entity categories. The metrics used include precision, recall, and F1-score, which are standard for evaluating classification models.</p>
</div>
""", unsafe_allow_html=True)
st.markdown("""
---
#### Classification Report

| Label | Precision | Recall | F1-Score | Support |
|-------|-----------|--------|----------|---------|
| B-LOC | 0.91      | 0.94   | 0.92     | 14818   |
| I-ORG | 0.84      | 0.74   | 0.79     | 1705    |
| I-LOC | 0.89      | 0.88   | 0.89     | 8354    |
| I-PER | 0.94      | 0.93   | 0.93     | 4338    |
| B-ORG | 0.90      | 0.77   | 0.83     | 2351    |
| B-PER | 0.92      | 0.93   | 0.93     | 6398    |

#### Averages

| Metric         | Precision | Recall | F1-Score | Support |
|----------------|-----------|--------|----------|---------|
| Micro Average  | 0.90      | 0.90   | 0.90     | 37964   |
| Macro Average  | 0.90      | 0.87   | 0.88     | 37964   |
| Weighted Avg   | 0.90      | 0.90   | 0.90     | 37964   |

#### Overall Metrics

- Processed 348,966 tokens with 26,513 phrases; found: 26,359 phrases; correct: 23,574.
- Accuracy (non-O): **88.48%**
- Overall Accuracy: **98.39%**
- Precision: **89.43%**
- Recall: **88.91%**
- F1 Score: **89.17**

#### Entity-Specific Metrics

| Entity | Precision | Recall | F1-Score | Instances |
|--------|-----------|--------|----------|-----------|
| LOC    | 89.52%    | 92.60% | 91.04    | 15328     |
| MISC   | 84.55%    | 72.47% | 78.05    | 2525      |
| ORG    | 88.53%    | 75.84% | 81.70    | 2014      |
| PER    | 91.40%    | 92.75% | 92.07    | 6492      |
---
""", unsafe_allow_html=True)

# Summary
st.markdown('<div class="sub-title">Summary</div>', unsafe_allow_html=True)
st.markdown("""
<div class="section">
    <p>In this article, we discussed named entity recognition using a deep learning-based method with the "wikiner_840B_300" model for Italian. We introduced how to perform the task using the open-source Spark NLP library with Python, which can be used at scale in the Spark ecosystem. These methods can be used for natural language processing applications in various fields, including finance and healthcare.</p>
</div>
""", unsafe_allow_html=True)

# References
st.markdown('<div class="sub-title">References</div>', unsafe_allow_html=True)
st.markdown("""
<div class="section">
    <ul>
        <li><a class="link" href="https://sparknlp.org/api/python/reference/autosummary/sparknlp/annotator/ner/ner_dl/index.html" target="_blank" rel="noopener">NerDLModel</a> annotator documentation</li>
        <li>Model Used: <a class="link" href="https://sparknlp.org/2021/07/19/ner_wikiner_glove_840B_300_xx.html" target="_blank" rel="noopener">ner_wikiner_glove_840B_300</a></li>
        <li><a class="link" href="https://nlp.johnsnowlabs.com/recognize_entitie" target="_blank" rel="noopener">Visualization demos for NER in Spark NLP</a></li>
        <li><a class="link" href="https://www.johnsnowlabs.com/named-entity-recognition-ner-with-bert-in-spark-nlp/">Named Entity Recognition (NER) with BERT in Spark NLP</a></li>
    </ul>
</div>
""", unsafe_allow_html=True)

# Community & Support
st.markdown('<div class="sub-title">Community & Support</div>', unsafe_allow_html=True)
st.markdown("""
<div class="section">
    <ul>
        <li><a class="link" href="https://sparknlp.org/" target="_blank">Official Website</a>: Documentation and examples</li>
        <li><a class="link" href="https://join.slack.com/t/spark-nlp/shared_invite/zt-198dipu77-L3UWNe_AJf4Rqb3DaMb-7A" target="_blank">Slack Community</a>: Connect with other Spark NLP users</li>
        <li><a class="link" href="https://github.com/JohnSnowLabs/spark-nlp" target="_blank">GitHub Repository</a>: Source code and issue tracker</li>
    </ul>
</div>
""", unsafe_allow_html=True)