<?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 Christian Kasim Loan on Medium]]></title>
        <description><![CDATA[Stories by Christian Kasim Loan on Medium]]></description>
        <link>https://medium.com/@christian.kasim.loan?source=rss-9e09bb71b869------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O_NLFGw9QspqYEEx8gXdKg.jpeg</url>
            <title>Stories by Christian Kasim Loan on Medium</title>
            <link>https://medium.com/@christian.kasim.loan?source=rss-9e09bb71b869------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 04:33:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@christian.kasim.loan/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[Plain-Text OCR Benchmark: The Gap Between On-Prem and API Is Gone]]></title>
            <link>https://medium.com/john-snow-labs/plain-text-ocr-benchmark-the-gap-between-on-prem-and-api-is-gone-f6184c7fa4fd?source=rss-9e09bb71b869------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6184c7fa4fd</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[document-ai]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Christian Kasim Loan]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 00:00:51 GMT</pubDate>
            <atom:updated>2026-11-11T03:56:49.183Z</atom:updated>
            <content:encoded><![CDATA[<p>For clinical search and RAG pipelines, OCR quality determines how reliably you can retrieve information from scanned documents. In John Snow Labs’ FUNSD plain-text OCR benchmark, the self-hosted JSL Vision model recorded a character error rate of <strong>0.148</strong>, compared with 0.155 for Grok-4 and 0.167 for Gemini 2.5 Pro. These results support evaluating an OCR pipeline that keeps documents inside your environment.</p><p>Our <a href="https://www.johnsnowlabs.com/bbox-ocr-benchmark-1-out-of-15-including-every-frontier-api/">grounded OCR benchmark</a> evaluated text extraction with bounding-box coordinates. This article evaluates full-page text in reading order, the output you need for document indexing and downstream text processing.</p><p>The comparison covers 16 models. API evaluations used 50 FUNSD pages, while locally evaluated VLMs used 10 because of GPU constraints. Read the scores alongside those sample sizes.</p><figure><img alt="Four summary cards: JSL Vision CER of 0.148, the gap to the best API result, historical H100 compute cost, and local document processing." src="https://cdn-images-1.medium.com/max/1024/1*rKonixR4xDNPaHUoILCceA.png" /><figcaption>The CER gap is 0.0073 (0.73 percentage points), with different evaluation sample sizes. The approximate 3–13× cost comparison uses the historical $6.76 H100 estimate explained in table note 2 and excludes software licensing and operations. Local inference supports data control; compliance depends on the complete deployment.</figcaption></figure><h3>What “markdown OCR” looks like</h3><p>Plain-text OCR converts a document image into text arranged in reading order. Markdown output can retain headings and other formatting for downstream processing.</p><p>The example below shows the input document on the left and JSL Vision’s output on the right.</p><figure><img alt="Scanned form on the left and its OCR text output in reading order on the right." src="https://cdn-images-1.medium.com/max/1024/1*TMJjdZ8h52HfeHR96kOGXw.gif" /><figcaption>For this benchmark, we normalized the output before scoring. Bounding-box coordinates and JSON field extraction were evaluated separately in the other articles in this series.</figcaption></figure><h3>How did we measure plain-text OCR?</h3><ul><li><strong>Dataset:</strong> <a href="https://guillaumejaume.github.io/FUNSD/">FUNSD</a> training pages, 50 pages for API-served models and 10 pages for locally evaluated VLMs (GPU-constrained, see methodology)</li><li><strong>Metric:</strong> character-level CER via jiwer.cer() on full-page text</li><li><strong>Ground truth:</strong> word-level FUNSD annotations reassembled into line-level reading order (top-left → bottom-right), lowercased, whitespace-normalized</li><li><strong>Predictions:</strong> preprocessed identically (strip markdown tables, collapse whitespace, lowercase) before scoring</li></ul><p>CER reflects differences in transcription and reading order. On forms, a different ordering of correctly recognized fields can increase the score.</p><h3>Which model leads on plain-text OCR?</h3><figure><img alt="Top three FUNSD plain-text OCR results: JSL Vision 0.148 CER, Grok-4 0.155, and Gemini 2.5 Pro 0.167." src="https://cdn-images-1.medium.com/max/786/1*BzkZueWc2kvv8h357z0E5Q.png" /></figure><p>JSL Vision (jsl_vision) recorded the lowest CER in the published comparison at <strong>0.148</strong>. Grok-4 followed at 0.155, and Gemini 2.5 Pro scored 0.167.</p><p>The difference between JSL Vision and Grok-4 is 0.007 CER, or 0.7 percentage points. The top three scores span 0.019. These are descriptive results from the evaluated samples; the different page counts limit conclusions about how the models compare across other documents.</p><h3>How all 16 models compare</h3><p>The published leaderboard shows that self-hosted OCR can achieve a CER comparable to frontier APIs on this FUNSD task. JSL Vision’s recorded CER was approximately <strong>4.5%</strong> lower than Grok-4’s.</p><h4>GPT-5.2</h4><p>GPT-5.2 scored 0.271 CER, ranking 15th among the 16 models shown. Its result illustrates why you should evaluate a model on your document extraction task before choosing it for an OCR pipeline.</p><h4>Grok-4</h4><p>Grok-4 ranked second on plain-text OCR at 0.155 CER. Its result on the separate grounded OCR benchmark was 0.582 BBox CER. Evaluate text recognition and spatial grounding separately when your workflow needs coordinates for redaction or field localization.</p><h4>Sub-10B open-source models</h4><p>Qwen3-VL-8B recorded 0.222 CER, compared with 0.227 for Qwen3-VL-235B and 0.271 for GPT-5.2. The 8B result supports including smaller models in your evaluation when deployment resources are constrained. Its evaluation used 10 pages, compared with 50 for the two API-served models.</p><p>The complete 16-model comparison and notes are in the appendix.</p><h3>How much does plain-text OCR cost?</h3><p>Cost comparisons need to distinguish API charges from self-hosted compute estimates. For a self-hosted model, the estimate depends on hardware price and processing time. Your production budget also includes software licensing and operating the service.</p><p>The recovered historical cost comparison reports $18.86 per 1,000 documents for Gemini 2.5 Pro and $86.70 for Grok-4. These are archived estimates, not current prices or itemized charges for the exact evaluation pages.</p><p>The separate grounded OCR benchmark estimates <strong>$0.56</strong> per 1,000 documents for JSL Vision OCR (jsl_vision_ocr) on a T4. That figure belongs to a different model and task from the 30B flagship’s plain-text CER result.</p><p>If your pipeline also requires structured fields, review the <a href="https://www.johnsnowlabs.com/schema-constrained-ocr-the-benchmark-that-actually-matters-in-production/">schema-constrained OCR benchmark</a>. Plain-text CER alone does not measure schema extraction quality.</p><h3>How fast is each model per page?</h3><p>For batch ingestion, processing time determines how quickly you can clear a document backlog. For interactive workflows, it determines how long you wait for extracted text.</p><p>The archived plain-text API runs averaged 3.24 seconds per page for Llama-4-Maverick, 4.81 for Gemini 2.5 Flash, and 7.38 for Pixtral-Large. The corresponding local runs averaged 2.65 seconds for Nanonets-OCR2–3B and 3.66 for Qwen3-VL-8B. API response time and local inference time reflect different serving conditions.</p><h3>How do GPU and CPU deployments compare?</h3><p>We compared OCR models on an NVIDIA H100 and a c5.2xlarge CPU instance with 8 vCPUs. The hardware charts label GPU precision as bfloat16 and CPU precision as float32, using the same prompts and 5 FUNSD pages. JSL Vision OCR’s separate vLLM configuration is discussed below.</p><figure><img alt="H100 GPU versus c5.2xlarge CPU OCR latency per page for six models." src="https://cdn-images-1.medium.com/max/786/1*LxgVXyHpWZfo13BXVIi1TQ.png" /></figure><p>GPU processing was approximately 2–7× faster per page across the tested models, with a maximum reported speedup of <strong>7.2×</strong> for models in the 7–8B range.</p><figure><img alt="Estimated GPU and CPU compute cost per 1,000 OCR documents across six models." src="https://cdn-images-1.medium.com/max/786/1*B0-dwoYJ05YVOC2FXeh-vw.png" /></figure><figure><img alt="GPU VRAM and CPU RAM usage during OCR inference across six models." src="https://cdn-images-1.medium.com/max/786/1*wR0Y9u2tUVYBeHF1R12l-g.png" /></figure><p>At the benchmark’s hourly prices of $0.34 for CPU and $2.50 for H100, CPU compute cost per document was lower across the configurations tested with Transformers. For JSL Vision Structured and RolmOCR, the CPU and GPU estimates differed by about 2%. Qwen3-VL-8B’s GPU estimate was about 12% higher than its CPU estimate.</p><p>The separate JSL Vision OCR configuration served through vLLM was reported at $1.22 per 1,000 documents on H100. Treat this as a comparison of hardware and serving configurations: vLLM introduces an additional difference from the Transformers baseline.</p><h3>How does on-premises OCR support healthcare workflows?</h3><p>JSL Vision supports deployment inside your environment through Docker or Amazon SageMaker. The approximately 1B JSL Vision OCR model supports a single-T4 configuration, while the 30B flagship was evaluated on an H100.</p><p>Local inference keeps document processing within your infrastructure and gives you control over access and retention. These deployment options support regulatory-grade healthcare AI workflows. Compliance also depends on how you configure and operate the complete system.</p><p>For reproducible processing, pin the model version and inference configuration, then validate repeatability in your deployment environment. Supported inputs include PDF, PNG, and JPG, with documents converted to images for inference.</p><h3>How we ran the benchmark</h3><ul><li><strong>Dataset:</strong> <a href="https://guillaumejaume.github.io/FUNSD/">FUNSD</a>. Reading order via line-level reassembly of word-level FUNSD annotations.</li><li><strong>Metric:</strong> jiwer.cer(gt, pred) at the corpus level, after consistent preprocessing (lowercase, strip markdown separators, collapse whitespace).</li><li><strong>Closed-source models:</strong> <a href="https://openrouter.ai/">OpenRouter</a> temperature=0, max_tokens=8192.</li><li><strong>Open-source models:</strong> <a href="https://github.com/vllm-project/vllm">vLLM v0.17.1</a>, H100, f16 precision.</li><li><strong>Sample sizes:</strong> API-served models were evaluated on 50 pages. Locally evaluated VLMs used 10 pages because of GPU constraints. The unequal sample sizes limit direct comparison; the reported differences do not establish statistical significance.</li><li><strong>Outliers:</strong> Ministral-14B produced a 34× length-explosion gen-loop on one page (63 k chars vs 1.8 k GT) that inflated its corpus CER to 1.63 with median page CER of 0.28. It is omitted from the leaderboard; the gen-loop behavior is real and worth knowing about for production deployments.</li></ul><h3>Frequently asked questions</h3><h4>What does plain-text OCR extract?</h4><p>Plain-text OCR extracts document text in reading order. It supports document indexing and downstream text processing. Workflows that require word coordinates should evaluate grounded OCR separately.</p><h4>Which model recorded the lowest plain-text CER?</h4><p>JSL Vision (jsl_vision) recorded 0.148 CER in the published FUNSD comparison. Grok-4 scored 0.155, and Gemini 2.5 Pro scored 0.167. The evaluations used different sample sizes.</p><h4>How was character error rate calculated?</h4><p>The benchmark used corpus-level jiwer.cer() after normalizing reference text and predictions. Normalization included lowercasing and collapsing whitespace. CER penalizes differences in both recognized characters and reading order.</p><h4>How many pages were evaluated?</h4><p>API evaluations used 50 FUNSD training pages. Locally evaluated VLMs used 10 pages because of GPU constraints. The separate CPU/GPU comparison used 5 pages.</p><h4>Are JSL Vision and JSL Vision OCR the same model?</h4><p>JSL Vision (jsl_vision) is the 30B-class flagship evaluated for plain-text OCR. JSL Vision OCR (jsl_vision_ocr) is the approximately 1B model evaluated for grounded OCR in Part 1. Their scores and hardware cost estimates describe different configurations.</p><h4>Does a GPU always reduce OCR compute cost?</h4><p>The H100 processed pages faster than the CPU configurations in the hardware comparison. At the hourly prices used, CPU compute cost per document was lower for the Transformers configurations tested. Hardware choice and serving software both affect the result.</p><h4>Can document processing stay inside my environment?</h4><p>JSL Vision supports deployment inside your infrastructure through Docker or Amazon SageMaker. Local inference keeps document processing within that environment. Validate the complete pipeline against your organization’s security and governance requirements.</p><h3>What’s next</h3><p>This is the second article in a three-part OCR benchmark series:</p><ol><li><a href="https://www.johnsnowlabs.com/bbox-ocr-benchmark-1-out-of-15-including-every-frontier-api/">Grounded OCR on FUNSD</a></li><li>Plain-text OCR on FUNSD, covered here</li><li><a href="https://www.johnsnowlabs.com/schema-constrained-ocr-the-benchmark-that-actually-matters-in-production/">Schema-constrained OCR on OmniOCR</a></li></ol><p>JSL Vision recorded the lowest plain-text CER in this comparison, with a 0.007 difference from the strongest API result. The findings support evaluating self-hosted OCR alongside APIs, using your own documents and deployment requirements.</p><p><a href="https://www.johnsnowlabs.com/schedule-a-demo/">Schedule a demo</a> to evaluate JSL Vision on your document processing workflow.</p><h3>Appendix: complete 16-model comparison and benchmark notes</h3><ul><li>JSL Vision¹ — Parameters: 30B; pages: 10; plain-text CER ↓: 0.148; mean seconds / page: 2.53; archived cost / 1,000 docs (USD): $6.76 (note 2).</li><li>Grok-4 — Parameters: Not stated; pages: 50; plain-text CER ↓: 0.1553; mean seconds / page: 15.57; archived cost / 1,000 docs (USD): $86.70.</li><li>Gemini 2.5 Pro — Parameters: Not stated; pages: 50; plain-text CER ↓: 0.1667; mean seconds / page: 42.73; archived cost / 1,000 docs (USD): $18.86.</li><li>Claude Opus 4.5 — Parameters: Not stated; pages: 50; plain-text CER ↓: 0.1689; mean seconds / page: 13.00; archived cost / 1,000 docs (USD): $13.07.</li><li>Llama-4-Maverick — Parameters: Approximately 400B³; pages: 50; plain-text CER ↓: 0.1728; mean seconds / page: 3.24; archived cost / 1,000 docs (USD): — .</li><li>Claude Sonnet 4.5 — Parameters: Not stated; pages: 50; plain-text CER ↓: 0.1898; mean seconds / page: 16.33; archived cost / 1,000 docs (USD): $7.78.</li><li>Gemini 2.5 Flash — Parameters: Not stated; pages: 50; plain-text CER ↓: 0.2069; mean seconds / page: 4.81; archived cost / 1,000 docs (USD): — .</li><li>Qwen3-VL-8B — Parameters: 8B; pages: 10; plain-text CER ↓: 0.222; mean seconds / page: 3.66; archived cost / 1,000 docs (USD): — .</li><li>Qwen3-VL-235B — Parameters: 235B; pages: 50; plain-text CER ↓: 0.227; mean seconds / page: 20.90; archived cost / 1,000 docs (USD): — .</li><li>RolmOCR¹ — Parameters: 7B; pages: 10; plain-text CER ↓: 0.230; mean seconds / page: 3.07; archived cost / 1,000 docs (USD): — .</li><li>Chandra OCR 2 — Parameters: 5B; pages: 10; plain-text CER ↓: 0.234 (note 4); mean seconds / page: — ; archived cost / 1,000 docs (USD): — .</li><li>Pixtral-Large — Parameters: Not stated; pages: 50; plain-text CER ↓: 0.2395; mean seconds / page: 7.38; archived cost / 1,000 docs (USD): — .</li><li>Nanonets-OCR2–3B — Parameters: 3B; pages: 10; plain-text CER ↓: 0.263; mean seconds / page: 2.65; archived cost / 1,000 docs (USD): — .</li><li>JSL Vision Structured¹ — Parameters: 7B; pages: 10; plain-text CER ↓: 0.268; mean seconds / page: — ; archived cost / 1,000 docs (USD): — .</li><li>GPT-5.2 — Parameters: Not stated; pages: 50; plain-text CER ↓: 0.271; mean seconds / page: 10.38; archived cost / 1,000 docs (USD): $10.24.</li><li>Sonar Pro — Parameters: Not stated; pages: 50; plain-text CER ↓: 0.4394; mean seconds / page: 7.71; archived cost / 1,000 docs (USD): — .</li></ul><p>— indicates an unavailable verified value. Costs are historical estimates, not current prices. API timings include service response time; local timings measure inference.</p><p>¹ Model names follow the original benchmark’s labels.</p><p>² The $6.76 estimate uses a reported 9.74 seconds per page at $2.50 per H100 hour. Its underlying timing run was not recovered. It does not correspond to the archived 2.53-second mean shown in this table.</p><p>³ Approximately 400B is the parameter count reported in the original article.</p><p>⁴ The published Chandra CER of 0.234 could not be verified from the recovered results.</p><p>Local CERs retain the archived published values. Re-scoring cached predictions yielded 0.147 and 0.229 for the rows originally reported as 0.148 and 0.230, respectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6184c7fa4fd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/john-snow-labs/plain-text-ocr-benchmark-the-gap-between-on-prem-and-api-is-gone-f6184c7fa4fd">Plain-Text OCR Benchmark: The Gap Between On-Prem and API Is Gone</a> was originally published in <a href="https://medium.com/john-snow-labs">John Snow Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A 2026 Field Guide to Visual Document Processing]]></title>
            <link>https://medium.com/john-snow-labs/a-2026-field-guide-to-visual-document-processing-87a24fc6699e?source=rss-9e09bb71b869------2</link>
            <guid isPermaLink="false">https://medium.com/p/87a24fc6699e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[document-ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Christian Kasim Loan]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 00:00:26 GMT</pubDate>
            <atom:updated>2026-11-11T04:03:51.355Z</atom:updated>
            <content:encoded><![CDATA[<h3>A 2026 Field Guide to Visual Document Processing in Regulated Industries</h3><p>Visual document processing converts scanned pages into text, coordinates, or structured fields for downstream systems. In healthcare, the output you need determines what to evaluate: bounding boxes for redaction, reading-order text for search, or schema-constrained JSON for ingestion.</p><p>This 2026 series compares <strong>20+ models</strong> across three tasks. JSL Vision OCR recorded the lowest grounded CER, and JSL Vision recorded the lowest plain-text CER in the published comparisons. JSL Vision Structured-8B ranked fifth overall on JSON extraction and highest among the self-hosted models tested. Each task uses its own dataset and scoring method.</p><p>John Snow Labs’ JSL Vision family includes models for these document processing tasks. The following overview helps you select the relevant benchmark and assess the deployment requirements.</p><figure><img alt="JSL Vision model lineup for grounded OCR, plain-text OCR, and JSON-schema extraction, with model sizes and GPU configurations." src="https://cdn-images-1.medium.com/max/786/1*jR8razhcQiOVATaMMNZjiQ.png" /><figcaption>JSL Vision model lineup with document tasks, model sizes, and GPU configurations.</figcaption></figure><h3>Three document tasks and three production realities</h3><figure><img alt="Animated document examples showing bounding-box OCR, reading-order text, and schema-constrained JSON output." src="https://cdn-images-1.medium.com/max/1024/1*B95-jDfUiZcm4PDKHP0x4A.gif" /><figcaption>Animated document examples showing bounding-box OCR, reading-order text, and schema-constrained JSON output. The JSON examples illustrate format constraints; extracted values and repeatability across deployments require separate validation. Example names are fictional.</figcaption></figure><p>The series evaluates three document output formats:</p><ol><li>Grounded (BBox) OCR. Extract text and its coordinates on the page. Use this output when your workflow needs to locate words for redaction or map text to form fields.</li><li>Image → Markdown OCR. Extract text in reading order for RAG pipelines and search indexing. This benchmark scores the normalized full-page text.</li><li>JSON-Schema OCR. Extract fields into a JSON object constrained by a supplied schema. Use this output when downstream systems require named fields and defined value types.</li></ol><p>A model’s rank can change with the output format. Evaluate text recognition, spatial grounding, and schema extraction separately against the requirements of your workflow.</p><h3>How JSL Vision performs across the series</h3><figure><img alt="JSL Vision scorecard: 0.039 grounded OCR CER, 0.148 plain-text CER, and 0.730 JSON-diff accuracy; JSON ranks fifth overall." src="https://cdn-images-1.medium.com/max/1024/1*Bj3EGSdNwU9Anl5urFnckg.png" /><figcaption>Published results for the models tested: first place on grounded and plain-text OCR, and fifth overall on JSON extraction. The plain-text evaluations used different sample sizes.</figcaption></figure><p>The published comparisons report two first-place results overall and one first-place result among self-hosted models:</p><ul><li>Task and dataset: Grounded OCR · FUNSD; Model: JSL Vision OCR; Published metric: 0.039 BBox CER ↓; Published rank: 1st of 15</li><li>Task and dataset: Plain-text OCR · FUNSD; Model: JSL Vision; Published metric: 0.148 CER ↓; Published rank: 1st of 16</li><li>Task and dataset: JSON-schema OCR · OmniOCR; Model: JSL Vision Structured-8B; Published metric: 0.730 JSON-diff accuracy ↑; Published rank: 5th of 23 overall; 1st self-hosted</li></ul><p>The scores use different metrics and cannot be compared directly across tasks. Lower CER is better; higher JSON-diff accuracy is better. Schema-constrained decoding controls output format; extracted field values require separate validation.</p><p>The JSON summary retains this overview’s published score of 0.730 and count of 23 models. The <a href="https://www.johnsnowlabs.com/schema-constrained-ocr-the-benchmark-that-actually-matters-in-production/">linked JSON benchmark</a> also reports 0.730 in its prose, while its leaderboard image shows 0.714 across 19 rows.</p><p>Evaluation methods are described in the <a href="https://www.johnsnowlabs.com/bbox-ocr-benchmark-1-out-of-15-including-every-frontier-api/">grounded OCR benchmark</a>, <a href="https://www.johnsnowlabs.com/plain-text-ocr-benchmark-the-gap-between-on-prem-and-api-is-gone/">plain-text OCR benchmark</a>, and <a href="https://www.johnsnowlabs.com/schema-constrained-ocr-the-benchmark-that-actually-matters-in-production/">JSON-schema OCR benchmark</a>. These articles describe the evaluation setups; they do not provide a complete public package for reproducing every result. The JSL models support deployment inside your environment.</p><h3>How should healthcare teams evaluate document processing?</h3><p>For regulatory-grade healthcare AI workflows, evaluate the model and its deployment against four requirements:</p><ol><li>Output validation. Check whether extracted text or fields meet the requirements of your downstream system. For JSON, validate schema conformance and the accuracy of the extracted values separately.</li><li>Repeatability. Pin the model version and inference settings, then test repeatability in your own serving environment. A decoding setting alone does not establish identical results across hardware or deployments.</li><li>Data control. Assess where documents are processed and retained. On-premises deployment supports control over data movement; HIPAA, GDPR, and SOC 2 requirements also depend on the complete deployment and its operating controls.</li><li>Cost per workload. Compare API charges with self-hosted compute, software licensing, and operating costs for the same task and document mix. State the hardware and pricing assumptions with each estimate.</li></ol><p>In the published JSON benchmark, JSL Vision Structured-8B scored <strong>0.730</strong>, compared with 0.709 for Claude Sonnet 4.5. GPT-5.2 led at 0.888; Gemini 2.5 Flash, Gemini 2.5 Pro, and Claude Opus 4.5 also scored higher than JSL Vision Structured-8B.</p><p>The difference between 0.730 and 0.888 is 0.158, approximately 17.8% relative to the leading score. Use that result alongside the published A10G deployment option and validate the complete pipeline on your own documents.</p><h3>What each part of the series covers</h3><h4>Part 1 · Grounded OCR on FUNSD</h4><p><a href="https://www.johnsnowlabs.com/bbox-ocr-benchmark-1-out-of-15-including-every-frontier-api/">Read the grounded OCR benchmark</a>. JSL Vision OCR recorded 0.039 BBox CER and ranked first in the published comparison. This task evaluates recognized text together with its position on the page.</p><h4>Part 2 · Plain-text OCR on FUNSD</h4><p><a href="https://www.johnsnowlabs.com/plain-text-ocr-benchmark-the-gap-between-on-prem-and-api-is-gone/">Read the plain-text OCR benchmark</a>. JSL Vision recorded 0.148 CER, compared with 0.1553 for Grok-4, the strongest API result in that comparison. The difference is 0.0073 CER, or 0.73 percentage points, across evaluations with different sample sizes.</p><h4>Part 3 · JSON-schema OCR on OmniOCR</h4><p><a href="https://www.johnsnowlabs.com/schema-constrained-ocr-the-benchmark-that-actually-matters-in-production/">Read the schema-constrained OCR benchmark</a>. GPT-5.2 led at 0.888 JSON-diff accuracy, despite ranking 15th in the 16-model plain-text comparison. JSL Vision Structured-8B scored <strong>0.730</strong> and ranked first among self-hosted models. Its schema-aware decoding is evaluated separately from the accuracy of extracted values.</p><h3>Which document benchmarks need further evaluation?</h3><p>Additional evaluation areas include medical de-identification on clinical notes, long-form document understanding on <a href="https://arxiv.org/abs/2412.07626">OmniDocBench</a>, medical visual question answering on <a href="https://arxiv.org/abs/2402.09181">OmniMedVQA</a>, OCR primitives on <a href="https://arxiv.org/abs/2305.07895">OCRBench</a>, and chart understanding on <a href="https://arxiv.org/abs/2406.18521">CharXiv</a>. Handwriting, lab reports, and insurance forms also need evaluations that reflect their document characteristics.</p><h3>Frequently asked questions</h3><h4>Which OCR output should my pipeline use?</h4><p>Use grounded OCR when the next step needs coordinates, such as locating words for redaction. Use reading-order text for search and RAG. Evaluate schema-constrained JSON when the next system expects named fields and defined value types.</p><h4>Does one model lead every OCR task?</h4><p>The published results show different rankings for different tasks. JSL Vision leads the plain-text comparison, while GPT-5.2 leads the JSON-schema comparison. Select the benchmark that matches the output your workflow needs.</p><h4>How close was self-hosted OCR to the best API?</h4><p>On the plain-text task, JSL Vision recorded 0.148 CER and Grok-4 recorded 0.1553. The absolute difference is 0.0073 CER, or 0.73 percentage points. Sample sizes differed, so these scores do not establish statistical significance.</p><h4>Does schema-constrained JSON guarantee correct extracted values?</h4><p>Schema-aware decoding constrains the output format. A schema-compliant field can still contain an incorrect value, so evaluate field accuracy separately. Validate complete responses before downstream ingestion.</p><h4>What should I validate before deploying OCR in healthcare?</h4><p>Test the model on documents representative of your workflow and validate the outputs required downstream. Review the serving configuration and data handling controls. Include software licensing and operating costs when comparing self-hosted inference with API charges.</p><h3>Evaluate OCR on your own documents</h3><p>The series compares text recognition, spatial grounding, and structured extraction using task-specific metrics. Start with the output your pipeline needs, then assess the model and deployment configuration against your own document mix.</p><p>The <a href="https://demo.johnsnowlabs.com/ocr/VLM_WORKSHOP/">JSL Vision Workshop</a> includes demonstrations of <a href="https://demo.johnsnowlabs.com/ocr/VLM_WORKSHOP/visual-deid">visual de-identification</a>, <a href="https://demo.johnsnowlabs.com/ocr/VLM_WORKSHOP/radiology-rag">radiology RAG</a>, <a href="https://demo.johnsnowlabs.com/ocr/VLM_WORKSHOP/dermatology-rag">dermatology RAG</a>, <a href="https://demo.johnsnowlabs.com/ocr/VLM_WORKSHOP/invoice-processing">invoice processing</a>, and <a href="https://demo.johnsnowlabs.com/ocr/VLM_WORKSHOP/kyc-verification">KYC verification</a>. The examples illustrate workflows; their outputs are not substitutes for a documented benchmark.</p><p>You can also watch the <a href="https://www.youtube.com/watch?v=Uk0OMwed0ys">one-hour workshop walkthrough</a>.</p><p><a href="https://www.johnsnowlabs.com/schedule-a-demo/">Schedule a demo</a> to evaluate JSL Vision for your document processing workflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87a24fc6699e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/john-snow-labs/a-2026-field-guide-to-visual-document-processing-87a24fc6699e">A 2026 Field Guide to Visual Document Processing</a> was originally published in <a href="https://medium.com/john-snow-labs">John Snow Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BBox OCR Benchmark: #1 Out of 15, Including Every Frontier API]]></title>
            <link>https://medium.com/john-snow-labs/bbox-ocr-benchmark-1-out-of-15-including-every-frontier-api-fcc3dcf1b7de?source=rss-9e09bb71b869------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcc3dcf1b7de</guid>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[document-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Christian Kasim Loan]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 00:00:24 GMT</pubDate>
            <atom:updated>2026-11-11T04:07:35.218Z</atom:updated>
            <content:encoded><![CDATA[<h3>BBox OCR Benchmark: #1 of 15 Models Including Every Frontier API</h3><p>John Snow Labs’ JSL Vision OCR-1B ranked first in the published 15-model FUNSD grounded OCR comparison at <strong>0.039 BBox CER</strong>, ahead of Gemini 2.5 Pro at 0.053. Grounded OCR returns recognized text with bounding-box coordinates, so your pipeline can locate words for redaction or field extraction.</p><p>The 1B model supports deployment on a single T4 GPU. The measured 1.8-second result uses H100 via vLLM; the approximately 4-second T4 figure is a separate estimate. The cost and hardware sections distinguish those configurations.</p><p>The comparison includes frontier APIs and traditional OCR engines on the <a href="https://guillaumejaume.github.io/FUNSD/">FUNSD</a> dataset. Read the results alongside the matching thresholds, parse rates, and serving configuration described below.</p><figure><img alt="Summary cards showing JSL Vision OCR at 0.039 BBox CER, 100% parse rate, a CER comparison with Tesseract, and H100 deployment." src="https://cdn-images-1.medium.com/max/786/1*QcDqdt__f01pNWLxW1eerQ.png" /><figcaption>Published results on the evaluated FUNSD pages. The reported 100% parse rate describes parseable output; the 4.7× comparison refers to CER, not a percentage-point accuracy gain.</figcaption></figure><h3>What “grounded OCR” looks like</h3><p>The example shows the input document on the left and recognized text with bounding boxes on the right.</p><figure><img alt="Scanned form alongside recognized text regions and bounding boxes returned by JSL Vision OCR." src="https://cdn-images-1.medium.com/max/1024/1*4fVZ4OjIVGSovkBt8AWbeg.gif" /><figcaption>Text recognition with bounding-box coordinates. Example names are fictional.</figcaption></figure><p>Downstream code can use the returned coordinates to select text regions for review, field mapping, or masking. Validate recognition and spatial alignment against the requirements of your workflow.</p><h3>Why do healthcare workflows need bounding boxes?</h3><p>Grounded OCR associates recognized text with coordinates on the source image. In healthcare document processing, those coordinates support:</p><ul><li>Visual de-identification: locate text regions before masking identified personal information.</li><li>Form-field extraction: associate text with its position on the form.</li><li>Audit review: link extracted text to the source region for inspection.</li><li>Region-level redaction: mask selected areas while retaining the rest of the page.</li></ul><p>The original evaluation reports 6 models that did not emit bounding boxes in the tested setup, including RolmOCR-8B, Nanonets-OCR2, Phi-4-Multimodal, DeepSeek-OCR, and Chandra OCR 2. This is a result for those prompts and configurations; it does not establish that every version or deployment of those models has the same limitation.</p><h3>Which models lead the published grounded OCR comparison?</h3><figure><img alt="Grounded OCR podium: JSL Vision OCR 0.039 BBox CER, Gemini 2.5 Pro 0.053, and Gemini 2.5 Flash 0.092." src="https://cdn-images-1.medium.com/max/1024/1*Tg-E8-HkV5Qbf2gOy-rGpQ.png" /><figcaption>Three lowest CERs in the published leaderboard. Lower BBox CER is better.</figcaption></figure><p>The three lowest scores in the published CER leaderboard are JSL Vision OCR at <strong>0.039 BBox CER</strong>, Gemini 2.5 Pro at 0.053, and Gemini 2.5 Flash at 0.092. JSL Vision OCR’s reported parse rate is 100%.</p><p>Lower BBox CER is better. Parse rate measures whether the output could be parsed; it does not establish that every recognized word or coordinate is correct.</p><h3>How do the grounded OCR models compare?</h3><p>The table compares BBox CER, parse rates, estimated costs, and per-page latency.</p><p>The complete model comparison and notes are in the appendix.</p><h4>Spatial errors in this evaluation</h4><p>GPT-5.2, Grok-4, and Claude Opus 4.5 each scored above 0.5 BBox CER in the published comparison. For workflows requiring text localization, evaluate the coordinate alignment as well as the extracted text.</p><h4>Gemini 2.5 Flash and Pro</h4><p>Gemini 2.5 Flash recorded 0.092 BBox CER, compared with 0.053 for Pro. Compare that error-rate difference with the cost and latency assumptions for your document mix.</p><h4>Pixtral-Large parse rate</h4><p>Pixtral-Large’s reported parse rate was <strong>12%</strong>, leaving 88 of 100 pages without parseable bounding-box output. Your pipeline needs to detect and handle such failures.</p><h3>What does grounded OCR cost per document?</h3><p>The reported compute estimate for JSL Vision OCR on T4 is approximately <strong>$0.56 per 1,000 documents</strong>, using approximately 4 seconds per page at $0.50 per hour. This is a T4 estimate, separate from the measured H100 latency.</p><p>Using the unrounded hourly rate, the calculation is $0.50 ÷ 3,600 × 4 × 1,000 ≈ $0.56. Include software licensing and operating costs when budgeting for a deployment.</p><p>The original article quotes API estimates of approximately $6.75 per 1,000 documents for Gemini 2.5 Pro, $9.45 for GPT-5.2, and $3.38 for Grok-4. Treat these as historical figures; the chart and prose reflect different reported pricing assumptions.</p><figure><img alt="Grounded OCR cost-versus-CER scatterplot, with self-hosted H100 estimates and historical API price points." src="https://cdn-images-1.medium.com/max/1024/1*XD66eeCgdIARyHVUlK3tkg.png" /><figcaption>Estimated cost per 1,000 documents versus BBox CER. Self-hosted costs use H100; the approximately $0.56 T4 estimate uses a separate configuration. Some API price points differ from the historical estimates in the text.</figcaption></figure><h3>How long does grounded OCR take per page?</h3><p>For batch ingestion and interactive processing, evaluate per-page latency alongside extraction quality.</p><figure><img alt="Grounded OCR timing chart showing 15 models, with JSL Vision OCR at 1.8 seconds per page." src="https://cdn-images-1.medium.com/max/1024/1*k_tA9ZASzwDKky8P1CfC1w.png" /><figcaption>Per-page latency for 15 models. JSL Vision OCR’s 1.8-second result uses H100/vLLM; approximately 4 seconds on T4 is a separate estimate. Pixtral-Large is shown at 20.0 seconds; the prose gives 69 seconds.</figcaption></figure><p>JSL Vision OCR’s reported <strong>1.8 seconds per page</strong> is the rounded H100/vLLM result; the more precise figure reported in the hardware section is 1.76 seconds. The approximately 4-second T4 figure belongs to the separate cost estimate.</p><p>The published timing chart places JSL Vision OCR third, behind Tesseract and docTR. It reports 50.0 seconds per page for Gemini 2.5 Pro and 93.5 for Grok-4. The original prose’s rounded Grok-4 figure is 94 seconds.</p><p>Pixtral-Large’s timing is inconsistent: the prose gives 69 seconds per page and the chart shows 20.0 seconds.</p><h3>How does JSL Vision OCR compare with traditional engines?</h3><p>Tesseract and EasyOCR return text regions and coordinates. This FUNSD comparison evaluates their spatially matched text against JSL Vision OCR using the same reported BBox CER metric.</p><figure><img alt="BBox CER comparison showing JSL Vision OCR at 0.039, Tesseract at 0.180, and EasyOCR at 0.237." src="https://cdn-images-1.medium.com/max/786/1*QGeSu3xYspETNRAXeSx6DQ.png" /><figcaption>Published CER comparison on FUNSD. The 4.7× and 6.1× labels are ratios of character error rates.</figcaption></figure><p>The published comparison gives Tesseract 0.180 CER and EasyOCR 0.237, compared with JSL Vision OCR at 0.039. It reports their relative CERs as approximately <strong>4.7×</strong> and 6.1× higher, respectively.</p><p>JSL Vision OCR’s reported parse rate is 100%. These results describe the evaluated FUNSD pages; separate testing is needed for handwriting, other layouts, and additional languages.</p><h3>How can you deploy grounded OCR in healthcare?</h3><p>JSL Vision OCR supports document processing inside your environment. Review the complete deployment against your healthcare data-handling and operational requirements.</p><ul><li><strong>Data control:</strong> local inference supports control over document processing and data movement. HIPAA, GDPR, and SOC 2 requirements also depend on the deployment’s configuration and operating controls.</li><li><strong>Deployment:</strong> Docker or Amazon SageMaker.</li><li><strong>Hardware:</strong> a single T4 for the 1B model or A10G for the 8B configuration. Validate your model and serving configuration before deployment.</li><li><strong>Repeatability:</strong> pin model versions and inference settings, then test repeatability in your own environment.</li><li><strong>Inputs:</strong> PDF, PNG, and JPG, converted to images for inference.</li></ul><h3>How did we evaluate grounded OCR accuracy?</h3><ul><li><strong>Dataset:</strong> <a href="https://guillaumejaume.github.io/FUNSD/">FUNSD</a>, Form Understanding in Noisy Scanned Documents. 100 pages from the training split.</li><li><strong>BBox CER metric:</strong> IoU-based spatial matching (threshold 0.3, score filter 0.15) followed by Levenshtein distance on matched text pairs. Unmatched regions counted as insertion/deletion errors.</li><li><strong>Closed-source models:</strong> Evaluated via <a href="https://openrouter.ai/">OpenRouter</a> API.</li><li><strong>Open-source VLMs:</strong> Evaluated via <a href="https://github.com/vllm-project/vllm">vLLM v0.17.1</a> on a single NVIDIA H100.</li><li><strong>Traditional OCR:</strong> Native Python libraries (tesserocr, easyocr).</li><li><strong>Parse rate:</strong> Percentage of pages where the model produced any parseable bounding-box output.</li></ul><p>The evaluation methodology is described above. Evaluation code and per-page JSON caches are archived internally.</p><h3>How do CPU and GPU OCR deployments compare?</h3><p>We compared H100 GPU and c5.2xlarge CPU inference on the same 5 FUNSD pages with the same prompts. The Transformers runs used bfloat16 on H100 and float32 on CPU. JSL Vision OCR ran separately on H100 via vLLM, so its result also reflects a different serving backend.</p><figure><img alt="H100 GPU versus c5.2xlarge CPU OCR latency comparison across six models." src="https://cdn-images-1.medium.com/max/1024/1*sHDfxU_HPs46kXNzLNLBEw.png" /><figcaption>Hardware comparison on 5 FUNSD pages. The Transformers GPU configuration is labeled bfloat16 and the CPU configuration float32; JSL Vision OCR’s vLLM result uses a different serving backend.</figcaption></figure><p>GPU processing was 2–7× faster per page in the Transformers comparisons, reaching 7.2× for 7–8B models. JSL Vision OCR took <strong>1.76 seconds per page</strong> on H100 via vLLM, rounded to 1.8 seconds in the latency chart. The approximately 4-second T4 figure is a separate estimate.</p><figure><img alt="Estimated compute cost per 1,000 OCR documents on H100 GPU and c5.2xlarge CPU." src="https://cdn-images-1.medium.com/max/1024/1*oUiHeUSV7PJdI6j-fhJKUg.png" /><figcaption>Published compute estimates use $2.50 per H100 hour and $0.34 per CPU hour. The approximately $1.22 JSL Vision OCR figure is H100/vLLM; the approximately $0.56 T4 estimate is separate.</figcaption></figure><p>At approximately $0.34 per CPU hour and $2.50 per H100 hour, CPU inference costs less for most models in this comparison despite taking longer per page. JSL Vision OCR’s H100/vLLM compute cost is approximately $1.22 per 1,000 documents. The separate T4 estimate is approximately $0.56 per 1,000 documents, based on approximately 4 seconds per page at $0.50 per hour.</p><figure><img alt="GPU VRAM and CPU RAM usage during OCR inference across six models." src="https://cdn-images-1.medium.com/max/1024/1*krK6aJ4bXpaQKMj_yTmuEg.png" /><figcaption>GPU VRAM and CPU RAM during inference, using bfloat16 on H100 and float32 on CPU.</figcaption></figure><p>The memory comparison uses bfloat16 on GPU and float32 on CPU. When choosing a deployment, account for inference precision and serving software alongside hardware price and per-page latency. These compute estimates exclude software licensing and operating costs.</p><h3>Frequently asked questions</h3><h4>What does grounded OCR return?</h4><p>Grounded OCR returns recognized text together with bounding-box coordinates. Coordinates let downstream code locate text regions for field mapping or redaction. Validate recognition and spatial alignment separately for your workflow.</p><h4>How was BBox CER calculated?</h4><p>The evaluation uses IoU-based spatial matching with threshold 0.3 and score filter 0.15, followed by Levenshtein distance on matched text pairs. Unmatched regions contribute insertion or deletion errors. Lower BBox CER is better.</p><h4>Does a 100% parse rate mean perfect OCR?</h4><p>Parse rate is the percentage of pages with any parseable bounding-box output. The model can still make text or location errors. JSL Vision OCR’s published figures are 100% parse rate and 0.039 BBox CER.</p><h4>Which hardware produced the 1.8-second result?</h4><p>The approximately 1.8-second result refers to H100 inference via vLLM, reported more precisely as 1.76 seconds per page. The approximately 4-second T4 figure is a separate estimate. They should not be used interchangeably in a cost calculation.</p><h4>How was the T4 cost estimate calculated?</h4><p>The estimate uses $0.50 per hour and approximately 4 seconds per page. At that processing time, $0.50 ÷ 3,600 × 4 × 1,000 is approximately $0.56 per 1,000 documents. This is a compute estimate, excluding licensing and operations.</p><h4>Where are the evaluation methods described?</h4><p>The methodology section defines the FUNSD dataset, spatial-matching thresholds, and scoring process. Evaluation code and per-page JSON caches are archived internally.</p><h3>What’s next</h3><p>This is the first article in a three-part OCR benchmark series:</p><ol><li>Grounded (BBox) OCR on FUNSD, covered here</li><li><a href="https://www.johnsnowlabs.com/plain-text-ocr-benchmark-the-gap-between-on-prem-and-api-is-gone/">Plain-text OCR on FUNSD</a></li><li><a href="https://www.johnsnowlabs.com/schema-constrained-ocr-the-benchmark-that-actually-matters-in-production/">Schema-constrained JSON OCR on OmniOCR</a></li></ol><p>JSL Vision OCR recorded the lowest BBox CER in the published comparison. Assess text recognition, spatial alignment, and serving requirements on documents representative of your own workflow.</p><p><a href="https://www.johnsnowlabs.com/schedule-a-demo/">Schedule a demo</a> to evaluate JSL Vision OCR for your document processing pipeline.</p><h3>Appendix: complete model comparison and benchmark notes</h3><ul><li>Model: JSL Vision OCR; Parameters: 1B; BBox CER ↓: 0.039; Parse rate: 100%; Estimated cost / 1,000 docs: ≈$0.56 (T4 estimate); ≈$1.22 (H100); Seconds / page: 1.8 (H100 / vLLM)</li><li>Model: Gemini 2.5 Pro; Parameters: Not stated; BBox CER ↓: 0.053; Parse rate: 100%; Estimated cost / 1,000 docs: ≈$6.75 (published API estimate); Seconds / page: 50.0</li><li>Model: Gemini 2.5 Flash; Parameters: Not stated; BBox CER ↓: 0.092; Parse rate: 100%; Estimated cost / 1,000 docs: — ; Seconds / page: 12.5</li><li>Model: Claude Sonnet 4.5; Parameters: Not stated; BBox CER ↓: 0.152; Parse rate: 100%; Estimated cost / 1,000 docs: — ; Seconds / page: 20.8</li><li>Model: Tesseract 5.5; Parameters: Not applicable; BBox CER ↓: 0.180; Parse rate: 100%; Estimated cost / 1,000 docs: — ; Seconds / page: 1.0</li><li>Model: EasyOCR; Parameters: Not stated; BBox CER ↓: 0.237; Parse rate: 100%; Estimated cost / 1,000 docs: — ; Seconds / page: 2.8</li><li>Model: Qwen3-VL-8B; Parameters: 8B; BBox CER ↓: 0.254; Parse rate: 91%; Estimated cost / 1,000 docs: — ; Seconds / page: 12.8</li><li>Model: Claude Opus 4.5; Parameters: Not stated; BBox CER ↓: 0.530; Parse rate: 90%; Estimated cost / 1,000 docs: — ; Seconds / page: 20.6</li><li>Model: Grok-4; Parameters: Not stated; BBox CER ↓: 0.582; Parse rate: 92%; Estimated cost / 1,000 docs: ≈$3.38 (published API estimate); Seconds / page: 93.5</li><li>Model: GPT-5.2; Parameters: Not stated; BBox CER ↓: 0.588; Parse rate: 100%; Estimated cost / 1,000 docs: ≈$9.45 (published API estimate); Seconds / page: 30.2</li><li>Model: Sonar Pro; Parameters: Not stated; BBox CER ↓: 0.676; Parse rate: 100%; Estimated cost / 1,000 docs: — ; Seconds / page: 13.5</li><li>Model: Llama-4-Maverick; Parameters: Not stated; BBox CER ↓: 0.723; Parse rate: 81%; Estimated cost / 1,000 docs: — ; Seconds / page: 8.0</li><li>Model: Ministral-14B; Parameters: 14B; BBox CER ↓: 0.736; Parse rate: 93%; Estimated cost / 1,000 docs: — ; Seconds / page: 14.0</li><li>Model: Pixtral-Large; Parameters: Not stated; BBox CER ↓: 0.783; Parse rate: 12%; Estimated cost / 1,000 docs: — ; Seconds / page: 20.0</li><li>Model: docTR (timing chart only); Parameters: Not stated; BBox CER ↓: — ; Parse rate: — ; Estimated cost / 1,000 docs: — ; Seconds / page: 1.1</li></ul><p>— means a value is unavailable here, not zero. The CER leaderboard ranks 14 models. docTR appears in the timing chart only and has no CER ranking in this table. Parse rates come from the archived comparison data; latency values come from the timing chart.</p><p>Costs are historical estimates. The $0.56 T4 estimate uses a different configuration from the H100/vLLM timing and approximately $1.22 H100 cost. The cost scatterplot uses H100 for self-hosted inference; some API price points differ from the prose estimates. For Pixtral-Large, the timing chart shows 20.0 seconds per page and the prose gives 69 seconds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcc3dcf1b7de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/john-snow-labs/bbox-ocr-benchmark-1-out-of-15-including-every-frontier-api-fcc3dcf1b7de">BBox OCR Benchmark: #1 Out of 15, Including Every Frontier API</a> was originally published in <a href="https://medium.com/john-snow-labs">John Snow Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Schema-Constrained OCR: The Benchmark That Actually Matters in Production]]></title>
            <link>https://medium.com/john-snow-labs/schema-constrained-ocr-the-benchmark-that-actually-matters-in-production-7a5215e02465?source=rss-9e09bb71b869------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a5215e02465</guid>
            <category><![CDATA[document-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Christian Kasim Loan]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 00:00:19 GMT</pubDate>
            <atom:updated>2026-11-11T04:12:33.497Z</atom:updated>
            <content:encoded><![CDATA[<h3>Schema-Constrained OCR: JSON Extraction Accuracy, Cost, and Reliability Across 19 Models</h3><p>Schema-constrained OCR extracts document values into a supplied JSON Schema. For clinical data ingestion and claims processing, you need both correct fields and a valid output structure. In John Snow Labs’ 100-document OmniOCR evaluation, GPT-5.2 led with <strong>0.888 json-diff accuracy</strong>. The article reports <strong>0.730 for JSL Vision Structured-8B</strong>, the highest score among its self-hosted models. Evaluate extraction accuracy and output validity separately when selecting your pipeline.</p><p>This third benchmark follows our <a href="https://www.johnsnowlabs.com/bbox-ocr-benchmark-1-out-of-15-including-every-frontier-api/">grounded OCR comparison</a>, which evaluates text and coordinates, and our <a href="https://www.johnsnowlabs.com/plain-text-ocr-benchmark-the-gap-between-on-prem-and-api-is-gone/">plain-text OCR comparison</a>, which evaluates full-page transcription.</p><p>The prose and published charts contain different result sets: the prose reports 0.730 for JSL Vision Structured-8B, while the summary and leaderboard graphics show 0.714. The leaderboard graphic contains 19 models. The sections below identify these differences rather than combining the values into one result.</p><figure><img alt="Summary cards showing 0.714 for JSL Vision Structured, 0.888 for GPT-5.2, and 100 OmniOCR documents." src="https://cdn-images-1.medium.com/max/786/1*y2zO5G-yT_QzmLZZmpbaDQ.png" /><figcaption>Published summary graphic. It shows 0.714 for JSL Vision Structured, while the prose reports 0.730. Its “100% valid JSON guaranteed” card describes a structural decoding claim, not a measured guarantee that every request succeeds.</figcaption></figure><h3>How does schema-constrained OCR produce structured records?</h3><p>You supply a document image and a JSON Schema defining the required fields and types. The model extracts values from the image into that structure.</p><figure><img alt="Example showing a JSON Schema, a document image, and structured JSON output." src="https://cdn-images-1.medium.com/max/1024/1*fvL32KkqiVYG5qVJBMRMjA.gif" /><figcaption>Schema-constrained extraction takes a document image and a supplied schema as inputs. The example illustrates the output format; extracted values still require validation.</figcaption></figure><p>You can then validate the extracted fields before mapping them into clinical records, claims systems, or research databases. A schema-valid response still needs checks for missing or incorrect values.</p><h3>What should you validate before importing extracted fields?</h3><p>Clinical document pipelines populate specific fields: lab measurements in an EHR, procedure codes in a claim, or timestamps in a case report form. Text recognition is one part of that task.</p><p>Check whether the response parses as JSON, conforms to the supplied schema, and contains the correct values. Route invalid or incomplete results to a retry or review step before importing them into your downstream system.</p><h3>Which models led the JSON extraction evaluation?</h3><figure><img alt="Published self-hosted podium showing JSL Vision Structured at 0.714, JSL Vision at 0.689, and Holo2–30B-A3B at 0.684." src="https://cdn-images-1.medium.com/max/786/1*qEOVx4Pf4LzTzN0sIUpyLA.png" /><figcaption>Self-hosted model comparison as shown in the published graphic. The prose separately reports JSL Vision Structured-8B at 0.730 and an additional olmOCR-7B result at 0.714.</figcaption></figure><p>GPT-5.2 recorded <strong>0.888</strong> json-diff accuracy, followed by Gemini 2.5 Flash at 0.873, Gemini 2.5 Pro at 0.840, and Claude Opus 4.5 at 0.800. Claude Sonnet 4.5 scored 0.709.</p><p>The article’s prose places JSL Vision Structured-8B fifth at 0.730 and lists olmOCR-7B at 0.714. The published podium and leaderboard instead show JSL Vision Structured at 0.714; the leaderboard does not include a separate olmOCR-7B row. These are different published result sets.</p><p>JSL Vision-30B scores 0.689 in both the prose and leaderboard, where it is seventh. GPT-5.2’s 0.271 character error rate on the separate plain-text benchmark shows why you should evaluate transcription and schema-based extraction as distinct tasks.</p><h3>How do the 19 charted models compare?</h3><figure><img alt="Json-diff accuracy leaderboard for 19 models, led by GPT-5.2 at 0.888; JSL Vision Structured is fifth at 0.714." src="https://cdn-images-1.medium.com/max/1024/1*GqmJGxmdnPrPmQIJiIbG4w.png" /><figcaption>Published 19-model OmniOCR leaderboard; higher json-diff accuracy is better. The appendix list reproduces these chart values, while the prose identifies its separately reported results.</figcaption></figure><p>The complete model comparison and notes are in the appendix.</p><p>Grok-4 scored 0.255 and Sonar Pro 0.134 in this evaluation. PaddleOCR-VL scored 0.033, with 50 empty predictions out of 100 documents. These results describe the tested extraction setup, rather than every deployment of those models.</p><h3>How much does schema-constrained OCR cost?</h3><p>Compare extraction accuracy with cost for your expected document volume. The following figures are the article’s historical estimates per 1,000 documents, rather than current API prices.</p><figure><img alt="Historical cost-versus-accuracy scatterplot for JSON extraction, comparing local compute estimates and API rates." src="https://cdn-images-1.medium.com/max/1024/1*IbZNFYGOSZBKGNAYF9G4IA.png" /><figcaption>Published cost estimates per 1,000 documents plotted against json-diff accuracy. JSL chart points differ from the prose estimates; compare hardware and serving configurations before using either for budgeting.</figcaption></figure><p>GPT-5.2 is listed at approximately $15.58 per 1,000 documents and 0.888 accuracy. Gemini 2.5 Flash is listed at approximately $2.75 and 0.873. The prose estimates approximately $6.76 on H100 for each JSL configuration, with an approximately $1.50 A10G estimate for JSL Vision Structured-8B. Grok-4 is listed at $86.70 and 0.255 accuracy.</p><p>The scatterplot shows different JSL cost points and uses 0.714 for JSL Vision Structured. Read those points as the chart’s published estimates; they do not establish the same hardware configuration or timing basis as the prose. Recalculate costs using your document lengths, inference settings, and infrastructure rates.</p><h3>How long does JSON extraction take per document?</h3><p>The published latency chart contains <strong>18 models</strong>. It combines local H100 inference timings with API response timings, so compare the hardware and serving setup alongside each value.</p><figure><img alt="Published latency chart for 18 models, showing JSL Vision OCR at 1.8 seconds and JSL Vision Structured at 3.5 seconds per document." src="https://cdn-images-1.medium.com/max/1024/1*-hKaBNhnq8xuz35veWGMBw.png" /><figcaption>Published JSON-extraction latency chart. Local values are labeled H100 inference; API values include service response time. The prose separately reports 9.7 seconds for JSL Vision and approximately 3–4 seconds on A10G for JSL Vision Structured.</figcaption></figure><p>The chart shows JSL Vision OCR at 1.8 seconds per document and JSL Vision Structured at 3.5 seconds. The prose separately gives 9.7 seconds for JSL Vision and approximately 3–4 seconds on A10G for JSL Vision Structured. It reports Gemini 2.5 Pro at 50 seconds and rounds Grok-4 to 94 seconds, versus 93.5 seconds in the chart. These published timings should not be combined into a single configuration or a universal speed ranking.</p><h3>How often did extraction return an empty prediction?</h3><p>Track empty predictions separately from average extraction accuracy. A missing result needs an explicit retry, fallback, or review path before downstream ingestion.</p><figure><img alt="Empty predictions on 100 documents: JSL Vision Structured 1, Claude Opus 4.5 6, JSL Vision OCR without schema decoding 18, PaddleOCR-VL 50." src="https://cdn-images-1.medium.com/max/786/1*8rW9ROWN4et2GCox9ZEozQ.png" /><figcaption>Empty-prediction counts for four published configurations. JSL Vision Structured has 1 empty result out of 100 in this chart; structured decoding does not eliminate every request failure.</figcaption></figure><p>The published failure chart shows <strong>1 empty prediction out of 100</strong> for JSL Vision Structured, 6 for Claude Opus 4.5, 18 for JSL Vision OCR without schema decoding, and 50 for PaddleOCR-VL. The chart compares these four configurations; it does not establish the failure rate of every model in the leaderboard.</p><p>Schema-aware decoding constrains output structure. It does not prevent every empty response, interrupted request, or incorrect field value.</p><h3>What does schema-aware decoding enforce during generation?</h3><p>The evaluation prompted API models with an image, a schema, and an instruction to return JSON. Local models used structured generation where supported. This compares the tested pipelines, including their decoding settings; it does not compare every provider’s native structured-output mode.</p><p>In <a href="https://docs.vllm.ai/en/latest/features/structured_outputs/">vLLM structured generation</a>, a backend such as xgrammar constrains generation to a supported output schema. Verify schema support and validate completed responses in your application. Structural constraints do not establish that extracted values are correct or that outputs will be identical across hardware, versions, and deployments.</p><h3>What should you check before deploying clinical extraction?</h3><p>For clinical ingestion, evaluate field accuracy and schema validity alongside failure handling. Keep the source document, extracted result, validation status, and model configuration available for review.</p><p>Self-hosted inference lets you process documents within your environment. Configure access controls, logging, and retention for your deployment; on-premises inference alone does not establish HIPAA or GDPR compliance or SOC 2 assurance.</p><p>The article lists single-GPU options and historical cost estimates of approximately $1.50 per 1,000 documents on A10G and $6.76 on H100 for the 30B model. Size your deployment using measurements from the model, task, and serving configuration you intend to run.</p><h3>How was schema-constrained OCR evaluated on OmniOCR?</h3><ul><li>Dataset: the <a href="https://huggingface.co/datasets/getomni-ai/ocr-benchmark">OmniAI OCR benchmark</a>, using the article’s stated <strong>100-document test split</strong>.</li><li>Metric: json-diff accuracy against reference JSON, with deep-sorted keys and case-insensitive values. This is an extraction score, separate from a JSON parsing or schema-validation pass rate.</li><li>API configuration: OpenRouter requests at temperature 0 and max_tokens 8192, with the schema in the prompt.</li><li>Local configuration: vLLM v0.17.1 on NVIDIA H100, f16 precision, with structured generation where supported.</li><li>Parsing: strip Markdown fences; if parsing fails, attempt extraction from the first opening brace to the last closing brace.</li><li>Empty predictions: count separately and include in the average with a score of 0.</li></ul><p>Per-document outputs are archived internally. The published prose and charts differ in some scores, model lists, and timing estimates; their specific values are identified alongside the relevant comparisons above.</p><h3>What do the separate GPU and CPU tests show?</h3><p>The following charts compare H100 GPU and CPU inference on the same <strong>5 FUNSD pages</strong>. The charts label GPU precision as bfloat16 and CPU precision as float32. Compare these hardware results separately from the 100-document OmniOCR JSON evaluation.</p><figure><img alt="Separate FUNSD hardware test showing JSL Vision Structured at 10.4 seconds per page on H100 GPU and 74.8 seconds on CPU." src="https://cdn-images-1.medium.com/max/786/1*LxgVXyHpWZfo13BXVIi1TQ.png" /><figcaption>GPU runs are labeled bfloat16 and CPU runs float32. Account for precision when comparing the hardware results.</figcaption></figure><p>In this hardware comparison, JSL Vision Structured takes 10.4 seconds per page on GPU and 74.8 seconds on CPU, a <strong>7.2× speedup</strong>.</p><figure><img alt="Separate hardware cost chart showing JSL Vision Structured at $7.22 per 1,000 documents on H100 and $7.07 on CPU." src="https://cdn-images-1.medium.com/max/786/1*B0-dwoYJ05YVOC2FXeh-vw.png" /><figcaption>Compute estimates for the separate hardware test, using $2.50 per H100 hour and $0.34 per CPU hour. The JSL Vision Structured estimates are approximately 2% apart; this does not establish JSON extraction cost.</figcaption></figure><p>At the chart’s hourly rates of $2.50 for H100 and $0.34 for CPU, JSL Vision Structured costs $7.22 and $7.07 per 1,000 documents respectively, approximately 2% apart. This estimate covers the chart’s measured inference workload; it does not establish the cost of schema-constrained JSON extraction. The A10G estimate elsewhere in the article is separate from these measurements.</p><figure><img alt="Memory comparison for six models using bfloat16 on H100 GPU and float32 on CPU." src="https://cdn-images-1.medium.com/max/786/1*wR0Y9u2tUVYBeHF1R12l-g.png" /><figcaption>Memory usage in the separate hardware comparison. GPU and CPU runs use different precision; these values are not memory measurements for the 100-document OmniOCR JSON evaluation.</figcaption></figure><p>The memory chart compares bfloat16 GPU usage with float32 CPU usage. Account for precision and serving backend when sizing your deployment, then measure latency and memory with your own JSON schemas and representative clinical documents.</p><h3>Which OCR benchmark fits your document pipeline?</h3><p>Choose an evaluation that matches the output you need:</p><ul><li><a href="https://www.johnsnowlabs.com/bbox-ocr-benchmark-1-out-of-15-including-every-frontier-api/">Grounded OCR on FUNSD</a> evaluates recognized text with bounding-box coordinates.</li><li><a href="https://www.johnsnowlabs.com/plain-text-ocr-benchmark-the-gap-between-on-prem-and-api-is-gone/">Plain-text OCR on FUNSD</a> evaluates full-page transcription for search and downstream text processing.</li><li>This schema-constrained OCR comparison evaluates extraction into a supplied JSON Schema on OmniOCR.</li></ul><p>GPT-5.2 led the JSON evaluation at 0.888. JSL Vision Structured had the highest self-hosted score in the published comparison, with 0.730 reported in the prose and 0.714 shown in the chart. For your deployment, assess field accuracy and output validation together, then measure the cost of handling failures.</p><p><a href="https://www.johnsnowlabs.com/schedule-a-demo/">Schedule a demo</a> to evaluate JSL Vision Structured with your document types and schemas.</p><h3>Frequently asked questions about schema-constrained OCR</h3><h4>What is schema-constrained OCR?</h4><p>Schema-constrained OCR extracts values from a document image into a supplied JSON Schema. You define the fields and types, then validate the model’s output before downstream ingestion.</p><h4>Does valid JSON mean the extracted values are correct?</h4><p>No. A response can satisfy its schema while containing an incorrect value or missing information from the source document. Evaluate extraction accuracy separately from parsing and schema validity.</p><h4>Which model scored highest in this evaluation?</h4><p>GPT-5.2 led at 0.888 json-diff accuracy. JSL Vision Structured led the self-hosted comparison, with 0.730 in the article’s prose and 0.714 in its published chart.</p><h4>Did schema-aware decoding eliminate every empty prediction?</h4><p>No. The published failure chart shows 1 empty prediction out of 100 for JSL Vision Structured. Keep an explicit fallback or review path for missing and invalid results.</p><h4>Do the CPU and GPU charts measure JSON extraction?</h4><p>The hardware charts label a separate comparison on 5 FUNSD pages. Use those results as hardware context, then benchmark schema-constrained extraction on representative documents and schemas.</p><h4>Does self-hosting establish compliance for clinical documents?</h4><p>Self-hosting lets you process documents within your environment. Your deployment still needs appropriate access controls, logging, retention policies, and review against its applicable requirements.</p><h3>Appendix: complete model comparison and benchmark notes</h3><ul><li>Chart rank: 1; Model label in published chart: GPT-5.2; Json-diff accuracy ↑: 0.888</li><li>Chart rank: 2; Model label in published chart: Gemini 2.5 Flash; Json-diff accuracy ↑: 0.873</li><li>Chart rank: 3; Model label in published chart: Gemini 2.5 Pro; Json-diff accuracy ↑: 0.840</li><li>Chart rank: 4; Model label in published chart: Claude Opus 4.5; Json-diff accuracy ↑: 0.800</li><li>Chart rank: 5; Model label in published chart: JSL Vision Structured; Json-diff accuracy ↑: 0.714</li><li>Chart rank: 6; Model label in published chart: Claude Sonnet 4.5; Json-diff accuracy ↑: 0.709</li><li>Chart rank: 7; Model label in published chart: JSL Vision; Json-diff accuracy ↑: 0.689</li><li>Chart rank: 8; Model label in published chart: Holo2–30B-A3B; Json-diff accuracy ↑: 0.684</li><li>Chart rank: 9; Model label in published chart: Qwen3-VL-8B; Json-diff accuracy ↑: 0.676</li><li>Chart rank: 10; Model label in published chart: Pixtral-Large; Json-diff accuracy ↑: 0.670</li><li>Chart rank: 11; Model label in published chart: Llama-4-Maverick; Json-diff accuracy ↑: 0.668</li><li>Chart rank: 12; Model label in published chart: Nanonets-OCR2–3B; Json-diff accuracy ↑: 0.593</li><li>Chart rank: 13; Model label in published chart: OCRFlux-3B; Json-diff accuracy ↑: 0.496</li><li>Chart rank: 14; Model label in published chart: Qwen3-VL-235B; Json-diff accuracy ↑: 0.488</li><li>Chart rank: 15; Model label in published chart: Phi-4-Multimodal; Json-diff accuracy ↑: 0.383</li><li>Chart rank: 16; Model label in published chart: JSL Vision OCR (no schema decoding); Json-diff accuracy ↑: 0.342</li><li>Chart rank: 17; Model label in published chart: Grok-4; Json-diff accuracy ↑: 0.255</li><li>Chart rank: 18; Model label in published chart: Sonar Pro; Json-diff accuracy ↑: 0.134</li><li>Chart rank: 19; Model label in published chart: PaddleOCR-VL; Json-diff accuracy ↑: 0.033</li></ul><p>Higher json-diff accuracy is better. The appendix list reproduces the published 19-row leaderboard. The prose separately reports JSL Vision Structured-8B at 0.730 and olmOCR-7B at 0.714; that additional olmOCR row is absent from the chart.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a5215e02465" width="1" height="1" alt=""><hr><p><a href="https://medium.com/john-snow-labs/schema-constrained-ocr-the-benchmark-that-actually-matters-in-production-7a5215e02465">Schema-Constrained OCR: The Benchmark That Actually Matters in Production</a> was originally published in <a href="https://medium.com/john-snow-labs">John Snow Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[De-identifying Whole Slide Images (WSI): Deploying on SageMaker — Part 3]]></title>
            <link>https://medium.com/john-snow-labs/de-identifying-whole-slide-images-wsi-deploying-on-sagemaker-part-3-25a4c57805c4?source=rss-9e09bb71b869------2</link>
            <guid isPermaLink="false">https://medium.com/p/25a4c57805c4</guid>
            <category><![CDATA[healthcare-ai]]></category>
            <category><![CDATA[medical-imaging]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws-sagemaker]]></category>
            <category><![CDATA[phi]]></category>
            <dc:creator><![CDATA[Christian Kasim Loan]]></dc:creator>
            <pubDate>Tue, 18 Nov 2025 16:10:16 GMT</pubDate>
            <atom:updated>2025-11-18T16:10:16.263Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>De-identifying Whole Slide Images (WSI): Deploying on SageMaker — Part 3</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*IG0NVJQDCmPU5rL-n-6bmw.png" /></figure><p>Protected health information (PHI) is often embedded in SVS files used by healthcare professionals. As explained in Part 1, this PHI must be removed before sharing or analyzing data for research, AI training, or diagnostics.</p><p>Here’s how to quickly set up SVS DEID on AWS SageMaker in just a few minutes:</p><h3>1. Import the listing from AWS Marketplace</h3><p>1.1 Visit the <a href="http://SVS Images De-identification">SVS Images De-identification listing on AWS Marketplace</a>, and click <strong>Continue to Subscribe</strong>.<br> 1.2 Review and accept the EULA, pricing, and support terms.<br> 1.3 Click <strong>Continue to Configuration</strong>, choose a region, and copy the <strong>Product ARN</strong> shown. You’ll use it when creating a deployable model with Boto3.</p><h3>2. Deploy the imported model as endpoint</h3><p>Choose your instance type based on your performance and cost preferences. You can refer to the provided benchmarks for guidance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*Rlbuh2nlSI2UrnE-kllx2A.png" /><figcaption>Benchmarked Instances and files</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*peIdrc3lOC_w8Q4VGvgX3w.png" /><figcaption>Benchmark Results</figcaption></figure><p><strong>While deploying make sure to</strong>:</p><ul><li>Select <strong>async configuration</strong> and provide the S3 path where DEID output files will be stored.</li><li>SageMaker role has read/write access to the output S3 folder, and read access to an input folder</li></ul><h3>3. Test the model</h3><h4><strong>3.1 Upload input SVS file to S3</strong></h4><pre># Step 1: Download the SVS file from GitHub<br>svs_url = &quot;https://raw.githubusercontent.com/JohnSnowLabs/visual-nlp-workshop/refs/heads/master/emr/input3.svs&quot;<br>file_name = svs_url.split(&#39;/&#39;)[-1]<br>response = requests.get(svs_url)<br>with open(local_path, &quot;wb&quot;) as f:<br>   f.write(response.content)<br><br># Step 2: Upload to S3<br>s3_client.upload_file(file_name, &quot;svs-sage-input&quot;, file_name)<br>print(f&quot;Uploaded {file} to s3://{bucket_name}/{s3_key}&quot;)</pre><h4>3.2 Deploy Model with model ARN</h4><pre>model_package_arn = &#39;arn:aws:sagemaker:YOUR ARN FROM STEP 1&#39;<br>model = ModelPackage(<br>    role=role,<br>    model_package_arn=model_package_arn,<br>    sagemaker_session=session,<br>)<br>model.deploy(<br>    initial_instance_count=1,<br>    instance_type=&#39;ml.m5.2xlarge&#39;,<br>    endpoint_name=&#39;svsdeid&#39;,<br>    async_inference_config=AsyncInferenceConfig(<br>        output_path=&quot;s3://svs-sage-output/outputs/&quot;<br>    )<br>)<br>model.endpoint_name</pre><h4>3.3 Call the endpoint with s3 SVS file path</h4><pre>sm_runtime = boto_session.client(&quot;sagemaker-runtime&quot;, region_name=&#39;us-east-1&#39;)  <br>response = sm_runtime.invoke_endpoint_async(  <br>    EndpointName=&#39;svsdeid&#39;,  <br>    ContentType=&#39;application/octet-stream&#39;,  <br>    InputLocation=&#39;s3://svs-sage-input/input1.svs&#39;,  <br>    Accept=&#39;application/octet-stream&#39;,  <br>)  <br>response</pre><p><strong>Optional</strong>: Specify tags to remove:</p><pre>deid_tags = [<br>    &#39;ImageDescription.ScanScope ID&#39;,<br>    &#39;ImageDescription.Time Zone&#39;,<br>    &#39;ImageDescription.ScannerType&#39;,<br>    ]<br>custom_attributes = f&quot;svs_tags={&#39;,&#39;.join(deid_tags)}&quot;<br>response = sm_runtime.invoke_endpoint_async(<br>    EndpointName=endpoint_name,<br>    ContentType=&#39;application/octet-stream&#39;,<br>    InputLocation=input_s3_path,<br>    Accept=&#39;application/octet-stream&#39;,<br>    CustomAttributes=custom_attributes<br>)</pre><p>While its processing you can check the endpoint logs in the Sagemaker Endpoint UI if the permissions are fine and the processing has started.</p><p>The response will look like</p><pre>{<br>  &quot;OutputLocation&quot;: &quot;s3://svs-sage-output/outputs/uuid.out&quot;,<br>  ...<br>}</pre><p>You can find more indepth Python tutorial in <a href="https://github.com/JohnSnowLabs/visual-nlp-workshop/blob/master/jupyter/SparkOCRWSIDeidentificationSagemaker.ipynb">this notebook</a></p><blockquote><strong>Note:</strong> Only <strong>async</strong> processing is supported. Synchronous (invoke_endpoint) calls will timeout.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LK0-HEE8v_WSkobTE9gCQw.png" /></figure><p>Now you have a fully working SVS DEID API at your fingertips, enjoy!</p><p>Refences:<br>- Part 1<br>- Part 2<br>- <a href="https://aws.amazon.com/marketplace/pp/prodview-kh7vsfj4pwxry">SVS DEID Sagemaker Marketplace Listing</a><br>- <a href="https://nlp.johnsnowlabs.com/2025/06/16/svs_pipe_en.html">SVS DEID Modelhub<br></a>- <a href="https://github.com/JohnSnowLabs/visual-nlp-workshop/blob/master/jupyter/SparkOCRWSIDeidentificationSagemaker.ipynb">SVS DEID Sagemaker Notebook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25a4c57805c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/john-snow-labs/de-identifying-whole-slide-images-wsi-deploying-on-sagemaker-part-3-25a4c57805c4">De-identifying Whole Slide Images (WSI): Deploying on SageMaker — Part 3</a> was originally published in <a href="https://medium.com/john-snow-labs">John Snow Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1 line to BIOBERT Word Embeddings with NLU in Python]]></title>
            <link>https://medium.com/spark-nlp/1-line-to-biobert-word-embeddings-with-nlu-in-python-7224ab52e131?source=rss-9e09bb71b869------2</link>
            <guid isPermaLink="false">https://medium.com/p/7224ab52e131</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[bert]]></category>
            <dc:creator><![CDATA[Christian Kasim Loan]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 18:37:00 GMT</pubDate>
            <atom:updated>2021-01-17T18:37:00.422Z</atom:updated>
            <content:encoded><![CDATA[<h3>1 line to BioBERT Word Embeddings with NLU in Python</h3><p>Including Part of Speech, Named Entity Recognition, Emotion Classification in the same line! With Bonus t-SNE plots!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrhD07MhQrvjaSqFcLMvrw.jpeg" /></figure><h3>0. Introduction</h3><h3>0.1 What is NLU?</h3><p><a href="http://nlu.johnsnowlabs.com/">John Snow Labs NLU library</a> gives you 1000+ NLP models and 100+ Word Embeddings in 300+ languages and infinite possibilities to explore your data and gain insights.</p><p>In this tutorial, we will cover how to get the powerful <a href="https://arxiv.org/abs/1810.04805">BioB</a>ERT Embeddings with 1 line of NLU code and then how to visualize them with t-SNE. We will compare Comparing Sentiment with Sarcasm and Emotions!</p><h3>0.2 What is t-SNE?</h3><p>T-SNE is a tool to visualize high-dimensional data. It converts similarities between data points to joint probabilities and tries to minimize the Kullback-Leibler divergence between the joint probabilities of the low-dimensional embedding and the high-dimensional data. t-SNE has a cost function that is not convex, i.e. with different initializations we can get different results.</p><h3>0.3 What is BioBERT?</h3><p>Biomedical text mining is becoming increasingly important as the number of biomedical documents rapidly grows. With the progress in natural language processing (NLP), extracting valuable information from biomedical literature has gained popularity among researchers, and deep learning has boosted the development of effective biomedical text mining models. However, directly applying the advancements in NLP to biomedical text mining often yields unsatisfactory results due to a word distribution shift from general domain corpora to biomedical corpora. BioBERT (Bidirectional Encoder Representations from Transformers for Biomedical Text Mining) is a domain-specific language representation model pre-trained on large-scale biomedical corpora. With almost the same architecture across tasks, BioBERT largely outperforms BERT and previous state-of-the-art models in a variety of biomedical text mining tasks when pre-trained on biomedical corpora. While BERT obtains performance comparable to that of previous state-of-the-art models, BioBERT significantly outperforms them on the following three representative biomedical text mining tasks: biomedical named entity recognition (0.62% F1 score improvement), biomedical relation extraction (2.80% F1 score improvement) and biomedical question answering (12.24% MRR improvement). Analysis results show that pre-training BERT on biomedical corpora helps it to understand complex biomedical texts.</p><h3>1. Import NLU, load BioBERT, and embed a sample string in 1 line</h3><pre>nlu.load(&#39;biobert&#39;).predict(&#39;He was suprised by the diversity of NLU&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4CQLAvHMK6Emko9IptTzQ.png" /></figure><h3>2. Load a larger dataset</h3><p>The following snippet will download a Reddit sarcasm dataset and load it to a Pandas Dataframe</p><pre>import pandas as pd</pre><pre># Download the dataset</pre><pre>! wget -N <a href="https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/sarcasm/train-balanced-sarcasm.csv">https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/sarcasm/train-balanced-sarcasm.csv</a> -P /tmp</pre><pre># Load dataset to Pandasdf = pd.read_csv(&#39;/tmp/train-balanced-sarcasm.csv&#39;)</pre><pre>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1xJyiRhNswLD6hsyb94sg.png" /></figure><h3>3. Predict on the dataset and also add Part of Speech, Emotion and Sentiment Classifiers</h3><p>Since adding additional classifiers and getting their predictions is so easy in NLU, we will extend our NLU pipeline with a POS, Emotion, and Sentiment classifier which all achieve results close to the state of the art.</p><p>Those extra predictions will also come in handy when plotting our results.<br>We are limiting ourselves to a subsection of the dataset because our RAM is sadly limited and we are not running on a cluster. With <a href="http://nlp.johnsnowlabs.com/">Spark NLP</a> you can take exactly the same models and run them in a scalable fashion inside of a Spark cluster</p><pre>pipe = nlu.load(&#39;pos sentiment emotion biobert&#39;)</pre><pre>df[&#39;text&#39;] = df[&#39;comment&#39;]</pre><pre># NLU to gives us one row per embedded word by specifying the output level<br>predictions = pipe.predict(df[[&#39;text&#39;,&#39;label&#39;]], output_level=&#39;token&#39;)</pre><pre>predictions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIduVCmU48wEoHYXmvoS6A.png" /></figure><h3>4. Emotion Plots</h3><p>We can quickly plot the distribution of predicted emotions using pandas functions on the data frame</p><pre># Some Tokens are None which we must drop first</pre><pre>predictions.dropna(how=&#39;any&#39;, inplace=True)</pre><pre># Some sentiment are &#39;na&#39; which we must drop first</pre><pre>predictions = predictions[predictions.emotion!= &#39;na&#39;]</pre><pre>predictions.emotion.value_counts().plot.bar(title=&#39;Dataset emotion distribution&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3oTQ7UXXYO8Ala_mO8_wg.png" /></figure><h3>5. Prepare data for T-SNE</h3><p>We prepare the data for the T-SNE algorithm by collecting them in a matrix for TSNE</p><pre>import numpy as np</pre><pre>mat = np.matrix([x for x in predictions.biobert_embeddings])</pre><h3>6. Fit T-SNE</h3><p>Finally, we fit the T-SNE algorithm and get our 2-Dimensional representation of our Biobert Word Embeddings</p><pre>from sklearn.manifold import TSNE</pre><pre>model = TSNE(n_components=2)</pre><pre>low_dim_data = model.fit_transform(mat)</pre><pre>print(&#39;Lower dim data has shape&#39;,low_dim_data.shape)</pre><h3>7. Plot BioBERT Word Embeddings, colored by Part of Speech Tag</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word in a sentence and the color represents the POS class that word belongs to.tsne_df = pd.DataFrame(low_dim_data, predictions.pos)ax = sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)ax.set_title(‘T-SNE BIOBERT Embeddings, colored by Part of Speech Tag’)</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.pos)</pre><pre>ax = sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE BIOBERT Embeddings, colored by Part of Speech Tag&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HfHuhbfpI1LcRrfAwJ4z5g.png" /></figure><h3>8. Plot Plot Biobert Word Embeddings, colored by Emotion</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified with a particular emotion, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.emotion)</pre><pre>ax =  sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE BIOBERT Embeddings, colored by Emotion&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBb4Qi83XkCooo2gj4CsmA.png" /></figure><h3>9. Plot Plot Biobert Word Embeddings, colored by Sarcasm</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified as sarcastic or not, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.label.replace({1:&#39;sarcasm&#39;,0:&#39;normal&#39;}))<br>tsne_df.columns=[&#39;x&#39;,&#39;y&#39;]</pre><pre>ax = sns.scatterplot(data=tsne_df, x=&#39;x&#39;, y=&#39;y&#39;, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE BIOBERT Embeddings, colored by Sarcasm label&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZyW06-0A3IiHhNTJT-Cpbw.png" /></figure><h3>9. Plot Plot Biobert Word Embeddings, colored by Sentiment</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified as sarcastic or not, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.sentiment)</pre><pre>tsne_df.columns = [&#39;x&#39;,&#39;y&#39;]</pre><pre>ax = sns.scatterplot(data=tsne_df, x=&#39;x&#39;, y=&#39;y&#39;, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE BIOBERT Embeddings, colored by Sentiment&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZyW06-0A3IiHhNTJT-Cpbw.png" /></figure><h3>10. There are many many more word Embeddings!</h3><p>To view all word embeddings, type the following command</p><pre>nlu.print_all_model_kinds_for_action(&#39;embed&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*VgAQnS_2BImpqoxTsa3BCw.png" /></figure><h3>More NLU Medium articles</h3><ul><li><a href="https://medium.com/@christian.kasim.loan/1-line-of-code-350-nlp-models-with-john-snow-labs-nlu-in-python-2f1c55bba619?sk=1379426a00ca970a6e101a8f74f66bd2">Introduction to NLU</a></li><li><a href="https://medium.com/spark-nlp/1-line-of-code-for-bert-albert-elmo-electra-xlnet-glove-part-of-speech-with-nlu-and-t-sne-9ebcd5379cd">One line of Python code for 6 Embeddings, BERT, ALBERT, ELMO, ELECTRA, XLNET, GLOVE, Part of Speech with NLU and t-SNE</a></li><li><a href="https://medium.com/spark-nlp/1-line-to-bert-word-embeddings-with-nlu-f50d2b08cddc?source=collection_home---4------1-----------------------">One-Line Bert Embeddings and t-SNE plots with NLU</a></li><li><a href="https://medium.com/spark-nlp/easy-sentence-similarity-with-bert-sentence-embeddings-using-john-snow-labs-nlu-ea078deb6ebf">Easy sentence similarity with BERT Sentence Embeddings using John Snow Labs NLU</a></li></ul><h3>NLU Talks</h3><ul><li><a href="https://www.nlpsummit.org/john-snow-labs-nlu-the-simplicity-of-python-the-power-of-spark-nlp/">NLP Summit 2020: John Snow Labs NLU: The simplicity of Python, the power of Spark NLP</a></li><li><a href="https://events.johnsnowlabs.com/john-snow-labs-nlu-become-a-data-science-superhero-with-one-line-of-python-code?hsCtaTracking=c659363c-2188-4c86-945f-5cfb7b42fcfc%7C8b2b188b-92a3-48ba-ad7e-073b384425b0">John Snow Labs NLU: Become a Data Science Superhero with One Line of Python code</a></li><li><a href="https://events.johnsnowlabs.com/language-detection-and-multi-lingual-text-mining-in-spark-nlp?hsCtaTracking=a3ee2983-7573-4d1d-bdba-ab7e69c851d0%7C54acc61c-99a8-465c-a163-bdd93d7c41a8">Language Detection and Multi-lingual Text Mining in Spark NLP</a></li></ul><h3>More about NLU</h3><ul><li><a href="https://nlu.johnsnowlabs.com/">NLU website</a></li><li><a href="https://github.com/JohnSnowLabs/nlu">NLU Github</a></li><li><a href="https://nlu.johnsnowlabs.com/docs/en/examples">NLU Documentation</a></li><li><a href="https://join.slack.com/t/spark-nlp/shared_invite/zt-7rd4kw03-7F44zohcrUo0RULCd8rYrw">Having questions or wanna share an idea? Join us on Slack!</a></li><li><a href="https://nlu.johnsnowlabs.com/docs/en/notebooks">Overview of all NLU example notebooks</a></li><li><a href="https://colab.research.google.com/drive/1_sgbJV3dYPZ_Q7acCgKWgqZkWcKAfg79?usp=sharing">Named Entity Recognition (NER) 18 class notebook</a></li><li><a href="https://colab.research.google.com/drive/1tW833T3HS8F5Lvn6LgeDd5LW5226syKN?usp=sharing">Part of Speech (POS) notebook</a></li><li><a href="https://colab.research.google.com/drive/1Rg1vdSeq6sURc48RV8lpS47ja0bYwQmt?usp=sharing">BERT Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/18yd9pDoPkde79boTbAC8Xd03ROKisPsn?usp=sharing">ALBERT Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1TtNYB9z0yH8d1ZjfxkH0TVxQ2O_iOYVV?usp=sharing">ELMO Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1C9T29QA00yjLuJ1yEMTbjUQMpUv35pHb?usp=sharing">XLNET Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1bnRR8FygiiN3zJz3mRdbjPBUvFsx6IVB?usp=sharing">Spellchecking</a></li><li><a href="https://colab.research.google.com/drive/1KXUqcF8e-LU9cXnHE8ni8z758LuFPvY7?usp=sharing">Typed Dependency Parsing</a> notebook</li></ul><h3>Link to the Notebook</h3><ul><li><a href="https://colab.research.google.com/drive/1llANd-XGD8vkGNMcqTi_8Dr_Ys6cr83W?usp=sharing">BIOBERT Word Embeddings and t-SNE plotting</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7224ab52e131" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spark-nlp/1-line-to-biobert-word-embeddings-with-nlu-in-python-7224ab52e131">1 line to BIOBERT Word Embeddings with NLU in Python</a> was originally published in <a href="https://medium.com/spark-nlp">spark-nlp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1 line to ELECTRA Word Embeddings with NLU in Python]]></title>
            <link>https://medium.com/spark-nlp/1-line-to-electra-word-embeddings-with-nlu-in-python-25f749bf3e92?source=rss-9e09bb71b869------2</link>
            <guid isPermaLink="false">https://medium.com/p/25f749bf3e92</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Christian Kasim Loan]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 18:36:30 GMT</pubDate>
            <atom:updated>2021-01-17T18:36:47.678Z</atom:updated>
            <content:encoded><![CDATA[<p>Including Part of Speech, Named Entity Recognition, Emotion Classification in the same line! With Bonus t-SNE plots!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSuQA_bEd2ZodFb5iS6VjQ.jpeg" /></figure><p>-</p><h3>0. Introduction</h3><ul><li><a href="https://nlp.stanford.edu/pubs/glove.pdf">GLOVE Paper</a></li></ul><h3>0.1 What is NLU?</h3><p><a href="http://nlu.johnsnowlabs.com/">John Snow Labs NLU library</a> gives you 1000+ NLP models and 100+ Word Embeddings in 300+ languages and infinite possibilities to explore your data and gain insights.</p><p>In this tutorial, we will cover how to get the powerful <a href="https://arxiv.org/abs/2003.10555">Electra</a> Embeddings with 1 line of NLU code and then how to visualize them with t-SNE. We will compare Comparing Sentiment with Sarcasm and Emotions!</p><h3>0.2 What is t-SNE?</h3><p>T-SNE is a tool to visualize high-dimensional data. It converts similarities between data points to joint probabilities and tries to minimize the Kullback-Leibler divergence between the joint probabilities of the low-dimensional embedding and the high-dimensional data. t-SNE has a cost function that is not convex, i.e. with different initializations we can get different results.</p><h3>0.3 What is Electra?</h3><p>Masked language modeling (MLM) pre-training methods such as BERT corrupt the input by replacing some tokens with [MASK] and then train a model to reconstruct the original tokens. While they produce good results when transferred to downstream NLP tasks, they generally require large amounts of compute to be effective. As an alternative, a more sample-efficient pre-training task called replaced token detection is proposed. Instead of masking the input, the approach corrupts it by replacing some tokens with plausible alternatives sampled from a small generator network. Then, instead of training a model that predicts the original identities of the corrupted tokens, Electra trains a discriminative model that predicts whether each token in the corrupted input was replaced by a generator sample or not. Thorough experiments demonstrate this new pre-training task is more efficient than MLM because the task is defined over all input tokens rather than just the small subset that was masked out. As a result, the contextual representations learned this approach substantially outperform the ones learned by BERT given the same model size, data, and compute. The gains are particularly strong for small models; for example, a model was trained on one GPU for 4 days that outperforms GPT (trained using 30x more compute) on the GLUE natural language understanding benchmark. The approach also works well at scale, where it performs comparably to RoBERTa and XLNet while using less than 1/4 of their compute and outperforms them when using the same amount of compute.</p><h3>1. Import NLU, load Electra, and embed a sample string in 1 line</h3><pre>nlu.load(&#39;electra&#39;).predict(&#39;He was suprised by the diversity of NLU&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Wz3BiFkXA7trXQ0Z1oD5A.png" /></figure><h3>2. Load a larger dataset</h3><p>The following snippet will download a Reddit sarcasm dataset and load it to a Pandas Dataframe</p><pre>import pandas as pd</pre><pre># Download the dataset</pre><pre>! wget -N <a href="https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/sarcasm/train-balanced-sarcasm.csv">https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/sarcasm/train-balanced-sarcasm.csv</a> -P /tmp</pre><pre># Load dataset to Pandasdf = pd.read_csv(&#39;/tmp/train-balanced-sarcasm.csv&#39;)</pre><pre>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1xJyiRhNswLD6hsyb94sg.png" /></figure><h3>3. Predict on the dataset and also add Part of Speech, Emotion and Sentiment Classifiers</h3><p>Since adding additional classifiers and getting their predictions is so easy in NLU, we will extend our NLU pipeline with a POS, Emotion, and Sentiment classifier which all achieve results close to the state of the art.</p><p>Those extra predictions will also come in handy when plotting our results.<br>We are limiting ourselves to a subsection of the dataset because our RAM is sadly limited and we are not running on a cluster. With <a href="http://nlp.johnsnowlabs.com/">Spark NLP</a> you can take exactly the same models and run them in a scalable fashion inside of a Spark cluster</p><pre>pipe = nlu.load(&#39;pos sentiment emotion electra&#39;)</pre><pre>df[&#39;text&#39;] = df[&#39;comment&#39;]</pre><pre># NLU to gives us one row per embedded word by specifying the output level<br>predictions = pipe.predict(df[[&#39;text&#39;,&#39;label&#39;]], output_level=&#39;token&#39;)</pre><pre>predictions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mI5S-Y0-mbsq3EQppylY_A.png" /></figure><h3>4. Emotion Plots</h3><p>We can quickly plot the distribution of predicted emotions using pandas functions on the data frame</p><pre># Some Tokens are None which we must drop first</pre><pre>predictions.dropna(how=&#39;any&#39;, inplace=True)</pre><pre># Some sentiment are &#39;na&#39; which we must drop first</pre><pre>predictions = predictions[predictions.emotion!= &#39;na&#39;]</pre><pre>predictions.emotion.value_counts().plot.bar(title=&#39;Dataset emotion distribution&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3oTQ7UXXYO8Ala_mO8_wg.png" /></figure><h3>5. Prepare data for T-SNE</h3><p>We prepare the data for the T-SNE algorithm by collecting them in a matrix for TSNE</p><pre>import numpy as np</pre><pre>mat = np.matrix([x for x in predictions.electra_embeddings])</pre><h3>6. Fit T-SNE</h3><p>Finally, we fit the T-SNE algorithm and get our 2-Dimensional representation of our Electra Word Embeddings</p><pre>from sklearn.manifold import TSNE</pre><pre>model = TSNE(n_components=2)</pre><pre>low_dim_data = model.fit_transform(mat)</pre><pre>print(&#39;Lower dim data has shape&#39;,low_dim_data.shape)</pre><h3>7. Plot ELECTRA Word Embeddings, colored by Part of Speech Tag</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word in a sentence and the color represents the POS class that word belongs to.tsne_df = pd.DataFrame(low_dim_data, predictions.pos)ax = sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)ax.set_title(‘T-SNE ELECTRA Embeddings, colored by Part of Speech Tag’)</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.pos)</pre><pre>ax = sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE ELECTRA Embeddings, colored by Part of Speech Tag&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VFn7jhWepmrOKVKbuKYV7w.png" /></figure><h3>8. Plot Plot Electra Word Embeddings, colored by Emotion</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified with a particular emotion, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.emotion)</pre><pre>ax =  sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE ElECTRA Embeddings, colored by Emotion&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-SSFFfGQMFHyL00zXgkqA.png" /></figure><h3>9. Plot Plot Electra Word Embeddings, colored by Sarcasm</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified as sarcastic or not, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.label.replace({1:&#39;sarcasm&#39;,0:&#39;normal&#39;}))<br>tsne_df.columns=[&#39;x&#39;,&#39;y&#39;]</pre><pre>ax = sns.scatterplot(data=tsne_df, x=&#39;x&#39;, y=&#39;y&#39;, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE ELECTRA Embeddings, colored by Sarcasm label&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UbTGkqNQSyPGE4VlEXk3ww.png" /></figure><h3>10. There are many many more word Embeddings!</h3><p>To view all word embeddings, type the following command</p><pre>nlu.print_all_model_kinds_for_action(&#39;embed&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*VgAQnS_2BImpqoxTsa3BCw.png" /></figure><h3>More NLU Medium articles</h3><ul><li><a href="https://medium.com/@christian.kasim.loan/1-line-of-code-350-nlp-models-with-john-snow-labs-nlu-in-python-2f1c55bba619?sk=1379426a00ca970a6e101a8f74f66bd2">Introduction to NLU</a></li><li><a href="https://medium.com/spark-nlp/1-line-of-code-for-bert-albert-elmo-electra-xlnet-glove-part-of-speech-with-nlu-and-t-sne-9ebcd5379cd">One line of Python code for 6 Embeddings, BERT, ALBERT, ELMO, ELECTRA, XLNET, GLOVE, Part of Speech with NLU and t-SNE</a></li><li><a href="https://medium.com/spark-nlp/1-line-to-bert-word-embeddings-with-nlu-f50d2b08cddc?source=collection_home---4------1-----------------------">One-Line Bert Embeddings and t-SNE plots with NLU</a></li><li><a href="https://medium.com/spark-nlp/easy-sentence-similarity-with-bert-sentence-embeddings-using-john-snow-labs-nlu-ea078deb6ebf">Easy sentence similarity with BERT Sentence Embeddings using John Snow Labs NLU</a></li></ul><h3>NLU Talks</h3><ul><li><a href="https://www.nlpsummit.org/john-snow-labs-nlu-the-simplicity-of-python-the-power-of-spark-nlp/">NLP Summit 2020: John Snow Labs NLU: The simplicity of Python, the power of Spark NLP</a></li><li><a href="https://events.johnsnowlabs.com/john-snow-labs-nlu-become-a-data-science-superhero-with-one-line-of-python-code?hsCtaTracking=c659363c-2188-4c86-945f-5cfb7b42fcfc%7C8b2b188b-92a3-48ba-ad7e-073b384425b0">John Snow Labs NLU: Become a Data Science Superhero with One Line of Python code</a></li><li><a href="https://events.johnsnowlabs.com/language-detection-and-multi-lingual-text-mining-in-spark-nlp?hsCtaTracking=a3ee2983-7573-4d1d-bdba-ab7e69c851d0%7C54acc61c-99a8-465c-a163-bdd93d7c41a8">Language Detection and Multi-lingual Text Mining in Spark NLP</a></li></ul><h3>More about NLU</h3><ul><li><a href="https://nlu.johnsnowlabs.com/">NLU website</a></li><li><a href="https://github.com/JohnSnowLabs/nlu">NLU Github</a></li><li><a href="https://nlu.johnsnowlabs.com/docs/en/examples">NLU Documentation</a></li><li><a href="https://join.slack.com/t/spark-nlp/shared_invite/zt-7rd4kw03-7F44zohcrUo0RULCd8rYrw">Having questions or wanna share an idea? Join us on Slack!</a></li><li><a href="https://nlu.johnsnowlabs.com/docs/en/notebooks">Overview of all NLU example notebooks</a></li><li><a href="https://colab.research.google.com/drive/1_sgbJV3dYPZ_Q7acCgKWgqZkWcKAfg79?usp=sharing">Named Entity Recognition (NER) 18 class notebook</a></li><li><a href="https://colab.research.google.com/drive/1tW833T3HS8F5Lvn6LgeDd5LW5226syKN?usp=sharing">Part of Speech (POS) notebook</a></li><li><a href="https://colab.research.google.com/drive/1Rg1vdSeq6sURc48RV8lpS47ja0bYwQmt?usp=sharing">BERT Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/18yd9pDoPkde79boTbAC8Xd03ROKisPsn?usp=sharing">ALBERT Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1TtNYB9z0yH8d1ZjfxkH0TVxQ2O_iOYVV?usp=sharing">ELMO Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1C9T29QA00yjLuJ1yEMTbjUQMpUv35pHb?usp=sharing">XLNET Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1bnRR8FygiiN3zJz3mRdbjPBUvFsx6IVB?usp=sharing">Spellchecking</a></li><li><a href="https://colab.research.google.com/drive/1KXUqcF8e-LU9cXnHE8ni8z758LuFPvY7?usp=sharing">Typed Dependency Parsing</a> notebook</li></ul><h3>Link to the Notebook</h3><ul><li><a href="https://colab.research.google.com/drive/1FueGEaOj2JkbqHzdmxwKrNMHzgVt4baE?usp=sharing">ELECTRA Word Embeddings and t-SNE plotting</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25f749bf3e92" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spark-nlp/1-line-to-electra-word-embeddings-with-nlu-in-python-25f749bf3e92">1 line to ELECTRA Word Embeddings with NLU in Python</a> was originally published in <a href="https://medium.com/spark-nlp">spark-nlp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1 line to COVIDBERT Word Embeddings with NLU in Python]]></title>
            <link>https://medium.com/spark-nlp/1-line-to-covidbert-word-embeddings-with-nlu-in-python-e67396da2f78?source=rss-9e09bb71b869------2</link>
            <guid isPermaLink="false">https://medium.com/p/e67396da2f78</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Christian Kasim Loan]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 18:36:12 GMT</pubDate>
            <atom:updated>2021-01-17T18:36:12.126Z</atom:updated>
            <content:encoded><![CDATA[<p>Including Part of Speech, Named Entity Recognition, Emotion Classification in the same line! With Bonus t-SNE plots!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcvKPc-76045kFk2GqtGJg.jpeg" /></figure><h3>0. Introduction</h3><h3>0.1 What is NLU?</h3><p><a href="http://nlu.johnsnowlabs.com/">John Snow Labs NLU library</a> gives you 1000+ NLP models and 100+ Word Embeddings in 300+ languages and infinite possibilities to explore your data and gain insights.</p><p>In this tutorial, we will cover how to get the powerful <a href="https://arxiv.org/abs/2005.07503">Covidbert</a> Embeddings with 1 line of NLU code and then how to visualize them with t-SNE. We will compare Comparing Sentiment with Sarcasm and Emotions!</p><h3>0.2 What is t-SNE?</h3><p>T-SNE is a tool to visualize high-dimensional data. It converts similarities between data points to joint probabilities and tries to minimize the Kullback-Leibler divergence between the joint probabilities of the low-dimensional embedding and the high-dimensional data. t-SNE has a cost function that is not convex, i.e. with different initializations we can get different results.</p><h3>0.3 What is COVIDBERT?</h3><p><a href="https://arxiv.org/abs/2005.07503">COVID-Twitter-BERT (CT-BERT)</a> is a transformer-based model, pretrained on a large corpus of Twitter messages on the topic of COVID-19. The model shows a 10–30% marginal improvement compared to its base model, BERT-Large, on five different classification datasets. The largest improvements are on the target domain. Pretrained transformer models, such as CT-BERT, are trained on a specific target domain and can be used for a wide variety of natural language processing tasks, including classification, question-answering and chatbots. CT-BERT is optimised to be used on COVID-19 content, in particular social media posts from Twitter.</p><h3>1. Import NLU, load Covidbert, and embed a sample string in 1 line</h3><pre>nlu.load(&#39;covidbert&#39;).predict(&#39;He was suprised by the diversity of NLU&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTCkzpwAM0C_3UmSepfqUQ.png" /></figure><h3>2. Load a larger dataset</h3><p>The following snippet will download a Reddit sarcasm dataset and load it to a Pandas Dataframe</p><pre>import pandas as pd</pre><pre># Download the dataset</pre><pre>! wget -N <a href="https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/sarcasm/train-balanced-sarcasm.csv">https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/sarcasm/train-balanced-sarcasm.csv</a> -P /tmp</pre><pre># Load dataset to Pandasdf = pd.read_csv(&#39;/tmp/train-balanced-sarcasm.csv&#39;)</pre><pre>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1xJyiRhNswLD6hsyb94sg.png" /></figure><h3>3. Predict on the dataset and also add Part of Speech, Emotion and Sentiment Classifiers</h3><p>Since adding additional classifiers and getting their predictions is so easy in NLU, we will extend our NLU pipeline with a POS, Emotion, and Sentiment classifier which all achieve results close to the state of the art.</p><p>Those extra predictions will also come in handy when plotting our results.<br>We are limiting ourselves to a subsection of the dataset because our RAM is sadly limited and we are not running on a cluster. With <a href="http://nlp.johnsnowlabs.com/">Spark NLP</a> you can take exactly the same models and run them in a scalable fashion inside of a Spark cluster</p><pre>pipe = nlu.load(&#39;pos sentiment emotion covidbert&#39;)</pre><pre>df[&#39;text&#39;] = df[&#39;comment&#39;]</pre><pre># NLU to gives us one row per embedded word by specifying the output level<br>predictions = pipe.predict(df[[&#39;text&#39;,&#39;label&#39;]], output_level=&#39;token&#39;)</pre><pre>predictions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X5tWBwXW6R1iJui1n1yAYQ.png" /></figure><h3>4. Emotion Plots</h3><p>We can quickly plot the distribution of predicted emotions using pandas functions on the data frame</p><pre># Some Tokens are None which we must drop first</pre><pre>predictions.dropna(how=&#39;any&#39;, inplace=True)</pre><pre># Some sentiment are &#39;na&#39; which we must drop first</pre><pre>predictions = predictions[predictions.emotion!= &#39;na&#39;]</pre><pre>predictions.emotion.value_counts().plot.bar(title=&#39;Dataset emotion distribution&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3oTQ7UXXYO8Ala_mO8_wg.png" /></figure><h3>5. Prepare data for T-SNE</h3><p>We prepare the data for the T-SNE algorithm by collecting them in a matrix for TSNE</p><pre>import numpy as np</pre><pre>mat = np.matrix([x for x in predictions.covidbert_embeddings])</pre><h3>6. Fit T-SNE</h3><p>Finally, we fit the T-SNE algorithm and get our 2-Dimensional representation of our Covidbert Word Embeddings</p><pre>from sklearn.manifold import TSNE</pre><pre>model = TSNE(n_components=2)</pre><pre>low_dim_data = model.fit_transform(mat)</pre><pre>print(&#39;Lower dim data has shape&#39;,low_dim_data.shape)</pre><h3>7. Plot COVIDBERT Word Embeddings, colored by Part of Speech Tag</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word in a sentence and the color represents the POS class that word belongs to.tsne_df = pd.DataFrame(low_dim_data, predictions.pos)ax = sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)ax.set_title(‘T-SNE COVIDBERT Embeddings, colored by Part of Speech Tag’)</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.pos)</pre><pre>ax = sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE COVIDBERT Embeddings, colored by Part of Speech Tag&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4DlQCUn3kDNPdqiPZKMXw.png" /></figure><h3>8. Plot Plot Covidbert Word Embeddings, colored by Sarcasm</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified as sarcastic or not, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.label.replace({1:&#39;sarcasm&#39;,0:&#39;normal&#39;}))<br>tsne_df.columns=[&#39;x&#39;,&#39;y&#39;]</pre><pre>ax = sns.scatterplot(data=tsne_df, x=&#39;x&#39;, y=&#39;y&#39;, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE COVIDBERT Embeddings, colored by Sarcasm label&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ab6LB8cziK6GleorDbiHIA.png" /></figure><h3>9. Plot Plot Covidbert Word Embeddings, colored by Sentiment</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified as sarcastic or not, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.sentiment)</pre><pre>tsne_df.columns = [&#39;x&#39;,&#39;y&#39;]</pre><pre>ax = sns.scatterplot(data=tsne_df, x=&#39;x&#39;, y=&#39;y&#39;, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE COVIDBERT Embeddings, colored by Sentiment&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cU1vj7HF-nW7vyq13oiLA.png" /></figure><h3>10. There are many many more word Embeddings!</h3><p>To view all word embeddings, type the following command</p><pre>nlu.print_all_model_kinds_for_action(&#39;embed&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*VgAQnS_2BImpqoxTsa3BCw.png" /></figure><h3>More NLU Medium articles</h3><ul><li><a href="https://medium.com/@christian.kasim.loan/1-line-of-code-350-nlp-models-with-john-snow-labs-nlu-in-python-2f1c55bba619?sk=1379426a00ca970a6e101a8f74f66bd2">Introduction to NLU</a></li><li><a href="https://medium.com/spark-nlp/1-line-of-code-for-bert-albert-elmo-electra-xlnet-glove-part-of-speech-with-nlu-and-t-sne-9ebcd5379cd">One line of Python code for 6 Embeddings, BERT, ALBERT, ELMO, ELECTRA, XLNET, GLOVE, Part of Speech with NLU and t-SNE</a></li><li><a href="https://events.johnsnowlabs.com/john-snow-labs-nlu-become-a-data-science-superhero-with-one-line-of-python-code?hsCtaTracking=c659363c-2188-4c86-945f-5cfb7b42fcfc%7C8b2b188b-92a3-48ba-ad7e-073b384425b0">John Snow Labs NLU: Become a Data Science Superhero with One Line of Python code</a></li><li><a href="https://medium.com/spark-nlp/easy-sentence-similarity-with-bert-sentence-embeddings-using-john-snow-labs-nlu-ea078deb6ebf">Easy sentence similarity with BERT Sentence Embeddings using John Snow Labs NLU</a></li></ul><h3>NLU Talks</h3><ul><li><a href="https://www.nlpsummit.org/john-snow-labs-nlu-the-simplicity-of-python-the-power-of-spark-nlp/">NLP Summit 2020: John Snow Labs NLU: The simplicity of Python, the power of Spark NLP</a></li><li><a href="https://events.johnsnowlabs.com/john-snow-labs-nlu-become-a-data-science-superhero-with-one-line-of-python-code?hsCtaTracking=c659363c-2188-4c86-945f-5cfb7b42fcfc%7C8b2b188b-92a3-48ba-ad7e-073b384425b0">John Snow Labs NLU: Become a Data Science Superhero with One Line of Python code</a></li><li><a href="https://events.johnsnowlabs.com/language-detection-and-multi-lingual-text-mining-in-spark-nlp?hsCtaTracking=a3ee2983-7573-4d1d-bdba-ab7e69c851d0%7C54acc61c-99a8-465c-a163-bdd93d7c41a8">Language Detection and Multi-lingual Text Mining in Spark NLP</a></li></ul><h3>More about NLU</h3><ul><li><a href="https://nlu.johnsnowlabs.com/">NLU website</a></li><li><a href="https://github.com/JohnSnowLabs/nlu">NLU Github</a></li><li><a href="https://nlu.johnsnowlabs.com/docs/en/examples">NLU Documentation</a></li><li><a href="https://join.slack.com/t/spark-nlp/shared_invite/zt-7rd4kw03-7F44zohcrUo0RULCd8rYrw">Having questions or wanna share an idea? Join us on Slack!</a></li><li><a href="https://nlu.johnsnowlabs.com/docs/en/notebooks">Overview of all NLU example notebooks</a></li><li><a href="https://colab.research.google.com/drive/1_sgbJV3dYPZ_Q7acCgKWgqZkWcKAfg79?usp=sharing">Named Entity Recognition (NER) 18 class notebook</a></li><li><a href="https://colab.research.google.com/drive/1tW833T3HS8F5Lvn6LgeDd5LW5226syKN?usp=sharing">Part of Speech (POS) notebook</a></li><li><a href="https://colab.research.google.com/drive/1Rg1vdSeq6sURc48RV8lpS47ja0bYwQmt?usp=sharing">BERT Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/18yd9pDoPkde79boTbAC8Xd03ROKisPsn?usp=sharing">ALBERT Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1TtNYB9z0yH8d1ZjfxkH0TVxQ2O_iOYVV?usp=sharing">ELMO Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1C9T29QA00yjLuJ1yEMTbjUQMpUv35pHb?usp=sharing">XLNET Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1bnRR8FygiiN3zJz3mRdbjPBUvFsx6IVB?usp=sharing">Spellchecking</a></li><li><a href="https://colab.research.google.com/drive/1KXUqcF8e-LU9cXnHE8ni8z758LuFPvY7?usp=sharing">Typed Dependency Parsing</a> notebook</li></ul><h3>Link to the Notebook</h3><ul><li><a href="https://colab.research.google.com/drive/1Yzc-GuNQyeWewJh5USTN7PbbcJvd-D7s?usp=sharing">COVIDBERT Word Embeddings and t-SNE plotting</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e67396da2f78" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spark-nlp/1-line-to-covidbert-word-embeddings-with-nlu-in-python-e67396da2f78">1 line to COVIDBERT Word Embeddings with NLU in Python</a> was originally published in <a href="https://medium.com/spark-nlp">spark-nlp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1 line to ALBERT Word Embeddings with NLU in Python]]></title>
            <link>https://medium.com/spark-nlp/1-line-to-albert-word-embeddings-with-nlu-in-python-1691bc048ed1?source=rss-9e09bb71b869------2</link>
            <guid isPermaLink="false">https://medium.com/p/1691bc048ed1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Christian Kasim Loan]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 18:35:54 GMT</pubDate>
            <atom:updated>2021-01-17T18:35:54.796Z</atom:updated>
            <content:encoded><![CDATA[<p>Including Part of Speech, Named Entity Recognition, Emotion Classification in the same line! With Bonus t-SNE plots!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjflmKKvYvmEnUEJnxN3PA.jpeg" /></figure><h3>0. Introduction</h3><h3>0.1 What is NLU?</h3><p><a href="http://nlu.johnsnowlabs.com/">John Snow Labs NLU library</a> gives you 1000+ NLP models and 100+ Word Embeddings in 300+ languages and infinite possibilities to explore your data and gain insights.</p><p>In this tutorial, we will cover how to get the powerful <a href="https://arxiv.org/pdf/1909.11942.pdf">Albert</a> Embeddings with 1 line of NLU code and then how to visualize them with t-SNE. We will compare Comparing Sentiment with Sarcasm and Emotions!</p><h3>0.2 What is t-SNE?</h3><p>T-SNE is a tool to visualize high-dimensional data. It converts similarities between data points to joint probabilities and tries to minimize the Kullback-Leibler divergence between the joint probabilities of the low-dimensional embedding and the high-dimensional data. t-SNE has a cost function that is not convex, i.e. with different initializations we can get different results.</p><h3>0.3 What is ALBERT?</h3><p>Increasing model size when pretraining natural language representations often results in improved performance on downstream tasks. However, at some point scaling to larger machines becomes infeasible. To address this problem, two parameter reduction techniques are introduced which lower memory consumption and increase the training speed of BERT. This scales much better compared to the original BERT. A new self-supervised loss that focuses on modeling inter-sentence coherence is used. As a result, the best ALBERT model establishes new state-of-the-art results on the GLUE, RACE, and SQuAD benchmarks while having fewer parameters compared to BERT-large.</p><h3>1. Import NLU, load Albert, and embed a sample string in 1 line</h3><pre>nlu.load(&#39;albert&#39;).predict(&#39;He was suprised by the diversity of NLU&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KpPS4rAJ761B8O-uSKlFQ.png" /></figure><h3>2. Load a larger dataset</h3><p>The following snippet will download a Reddit sarcasm dataset and load it to a Pandas Dataframe</p><pre>import pandas as pd</pre><pre># Download the dataset</pre><pre>! wget -N <a href="https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/sarcasm/train-balanced-sarcasm.csv">https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/sarcasm/train-balanced-sarcasm.csv</a> -P /tmp</pre><pre># Load dataset to Pandasdf = pd.read_csv(&#39;/tmp/train-balanced-sarcasm.csv&#39;)</pre><pre>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1xJyiRhNswLD6hsyb94sg.png" /></figure><h3>3. Predict on the dataset and also add Part of Speech, Emotion and Sentiment Classifiers</h3><p>Since adding additional classifiers and getting their predictions is so easy in NLU, we will extend our NLU pipeline with a POS, Emotion, and Sentiment classifier which all achieve results close to the state of the art.</p><p>Those extra predictions will also come in handy when plotting our results.<br>We are limiting ourselves to a subsection of the dataset because our RAM is sadly limited and we are not running on a cluster. With <a href="http://nlp.johnsnowlabs.com/">Spark NLP</a> you can take exactly the same models and run them in a scalable fashion inside of a Spark cluster</p><pre>pipe = nlu.load(&#39;pos sentiment emotion albert&#39;)</pre><pre>df[&#39;text&#39;] = df[&#39;comment&#39;]</pre><pre># NLU to gives us one row per embedded word by specifying the output level<br>predictions = pipe.predict(df[[&#39;text&#39;,&#39;label&#39;]], output_level=&#39;token&#39;)</pre><pre>predictions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p-vY8gjnpMqAFUVBZn6QWA.png" /></figure><h3>4. Emotion Plots</h3><p>We can quickly plot the distribution of predicted emotions using pandas functions on the data frame</p><pre># Some Tokens are None which we must drop first</pre><pre>predictions.dropna(how=&#39;any&#39;, inplace=True)</pre><pre># Some sentiment are &#39;na&#39; which we must drop first</pre><pre>predictions = predictions[predictions.emotion!= &#39;na&#39;]</pre><pre>predictions.emotion.value_counts().plot.bar(title=&#39;Dataset emotion distribution&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3oTQ7UXXYO8Ala_mO8_wg.png" /></figure><h3>5. Prepare data for T-SNE</h3><p>We prepare the data for the T-SNE algorithm by collecting them in a matrix for TSNE</p><pre>import numpy as np</pre><pre>mat = np.matrix([x for x in predictions.albert_embeddings])</pre><h3>6. Fit T-SNE</h3><p>Finally, we fit the T-SNE algorithm and get our 2-Dimensional representation of our Albert Word Embeddings</p><pre>from sklearn.manifold import TSNE</pre><pre>model = TSNE(n_components=2)</pre><pre>low_dim_data = model.fit_transform(mat)</pre><pre>print(&#39;Lower dim data has shape&#39;,low_dim_data.shape)</pre><h3>7. Plot ALBERT Word Embeddings, colored by Part of Speech Tag</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word in a sentence and the color represents the POS class that word belongs to.tsne_df = pd.DataFrame(low_dim_data, predictions.pos)ax = sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)ax.set_title(‘T-SNE ALBERT Embeddings, colored by Part of Speech Tag’)</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.pos)</pre><pre>ax = sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE ALBERT Embeddings, colored by Part of Speech Tag&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5WkWVocSV8Ee4gHSvcG3wA.png" /></figure><h3>8. Plot Plot Albert Word Embeddings, colored by Emotion</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified with a particular emotion, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.emotion)</pre><pre>ax =  sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE ALBERT Embeddings, colored by Emotion&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zIxDb5dSfBrBK20085GHQw.png" /></figure><h3>9. Plot Plot Albert Word Embeddings, colored by Sarcasm</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified as sarcastic or not, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.label.replace({1:&#39;sarcasm&#39;,0:&#39;normal&#39;}))<br>tsne_df.columns=[&#39;x&#39;,&#39;y&#39;]</pre><pre>ax = sns.scatterplot(data=tsne_df, x=&#39;x&#39;, y=&#39;y&#39;, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE ALBERT Embeddings, colored by Sarcasm label&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jiAqE5Jzwv1Gu5etZDjrQ.png" /></figure><h3>9. Plot Plot Albert Word Embeddings, colored by Sentiment</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified as sarcastic or not, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.sentiment)</pre><pre>tsne_df.columns = [&#39;x&#39;,&#39;y&#39;]</pre><pre>ax = sns.scatterplot(data=tsne_df, x=&#39;x&#39;, y=&#39;y&#39;, hue=tsne_df.index)</pre><pre>ax.set_title(&#39;T-SNE ALBERT Embeddings, colored by Sentiment&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ygRamgyTJUQv24Bw1OMcKA.png" /></figure><h3>10. There are many many more word Embeddings!</h3><p>To view all word embeddings, type the following command</p><pre>nlu.print_all_model_kinds_for_action(&#39;embed&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*VgAQnS_2BImpqoxTsa3BCw.png" /></figure><h3>More NLU Medium articles</h3><ul><li><a href="https://medium.com/@christian.kasim.loan/1-line-of-code-350-nlp-models-with-john-snow-labs-nlu-in-python-2f1c55bba619?sk=1379426a00ca970a6e101a8f74f66bd2">Introduction to NLU</a></li><li><a href="https://medium.com/spark-nlp/1-line-of-code-for-bert-albert-elmo-electra-xlnet-glove-part-of-speech-with-nlu-and-t-sne-9ebcd5379cd">One line of Python code for 6 Embeddings, BERT, ALBERT, ELMO, ELECTRA, XLNET, GLOVE, Part of Speech with NLU and t-SNE</a></li><li><a href="https://medium.com/spark-nlp/1-line-to-bert-word-embeddings-with-nlu-f50d2b08cddc?source=collection_home---4------1-----------------------">One-Line Bert Embeddings and t-SNE plots with NLU</a></li><li><a href="https://medium.com/spark-nlp/easy-sentence-similarity-with-bert-sentence-embeddings-using-john-snow-labs-nlu-ea078deb6ebf">Easy sentence similarity with BERT Sentence Embeddings using John Snow Labs NLU</a></li></ul><h3>NLU Talks</h3><ul><li><a href="https://www.nlpsummit.org/john-snow-labs-nlu-the-simplicity-of-python-the-power-of-spark-nlp/">NLP Summit 2020: John Snow Labs NLU: The simplicity of Python, the power of Spark NLP</a></li><li><a href="https://events.johnsnowlabs.com/john-snow-labs-nlu-become-a-data-science-superhero-with-one-line-of-python-code?hsCtaTracking=c659363c-2188-4c86-945f-5cfb7b42fcfc%7C8b2b188b-92a3-48ba-ad7e-073b384425b0">John Snow Labs NLU: Become a Data Science Superhero with One Line of Python code</a></li><li><a href="https://events.johnsnowlabs.com/language-detection-and-multi-lingual-text-mining-in-spark-nlp?hsCtaTracking=a3ee2983-7573-4d1d-bdba-ab7e69c851d0%7C54acc61c-99a8-465c-a163-bdd93d7c41a8">Language Detection and Multi-lingual Text Mining in Spark NLP</a></li></ul><h3>More about NLU</h3><ul><li><a href="https://nlu.johnsnowlabs.com/">NLU website</a></li><li><a href="https://github.com/JohnSnowLabs/nlu">NLU Github</a></li><li><a href="https://nlu.johnsnowlabs.com/docs/en/examples">NLU Documentation</a></li><li><a href="https://join.slack.com/t/spark-nlp/shared_invite/zt-7rd4kw03-7F44zohcrUo0RULCd8rYrw">Having questions or wanna share an idea? Join us on Slack!</a></li><li><a href="https://nlu.johnsnowlabs.com/docs/en/notebooks">Overview of all NLU example notebooks</a></li><li><a href="https://colab.research.google.com/drive/1_sgbJV3dYPZ_Q7acCgKWgqZkWcKAfg79?usp=sharing">Named Entity Recognition (NER) 18 class notebook</a></li><li><a href="https://colab.research.google.com/drive/1tW833T3HS8F5Lvn6LgeDd5LW5226syKN?usp=sharing">Part of Speech (POS) notebook</a></li><li><a href="https://colab.research.google.com/drive/1Rg1vdSeq6sURc48RV8lpS47ja0bYwQmt?usp=sharing">BERT Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/18yd9pDoPkde79boTbAC8Xd03ROKisPsn?usp=sharing">ALBERT Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1TtNYB9z0yH8d1ZjfxkH0TVxQ2O_iOYVV?usp=sharing">ELMO Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1C9T29QA00yjLuJ1yEMTbjUQMpUv35pHb?usp=sharing">XLNET Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1bnRR8FygiiN3zJz3mRdbjPBUvFsx6IVB?usp=sharing">Spellchecking</a></li><li><a href="https://colab.research.google.com/drive/1KXUqcF8e-LU9cXnHE8ni8z758LuFPvY7?usp=sharing">Typed Dependency Parsing</a> notebook</li></ul><h3>Link to the Notebook</h3><ul><li><a href="https://colab.research.google.com/drive/18yd9pDoPkde79boTbAC8Xd03ROKisPsn?usp=sharing">ALBERT Word Embeddings and t-SNE plotting</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1691bc048ed1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spark-nlp/1-line-to-albert-word-embeddings-with-nlu-in-python-1691bc048ed1">1 line to ALBERT Word Embeddings with NLU in Python</a> was originally published in <a href="https://medium.com/spark-nlp">spark-nlp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[1 line to XLNET Word Embeddings with NLU in Python]]></title>
            <link>https://medium.com/spark-nlp/1-line-to-xlnet-word-embeddings-with-nlu-in-python-5efc57d7ac79?source=rss-9e09bb71b869------2</link>
            <guid isPermaLink="false">https://medium.com/p/5efc57d7ac79</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Christian Kasim Loan]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 18:35:04 GMT</pubDate>
            <atom:updated>2021-01-17T18:35:04.714Z</atom:updated>
            <content:encoded><![CDATA[<p>Including Part of Speech, Named Entity Recognition, Emotion Classification in the same line! With Bonus t-SNE plots!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKarcpXfh4Zye-sda8j_eg.jpeg" /></figure><h3>0. Introduction</h3><h3>0.1 What is NLU?</h3><p><a href="http://nlu.johnsnowlabs.com/">John Snow Labs NLU library</a> gives you 1000+ NLP models and 100+ Word Embeddings in 300+ languages and infinite possibilities to explore your data and gain insights.</p><p>In this tutorial, we will cover how to get the powerful <a href="https://arxiv.org/pdf/1909.11942.pdf">Xlnet</a> Embeddings with 1 line of NLU code and then how to visualize them with t-SNE. We will compare Comparing Sentiment with Sarcasm and Emotions!</p><h3>0.2 What is t-SNE?</h3><p>T-SNE is a tool to visualize high-dimensional data. It converts similarities between data points to joint probabilities and tries to minimize the Kullback-Leibler divergence between the joint probabilities of the low-dimensional embedding and the high-dimensional data. t-SNE has a cost function that is not convex, i.e. with different initializations we can get different results.</p><h3>0.3 What are XLNET embeddings?</h3><p>With the capability of modeling bidirectional contexts, denoising autoencoding-based pretraining like BERT achieves better performance than pretraining approaches based on autoregressive language modeling. However, relying on corrupting the input with masks, BERT neglects dependency between the masked positions and suffers from a pretrain-finetune discrepancy. In light of these pros and cons, XLNet was proposed, a generalized autoregressive pretraining method that (1) enables learning bidirectional contexts by maximizing the expected likelihood over all permutations of the factorization order and (2) overcomes the limitations of BERT thanks to its autoregressive formulation. Furthermore, XLNet integrates ideas from Transformer-XL, the state-of-the-art autoregressive model, into pretraining. Empirically, under comparable experiment settings, XLNet outperforms BERT on 20 tasks, often by a large margin, including question answering, natural language inference, sentiment analysis, and document ranking.</p><h3>1. Import NLU, load Xlnet, and embed a sample string in 1 line</h3><pre>nlu.load(&#39;xlnet&#39;).predict(&#39;He was suprised by the diversity of NLU&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tut5xxkMcdOiIZi2.png" /></figure><h3>2. Load a larger dataset</h3><p>The following snippet will download a Reddit sarcasm dataset and load it to a Pandas Dataframe</p><pre>import pandas as pd# Download the dataset! wget -N <a href="https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/sarcasm/train-balanced-sarcasm.csv">https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/resources/en/sarcasm/train-balanced-sarcasm.csv</a> -P /tmp# Load dataset to Pandasdf = pd.read_csv(&#39;/tmp/train-balanced-sarcasm.csv&#39;)df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gJMGok1CMJPr8Z2u.png" /></figure><h3>3. Predict on the dataset and also add Part of Speech, Emotion and Sentiment Classifiers</h3><p>Since adding additional classifiers and getting their predictions is so easy in NLU, we will extend our NLU pipeline with a POS, Emotion, and Sentiment classifier which all achieve results close to the state of the art.</p><p>Those extra predictions will also come in handy when plotting our results.<br>We are limiting ourselves to a subsection of the dataset because our RAM is sadly limited and we are not running on a cluster. With <a href="http://nlp.johnsnowlabs.com/">Spark NLP</a> you can take exactly the same models and run them in a scalable fashion inside of a Spark cluster</p><pre>pipe = nlu.load(&#39;pos sentiment emotion xlnet&#39;)df[&#39;text&#39;] = df[&#39;comment&#39;]# NLU to gives us one row per embedded word by specifying the output level<br>predictions = pipe.predict(df[[&#39;text&#39;,&#39;label&#39;]], output_level=&#39;token&#39;)predictions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eLfSDlHMfuyvUQKD.png" /></figure><h3>4. Emotion Plots</h3><p>We can quickly plot the distribution of predicted emotions using pandas functions on the data frame</p><pre># Some Tokens are None which we must drop firstpredictions.dropna(how=&#39;any&#39;, inplace=True)# Some sentiment are &#39;na&#39; which we must drop firstpredictions = predictions[predictions.emotion!= &#39;na&#39;]predictions.emotion.value_counts().plot.bar(title=&#39;Dataset emotion distribution&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fPKYHHs71WS35CYp.png" /></figure><h3>5. Prepare data for T-SNE</h3><p>We prepare the data for the T-SNE algorithm by collecting them in a matrix for TSNE</p><pre>import numpy as npmat = np.matrix([x for x in predictions.xlnet_embeddings])</pre><h3>6. Fit T-SNE</h3><p>Finally, we fit the T-SNE algorithm and get our 2-Dimensional representation of our Xlnet Word Embeddings</p><pre>from sklearn.manifold import TSNEmodel = TSNE(n_components=2)low_dim_data = model.fit_transform(mat)print(&#39;Lower dim data has shape&#39;,low_dim_data.shape)</pre><h3>7. Plot XLNET Word Embeddings, colored by Part of Speech Tag</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word in a sentence and the color represents the POS class that word belongs to.tsne_df = pd.DataFrame(low_dim_data, predictions.pos)ax = sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)ax.set_title(‘T-SNE XLNET Embeddings, colored by Part of Speech Tag’)</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.pos)ax = sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)ax.set_title(&#39;T-SNE XLNET Embeddings, colored by Part of Speech Tag&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2B_wnLXYRgeG21T6.png" /></figure><h3>8. Plot Plot Xlnet Word Embeddings, colored by Emotion</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified with a particular emotion, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.emotion)ax =  sns.scatterplot(data=tsne_df, x=0, y=1, hue=tsne_df.index)ax.set_title(&#39;T-SNE XLNET Embeddings, colored by Emotion&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6rdFIrW4TrKCgzg-.png" /></figure><h3>9. Plot Plot Xlnet Word Embeddings, colored by Sarcasm</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified as sarcastic or not, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.label.replace({1:&#39;sarcasm&#39;,0:&#39;normal&#39;}))<br>tsne_df.columns=[&#39;x&#39;,&#39;y&#39;]ax = sns.scatterplot(data=tsne_df, x=&#39;x&#39;, y=&#39;y&#39;, hue=tsne_df.index)ax.set_title(&#39;T-SNE XLNET Embeddings, colored by Sarcasm label&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PXx7bx-3W0S74lxW.png" /></figure><h3>9. Plot Plot Xlnet Word Embeddings, colored by Sentiment</h3><p>The following plots show scatter plots for the 2-D representation of the Word Embeddings. Each point represents a word from a sentence that was classified as sarcastic or not, which reflects in the colors</p><pre>tsne_df =  pd.DataFrame(low_dim_data, predictions.sentiment)tsne_df.columns = [&#39;x&#39;,&#39;y&#39;]ax = sns.scatterplot(data=tsne_df, x=&#39;x&#39;, y=&#39;y&#39;, hue=tsne_df.index)ax.set_title(&#39;T-SNE XLNET Embeddings, colored by Sentiment&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FpL_ucTvFKqyApyf.png" /></figure><h3>10. There are many many more word Embeddings!</h3><p>To view all word embeddings, type the following command</p><pre>nlu.print_all_model_kinds_for_action(&#39;embed&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*h5SnAJ_tHUoa9v4b.png" /></figure><h3>More NLU Medium articles</h3><ul><li><a href="https://medium.com/@christian.kasim.loan/1-line-of-code-350-nlp-models-with-john-snow-labs-nlu-in-python-2f1c55bba619?sk=1379426a00ca970a6e101a8f74f66bd2">Introduction to NLU</a></li><li><a href="https://medium.com/spark-nlp/1-line-of-code-for-bert-albert-elmo-electra-xlnet-glove-part-of-speech-with-nlu-and-t-sne-9ebcd5379cd">One line of Python code for 6 Embeddings, BERT, ALBERT, ELMO, ELECTRA, XLNET, GLOVE, Part of Speech with NLU and t-SNE</a></li><li><a href="https://medium.com/spark-nlp/1-line-to-bert-word-embeddings-with-nlu-f50d2b08cddc?source=collection_home---4------1-----------------------">One-Line Bert Embeddings and t-SNE plots with NLU</a></li><li><a href="https://medium.com/spark-nlp/easy-sentence-similarity-with-bert-sentence-embeddings-using-john-snow-labs-nlu-ea078deb6ebf">Easy sentence similarity with BERT Sentence Embeddings using John Snow Labs NLU</a></li></ul><h3>NLU Talks</h3><ul><li><a href="https://www.nlpsummit.org/john-snow-labs-nlu-the-simplicity-of-python-the-power-of-spark-nlp/">NLP Summit 2020: John Snow Labs NLU: The simplicity of Python, the power of Spark NLP</a></li><li><a href="https://events.johnsnowlabs.com/john-snow-labs-nlu-become-a-data-science-superhero-with-one-line-of-python-code?hsCtaTracking=c659363c-2188-4c86-945f-5cfb7b42fcfc%7C8b2b188b-92a3-48ba-ad7e-073b384425b0">John Snow Labs NLU: Become a Data Science Superhero with One Line of Python code</a></li><li><a href="https://events.johnsnowlabs.com/language-detection-and-multi-lingual-text-mining-in-spark-nlp?hsCtaTracking=a3ee2983-7573-4d1d-bdba-ab7e69c851d0%7C54acc61c-99a8-465c-a163-bdd93d7c41a8">Language Detection and Multi-lingual Text Mining in Spark NLP</a></li></ul><h3>More about NLU</h3><ul><li><a href="https://nlu.johnsnowlabs.com/">NLU website</a></li><li><a href="https://github.com/JohnSnowLabs/nlu">NLU Github</a></li><li><a href="https://nlu.johnsnowlabs.com/docs/en/examples">NLU Documentation</a></li><li><a href="https://join.slack.com/t/spark-nlp/shared_invite/zt-7rd4kw03-7F44zohcrUo0RULCd8rYrw">Having questions or wanna share an idea? Join us on Slack!</a></li><li><a href="https://nlu.johnsnowlabs.com/docs/en/notebooks">Overview of all NLU example notebooks</a></li><li><a href="https://colab.research.google.com/drive/1_sgbJV3dYPZ_Q7acCgKWgqZkWcKAfg79?usp=sharing">Named Entity Recognition (NER) 18 class notebook</a></li><li><a href="https://colab.research.google.com/drive/1tW833T3HS8F5Lvn6LgeDd5LW5226syKN?usp=sharing">Part of Speech (POS) notebook</a></li><li><a href="https://colab.research.google.com/drive/1Rg1vdSeq6sURc48RV8lpS47ja0bYwQmt?usp=sharing">BERT Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/18yd9pDoPkde79boTbAC8Xd03ROKisPsn?usp=sharing">ALBERT Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1TtNYB9z0yH8d1ZjfxkH0TVxQ2O_iOYVV?usp=sharing">ELMO Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1C9T29QA00yjLuJ1yEMTbjUQMpUv35pHb?usp=sharing">XLNET Word Embeddings and T-SNE plotting</a> notebook</li><li><a href="https://colab.research.google.com/drive/1bnRR8FygiiN3zJz3mRdbjPBUvFsx6IVB?usp=sharing">Spellchecking</a></li><li><a href="https://colab.research.google.com/drive/1KXUqcF8e-LU9cXnHE8ni8z758LuFPvY7?usp=sharing">Typed Dependency Parsing</a> notebook</li></ul><h3>Link to the Notebook</h3><ul><li><a href="https://colab.research.google.com/drive/1C9T29QA00yjLuJ1yEMTbjUQMpUv35pHb?usp=sharing">XLNET Word Embeddings and t-SNE plotting</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5efc57d7ac79" width="1" height="1" alt=""><hr><p><a href="https://medium.com/spark-nlp/1-line-to-xlnet-word-embeddings-with-nlu-in-python-5efc57d7ac79">1 line to XLNET Word Embeddings with NLU in Python</a> was originally published in <a href="https://medium.com/spark-nlp">spark-nlp</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>