Spaces:
Sleeping
Sleeping
Update pages/Workflow & Model Overview.py
Browse files- pages/Workflow & Model Overview.py +264 -264
pages/Workflow & Model Overview.py
CHANGED
@@ -1,264 +1,264 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
|
3 |
-
# Custom CSS for better styling
|
4 |
-
st.markdown("""
|
5 |
-
<style>
|
6 |
-
.main-title {
|
7 |
-
font-size: 36px;
|
8 |
-
color: #4A90E2;
|
9 |
-
font-weight: bold;
|
10 |
-
text-align: center;
|
11 |
-
}
|
12 |
-
.sub-title {
|
13 |
-
font-size: 24px;
|
14 |
-
color: #4A90E2;
|
15 |
-
margin-top: 20px;
|
16 |
-
}
|
17 |
-
.section {
|
18 |
-
background-color: #f9f9f9;
|
19 |
-
padding: 15px;
|
20 |
-
border-radius: 10px;
|
21 |
-
margin-top: 20px;
|
22 |
-
}
|
23 |
-
.section h2 {
|
24 |
-
font-size: 22px;
|
25 |
-
color: #4A90E2;
|
26 |
-
}
|
27 |
-
.section p, .section ul {
|
28 |
-
color: #666666;
|
29 |
-
}
|
30 |
-
.link {
|
31 |
-
color: #4A90E2;
|
32 |
-
text-decoration: none;
|
33 |
-
}
|
34 |
-
</style>
|
35 |
-
""", unsafe_allow_html=True)
|
36 |
-
|
37 |
-
# Main Title
|
38 |
-
st.markdown('<div class="main-title">State-of-the-Art Named Entity Recognition with Spark NLP (
|
39 |
-
|
40 |
-
# Introduction
|
41 |
-
st.markdown("""
|
42 |
-
<div class="section">
|
43 |
-
<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>
|
44 |
-
<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>
|
45 |
-
</div>
|
46 |
-
""", unsafe_allow_html=True)
|
47 |
-
|
48 |
-
# Introduction to Spark NLP
|
49 |
-
st.markdown('<div class="sub-title">Introduction to Spark NLP</div>', unsafe_allow_html=True)
|
50 |
-
st.markdown("""
|
51 |
-
<div class="section">
|
52 |
-
<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>
|
53 |
-
<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>
|
54 |
-
</div>
|
55 |
-
""", unsafe_allow_html=True)
|
56 |
-
|
57 |
-
# Using NerDL Model
|
58 |
-
st.markdown('<div class="sub-title">Using NerDL Model</div>', unsafe_allow_html=True)
|
59 |
-
st.markdown("""
|
60 |
-
<div class="section">
|
61 |
-
<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>
|
62 |
-
</div>
|
63 |
-
""", unsafe_allow_html=True)
|
64 |
-
|
65 |
-
# Setup Instructions
|
66 |
-
st.markdown('<div class="sub-title">Setup</div>', unsafe_allow_html=True)
|
67 |
-
st.markdown('<p>To install Spark NLP in Python, use your favorite package manager (conda, pip, etc.). For example:</p>', unsafe_allow_html=True)
|
68 |
-
st.code("""
|
69 |
-
pip install spark-nlp
|
70 |
-
pip install pyspark
|
71 |
-
""", language="bash")
|
72 |
-
|
73 |
-
st.markdown("<p>Then, import Spark NLP and start a Spark session:</p>", unsafe_allow_html=True)
|
74 |
-
st.code("""
|
75 |
-
import sparknlp
|
76 |
-
|
77 |
-
# Start Spark Session
|
78 |
-
spark = sparknlp.start()
|
79 |
-
""", language='python')
|
80 |
-
|
81 |
-
# Example Usage with NerDL Model in Italian
|
82 |
-
st.markdown('<div class="sub-title">Example Usage with NerDL Model in portuguese</div>', unsafe_allow_html=True)
|
83 |
-
st.markdown("""
|
84 |
-
<div class="section">
|
85 |
-
<p>Below is an example of how to set up and use the NerDL model for named entity recognition in portuguese:</p>
|
86 |
-
</div>
|
87 |
-
""", unsafe_allow_html=True)
|
88 |
-
st.code('''
|
89 |
-
from sparknlp.base import *
|
90 |
-
from sparknlp.annotator import *
|
91 |
-
from pyspark.ml import Pipeline
|
92 |
-
from pyspark.sql.functions import col, expr, round, concat, lit
|
93 |
-
|
94 |
-
# Document Assembler
|
95 |
-
document_assembler = DocumentAssembler() \\
|
96 |
-
.setInputCol("text") \\
|
97 |
-
.setOutputCol("document")
|
98 |
-
|
99 |
-
# Tokenizer
|
100 |
-
tokenizer = Tokenizer() \\
|
101 |
-
.setInputCols(["document"]) \\
|
102 |
-
.setOutputCol("token")
|
103 |
-
|
104 |
-
# Word Embeddings
|
105 |
-
embeddings = WordEmbeddingsModel.pretrained('glove_840B_300', lang='xx') \\
|
106 |
-
.setInputCols(["document", "token"]) \\
|
107 |
-
.setOutputCol("embeddings")
|
108 |
-
|
109 |
-
# NerDL Model
|
110 |
-
ner_model = NerDLModel.pretrained('ner_wikiner_glove_840B_300', 'xx') \\
|
111 |
-
.setInputCols(["document", "token", "embeddings"]) \\
|
112 |
-
.setOutputCol("ner")
|
113 |
-
|
114 |
-
# NER Converter
|
115 |
-
ner_converter = NerConverter() \\
|
116 |
-
.setInputCols(["document", "token", "ner"]) \\
|
117 |
-
.setOutputCol("ner_chunk")
|
118 |
-
|
119 |
-
# Pipeline
|
120 |
-
pipeline = Pipeline(stages=[
|
121 |
-
document_assembler,
|
122 |
-
tokenizer,
|
123 |
-
embeddings,
|
124 |
-
ner_model,
|
125 |
-
ner_converter
|
126 |
-
])
|
127 |
-
|
128 |
-
# Example sentence
|
129 |
-
example = """
|
130 |
-
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.
|
131 |
-
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.
|
132 |
-
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.
|
133 |
-
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.
|
134 |
-
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.
|
135 |
-
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
|
136 |
-
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.
|
137 |
-
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.
|
138 |
-
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.
|
139 |
-
"""
|
140 |
-
data = spark.createDataFrame([[example]]).toDF("text")
|
141 |
-
|
142 |
-
# Transforming data
|
143 |
-
result = pipeline.fit(data).transform(data)
|
144 |
-
|
145 |
-
# Select the result, entity, and confidence columns
|
146 |
-
result.select(
|
147 |
-
expr("explode(ner_chunk) as ner_chunk")
|
148 |
-
).select(
|
149 |
-
col("ner_chunk.result").alias("result"),
|
150 |
-
col("ner_chunk.metadata").getItem("entity").alias("entity"),
|
151 |
-
concat(
|
152 |
-
round((col("ner_chunk.metadata").getItem("confidence").cast("float") * 100), 2),
|
153 |
-
lit("%")
|
154 |
-
).alias("confidence")
|
155 |
-
).show(truncate=False)
|
156 |
-
''', language="python")
|
157 |
-
|
158 |
-
st.text("""
|
159 |
-
+--------------------------+------+----------+
|
160 |
-
|result |entity|confidence|
|
161 |
-
+--------------------------+------+----------+
|
162 |
-
|Lisboa |LOC |88.48% |
|
163 |
-
|Portugal |LOC |90.64% |
|
164 |
-
|Lisboa |LOC |99.55% |
|
165 |
-
|Europa |LOC |97.55% |
|
166 |
-
|Alfama |LOC |96.97% |
|
167 |
-
|Bairro Alto |LOC |76.44% |
|
168 |
-
|Belém |LOC |95.85% |
|
169 |
-
|Fernando Pessoa |LOC |77.32% |
|
170 |
-
|Lisboa |LOC |94.97% |
|
171 |
-
|Portugal |LOC |90.94% |
|
172 |
-
|José Saramago |PER |73.39% |
|
173 |
-
|Prêmio Nobel de Literatura|MISC |47.64% |
|
174 |
-
|Rio Tejo |LOC |73.64% |
|
175 |
-
|Lisboa |LOC |96.04% |
|
176 |
-
|Perto |LOC |88.33% |
|
177 |
-
|Torre de Belém |LOC |80.21% |
|
178 |
-
|Era dos Descobrimentos |LOC |63.05% |
|
179 |
-
|Portugal |LOC |72.65% |
|
180 |
-
|Lisboa |LOC |99.28% |
|
181 |
-
|Portugal |LOC |88.78% |
|
182 |
-
+--------------------------+------+----------+
|
183 |
-
""")
|
184 |
-
|
185 |
-
# Benchmark Section
|
186 |
-
st.markdown('<div class="sub-title">Benchmark</div>', unsafe_allow_html=True)
|
187 |
-
st.markdown("""
|
188 |
-
<div class="section">
|
189 |
-
<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>
|
190 |
-
</div>
|
191 |
-
""", unsafe_allow_html=True)
|
192 |
-
st.markdown("""
|
193 |
-
---
|
194 |
-
#### Classification Report
|
195 |
-
|
196 |
-
| Label | Precision | Recall | F1-Score | Support |
|
197 |
-
|-------|-----------|--------|----------|---------|
|
198 |
-
| B-LOC | 0.91 | 0.94 | 0.92 | 14818 |
|
199 |
-
| I-ORG | 0.84 | 0.74 | 0.79 | 1705 |
|
200 |
-
| I-LOC | 0.89 | 0.88 | 0.89 | 8354 |
|
201 |
-
| I-PER | 0.94 | 0.93 | 0.93 | 4338 |
|
202 |
-
| B-ORG | 0.90 | 0.77 | 0.83 | 2351 |
|
203 |
-
| B-PER | 0.92 | 0.93 | 0.93 | 6398 |
|
204 |
-
|
205 |
-
#### Averages
|
206 |
-
|
207 |
-
| Metric | Precision | Recall | F1-Score | Support |
|
208 |
-
|----------------|-----------|--------|----------|---------|
|
209 |
-
| Micro Average | 0.90 | 0.90 | 0.90 | 37964 |
|
210 |
-
| Macro Average | 0.90 | 0.87 | 0.88 | 37964 |
|
211 |
-
| Weighted Avg | 0.90 | 0.90 | 0.90 | 37964 |
|
212 |
-
|
213 |
-
#### Overall Metrics
|
214 |
-
|
215 |
-
- Processed 348,966 tokens with 26,513 phrases; found: 26,359 phrases; correct: 23,574.
|
216 |
-
- Accuracy (non-O): **88.48%**
|
217 |
-
- Overall Accuracy: **98.39%**
|
218 |
-
- Precision: **89.43%**
|
219 |
-
- Recall: **88.91%**
|
220 |
-
- F1 Score: **89.17**
|
221 |
-
|
222 |
-
#### Entity-Specific Metrics
|
223 |
-
|
224 |
-
| Entity | Precision | Recall | F1-Score | Instances |
|
225 |
-
|--------|-----------|--------|----------|-----------|
|
226 |
-
| LOC | 89.52% | 92.60% | 91.04 | 15328 |
|
227 |
-
| MISC | 84.55% | 72.47% | 78.05 | 2525 |
|
228 |
-
| ORG | 88.53% | 75.84% | 81.70 | 2014 |
|
229 |
-
| PER | 91.40% | 92.75% | 92.07 | 6492 |
|
230 |
-
---
|
231 |
-
""", unsafe_allow_html=True)
|
232 |
-
|
233 |
-
# Summary
|
234 |
-
st.markdown('<div class="sub-title">Summary</div>', unsafe_allow_html=True)
|
235 |
-
st.markdown("""
|
236 |
-
<div class="section">
|
237 |
-
<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>
|
238 |
-
</div>
|
239 |
-
""", unsafe_allow_html=True)
|
240 |
-
|
241 |
-
# References
|
242 |
-
st.markdown('<div class="sub-title">References</div>', unsafe_allow_html=True)
|
243 |
-
st.markdown("""
|
244 |
-
<div class="section">
|
245 |
-
<ul>
|
246 |
-
<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>
|
247 |
-
<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>
|
248 |
-
<li><a class="link" href="https://nlp.johnsnowlabs.com/recognize_entitie" target="_blank" rel="noopener">Visualization demos for NER in Spark NLP</a></li>
|
249 |
-
<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>
|
250 |
-
</ul>
|
251 |
-
</div>
|
252 |
-
""", unsafe_allow_html=True)
|
253 |
-
|
254 |
-
# Community & Support
|
255 |
-
st.markdown('<div class="sub-title">Community & Support</div>', unsafe_allow_html=True)
|
256 |
-
st.markdown("""
|
257 |
-
<div class="section">
|
258 |
-
<ul>
|
259 |
-
<li><a class="link" href="https://sparknlp.org/" target="_blank">Official Website</a>: Documentation and examples</li>
|
260 |
-
<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>
|
261 |
-
<li><a class="link" href="https://github.com/JohnSnowLabs/spark-nlp" target="_blank">GitHub Repository</a>: Source code and issue tracker</li>
|
262 |
-
</ul>
|
263 |
-
</div>
|
264 |
-
""", unsafe_allow_html=True)
|
|
|
1 |
+
import streamlit as st
|
2 |
+
|
3 |
+
# Custom CSS for better styling
|
4 |
+
st.markdown("""
|
5 |
+
<style>
|
6 |
+
.main-title {
|
7 |
+
font-size: 36px;
|
8 |
+
color: #4A90E2;
|
9 |
+
font-weight: bold;
|
10 |
+
text-align: center;
|
11 |
+
}
|
12 |
+
.sub-title {
|
13 |
+
font-size: 24px;
|
14 |
+
color: #4A90E2;
|
15 |
+
margin-top: 20px;
|
16 |
+
}
|
17 |
+
.section {
|
18 |
+
background-color: #f9f9f9;
|
19 |
+
padding: 15px;
|
20 |
+
border-radius: 10px;
|
21 |
+
margin-top: 20px;
|
22 |
+
}
|
23 |
+
.section h2 {
|
24 |
+
font-size: 22px;
|
25 |
+
color: #4A90E2;
|
26 |
+
}
|
27 |
+
.section p, .section ul {
|
28 |
+
color: #666666;
|
29 |
+
}
|
30 |
+
.link {
|
31 |
+
color: #4A90E2;
|
32 |
+
text-decoration: none;
|
33 |
+
}
|
34 |
+
</style>
|
35 |
+
""", unsafe_allow_html=True)
|
36 |
+
|
37 |
+
# Main Title
|
38 |
+
st.markdown('<div class="main-title">State-of-the-Art Named Entity Recognition with Spark NLP (Portuguese)</div>', unsafe_allow_html=True)
|
39 |
+
|
40 |
+
# Introduction
|
41 |
+
st.markdown("""
|
42 |
+
<div class="section">
|
43 |
+
<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>
|
44 |
+
<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>
|
45 |
+
</div>
|
46 |
+
""", unsafe_allow_html=True)
|
47 |
+
|
48 |
+
# Introduction to Spark NLP
|
49 |
+
st.markdown('<div class="sub-title">Introduction to Spark NLP</div>', unsafe_allow_html=True)
|
50 |
+
st.markdown("""
|
51 |
+
<div class="section">
|
52 |
+
<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>
|
53 |
+
<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>
|
54 |
+
</div>
|
55 |
+
""", unsafe_allow_html=True)
|
56 |
+
|
57 |
+
# Using NerDL Model
|
58 |
+
st.markdown('<div class="sub-title">Using NerDL Model</div>', unsafe_allow_html=True)
|
59 |
+
st.markdown("""
|
60 |
+
<div class="section">
|
61 |
+
<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>
|
62 |
+
</div>
|
63 |
+
""", unsafe_allow_html=True)
|
64 |
+
|
65 |
+
# Setup Instructions
|
66 |
+
st.markdown('<div class="sub-title">Setup</div>', unsafe_allow_html=True)
|
67 |
+
st.markdown('<p>To install Spark NLP in Python, use your favorite package manager (conda, pip, etc.). For example:</p>', unsafe_allow_html=True)
|
68 |
+
st.code("""
|
69 |
+
pip install spark-nlp
|
70 |
+
pip install pyspark
|
71 |
+
""", language="bash")
|
72 |
+
|
73 |
+
st.markdown("<p>Then, import Spark NLP and start a Spark session:</p>", unsafe_allow_html=True)
|
74 |
+
st.code("""
|
75 |
+
import sparknlp
|
76 |
+
|
77 |
+
# Start Spark Session
|
78 |
+
spark = sparknlp.start()
|
79 |
+
""", language='python')
|
80 |
+
|
81 |
+
# Example Usage with NerDL Model in Italian
|
82 |
+
st.markdown('<div class="sub-title">Example Usage with NerDL Model in portuguese</div>', unsafe_allow_html=True)
|
83 |
+
st.markdown("""
|
84 |
+
<div class="section">
|
85 |
+
<p>Below is an example of how to set up and use the NerDL model for named entity recognition in portuguese:</p>
|
86 |
+
</div>
|
87 |
+
""", unsafe_allow_html=True)
|
88 |
+
st.code('''
|
89 |
+
from sparknlp.base import *
|
90 |
+
from sparknlp.annotator import *
|
91 |
+
from pyspark.ml import Pipeline
|
92 |
+
from pyspark.sql.functions import col, expr, round, concat, lit
|
93 |
+
|
94 |
+
# Document Assembler
|
95 |
+
document_assembler = DocumentAssembler() \\
|
96 |
+
.setInputCol("text") \\
|
97 |
+
.setOutputCol("document")
|
98 |
+
|
99 |
+
# Tokenizer
|
100 |
+
tokenizer = Tokenizer() \\
|
101 |
+
.setInputCols(["document"]) \\
|
102 |
+
.setOutputCol("token")
|
103 |
+
|
104 |
+
# Word Embeddings
|
105 |
+
embeddings = WordEmbeddingsModel.pretrained('glove_840B_300', lang='xx') \\
|
106 |
+
.setInputCols(["document", "token"]) \\
|
107 |
+
.setOutputCol("embeddings")
|
108 |
+
|
109 |
+
# NerDL Model
|
110 |
+
ner_model = NerDLModel.pretrained('ner_wikiner_glove_840B_300', 'xx') \\
|
111 |
+
.setInputCols(["document", "token", "embeddings"]) \\
|
112 |
+
.setOutputCol("ner")
|
113 |
+
|
114 |
+
# NER Converter
|
115 |
+
ner_converter = NerConverter() \\
|
116 |
+
.setInputCols(["document", "token", "ner"]) \\
|
117 |
+
.setOutputCol("ner_chunk")
|
118 |
+
|
119 |
+
# Pipeline
|
120 |
+
pipeline = Pipeline(stages=[
|
121 |
+
document_assembler,
|
122 |
+
tokenizer,
|
123 |
+
embeddings,
|
124 |
+
ner_model,
|
125 |
+
ner_converter
|
126 |
+
])
|
127 |
+
|
128 |
+
# Example sentence
|
129 |
+
example = """
|
130 |
+
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.
|
131 |
+
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.
|
132 |
+
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.
|
133 |
+
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.
|
134 |
+
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.
|
135 |
+
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.
|
136 |
+
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.
|
137 |
+
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.
|
138 |
+
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.
|
139 |
+
"""
|
140 |
+
data = spark.createDataFrame([[example]]).toDF("text")
|
141 |
+
|
142 |
+
# Transforming data
|
143 |
+
result = pipeline.fit(data).transform(data)
|
144 |
+
|
145 |
+
# Select the result, entity, and confidence columns
|
146 |
+
result.select(
|
147 |
+
expr("explode(ner_chunk) as ner_chunk")
|
148 |
+
).select(
|
149 |
+
col("ner_chunk.result").alias("result"),
|
150 |
+
col("ner_chunk.metadata").getItem("entity").alias("entity"),
|
151 |
+
concat(
|
152 |
+
round((col("ner_chunk.metadata").getItem("confidence").cast("float") * 100), 2),
|
153 |
+
lit("%")
|
154 |
+
).alias("confidence")
|
155 |
+
).show(truncate=False)
|
156 |
+
''', language="python")
|
157 |
+
|
158 |
+
st.text("""
|
159 |
+
+--------------------------+------+----------+
|
160 |
+
|result |entity|confidence|
|
161 |
+
+--------------------------+------+----------+
|
162 |
+
|Lisboa |LOC |88.48% |
|
163 |
+
|Portugal |LOC |90.64% |
|
164 |
+
|Lisboa |LOC |99.55% |
|
165 |
+
|Europa |LOC |97.55% |
|
166 |
+
|Alfama |LOC |96.97% |
|
167 |
+
|Bairro Alto |LOC |76.44% |
|
168 |
+
|Belém |LOC |95.85% |
|
169 |
+
|Fernando Pessoa |LOC |77.32% |
|
170 |
+
|Lisboa |LOC |94.97% |
|
171 |
+
|Portugal |LOC |90.94% |
|
172 |
+
|José Saramago |PER |73.39% |
|
173 |
+
|Prêmio Nobel de Literatura|MISC |47.64% |
|
174 |
+
|Rio Tejo |LOC |73.64% |
|
175 |
+
|Lisboa |LOC |96.04% |
|
176 |
+
|Perto |LOC |88.33% |
|
177 |
+
|Torre de Belém |LOC |80.21% |
|
178 |
+
|Era dos Descobrimentos |LOC |63.05% |
|
179 |
+
|Portugal |LOC |72.65% |
|
180 |
+
|Lisboa |LOC |99.28% |
|
181 |
+
|Portugal |LOC |88.78% |
|
182 |
+
+--------------------------+------+----------+
|
183 |
+
""")
|
184 |
+
|
185 |
+
# Benchmark Section
|
186 |
+
st.markdown('<div class="sub-title">Benchmark</div>', unsafe_allow_html=True)
|
187 |
+
st.markdown("""
|
188 |
+
<div class="section">
|
189 |
+
<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>
|
190 |
+
</div>
|
191 |
+
""", unsafe_allow_html=True)
|
192 |
+
st.markdown("""
|
193 |
+
---
|
194 |
+
#### Classification Report
|
195 |
+
|
196 |
+
| Label | Precision | Recall | F1-Score | Support |
|
197 |
+
|-------|-----------|--------|----------|---------|
|
198 |
+
| B-LOC | 0.91 | 0.94 | 0.92 | 14818 |
|
199 |
+
| I-ORG | 0.84 | 0.74 | 0.79 | 1705 |
|
200 |
+
| I-LOC | 0.89 | 0.88 | 0.89 | 8354 |
|
201 |
+
| I-PER | 0.94 | 0.93 | 0.93 | 4338 |
|
202 |
+
| B-ORG | 0.90 | 0.77 | 0.83 | 2351 |
|
203 |
+
| B-PER | 0.92 | 0.93 | 0.93 | 6398 |
|
204 |
+
|
205 |
+
#### Averages
|
206 |
+
|
207 |
+
| Metric | Precision | Recall | F1-Score | Support |
|
208 |
+
|----------------|-----------|--------|----------|---------|
|
209 |
+
| Micro Average | 0.90 | 0.90 | 0.90 | 37964 |
|
210 |
+
| Macro Average | 0.90 | 0.87 | 0.88 | 37964 |
|
211 |
+
| Weighted Avg | 0.90 | 0.90 | 0.90 | 37964 |
|
212 |
+
|
213 |
+
#### Overall Metrics
|
214 |
+
|
215 |
+
- Processed 348,966 tokens with 26,513 phrases; found: 26,359 phrases; correct: 23,574.
|
216 |
+
- Accuracy (non-O): **88.48%**
|
217 |
+
- Overall Accuracy: **98.39%**
|
218 |
+
- Precision: **89.43%**
|
219 |
+
- Recall: **88.91%**
|
220 |
+
- F1 Score: **89.17**
|
221 |
+
|
222 |
+
#### Entity-Specific Metrics
|
223 |
+
|
224 |
+
| Entity | Precision | Recall | F1-Score | Instances |
|
225 |
+
|--------|-----------|--------|----------|-----------|
|
226 |
+
| LOC | 89.52% | 92.60% | 91.04 | 15328 |
|
227 |
+
| MISC | 84.55% | 72.47% | 78.05 | 2525 |
|
228 |
+
| ORG | 88.53% | 75.84% | 81.70 | 2014 |
|
229 |
+
| PER | 91.40% | 92.75% | 92.07 | 6492 |
|
230 |
+
---
|
231 |
+
""", unsafe_allow_html=True)
|
232 |
+
|
233 |
+
# Summary
|
234 |
+
st.markdown('<div class="sub-title">Summary</div>', unsafe_allow_html=True)
|
235 |
+
st.markdown("""
|
236 |
+
<div class="section">
|
237 |
+
<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>
|
238 |
+
</div>
|
239 |
+
""", unsafe_allow_html=True)
|
240 |
+
|
241 |
+
# References
|
242 |
+
st.markdown('<div class="sub-title">References</div>', unsafe_allow_html=True)
|
243 |
+
st.markdown("""
|
244 |
+
<div class="section">
|
245 |
+
<ul>
|
246 |
+
<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>
|
247 |
+
<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>
|
248 |
+
<li><a class="link" href="https://nlp.johnsnowlabs.com/recognize_entitie" target="_blank" rel="noopener">Visualization demos for NER in Spark NLP</a></li>
|
249 |
+
<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>
|
250 |
+
</ul>
|
251 |
+
</div>
|
252 |
+
""", unsafe_allow_html=True)
|
253 |
+
|
254 |
+
# Community & Support
|
255 |
+
st.markdown('<div class="sub-title">Community & Support</div>', unsafe_allow_html=True)
|
256 |
+
st.markdown("""
|
257 |
+
<div class="section">
|
258 |
+
<ul>
|
259 |
+
<li><a class="link" href="https://sparknlp.org/" target="_blank">Official Website</a>: Documentation and examples</li>
|
260 |
+
<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>
|
261 |
+
<li><a class="link" href="https://github.com/JohnSnowLabs/spark-nlp" target="_blank">GitHub Repository</a>: Source code and issue tracker</li>
|
262 |
+
</ul>
|
263 |
+
</div>
|
264 |
+
""", unsafe_allow_html=True)
|