PYTHON ヘルプ

fastText Python(仕組み:開発者ガイド)

公開済み 2025年3月5日
共有:

FastText入門

FastTextは、もともとFacebookのAIリサーチラボによって開発されたPythonライブラリです。(公正)効率的なテキスト分類とWordの表現学習を提供します。 それはWord表現への革新的なアプローチを提供し、Word2Vecのような以前のモデルのいくつかの制限を解決します。 単語ベクトルや要素を理解し、さまざまな言語的課題を処理する能力があるため、NLPツールキットにおいて強力なツールとなっています。 FastTextは、最新のmacOSおよびLinuxディストリビューション上で構築されています。 この記事では、FastText Pythonパッケージと多用途なPDF生成ライブラリについて学びます。IronPDFからIron Software.

機能

  1. 単語表現モデル:

    • Wordベクトルを計算する方法を学び、skip-gramまたはCBOWモデルを使用し、低メモリ使用量でfasttext.train_unsupervisedを使用します。
import fasttext
        model = fasttext.train_unsupervised('data.txt', model='skipgram')
        # data.txt is the training file
import fasttext
        model = fasttext.train_unsupervised('data.txt', model='skipgram')
        # data.txt is the training file
import fasttext model = fasttext.train_unsupervised( 'data.txt', model='skipgram')
		#data.txt is the training file
$vbLabelText   $csharpLabel
  • 単語ベクトルを取得する:
print(model.words)  # List of words in the dictionary
        print(model['king'])  # Vector for the word 'king'
print(model.words)  # List of words in the dictionary
        print(model['king'])  # Vector for the word 'king'
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'print(model.words) # List @of words in the dictionary print(model['king']) # Vector for the word 'king'
$vbLabelText   $csharpLabel
  • トレーニング済みモデルの保存と読み込み:
model.save_model("model_filename.bin")
        loaded_model = fasttext.load_model("model_filename.bin")
model.save_model("model_filename.bin")
        loaded_model = fasttext.load_model("model_filename.bin")
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'model.save_model("model_filename.bin") loaded_model = fasttext.load_model("model_filename.bin")
$vbLabelText   $csharpLabel
  1. テキスト分類モデル:

    • fasttext.train_supervisedを使用して、教師付きテキスト分類器を訓練するか、既に訓練されたモデルを使用してください。
model = fasttext.train_supervised('data.train.txt')
model = fasttext.train_supervised('data.train.txt')
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'model = fasttext.train_supervised('data.train.txt')
$vbLabelText   $csharpLabel
  • コンテキストウィンドウ内でモデルを評価する:
print(model.test('data.test.txt'))  # Precision and recall
print(model.test('data.test.txt'))  # Precision and recall
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'print(model.test('data.test.txt')) # Precision @and recall
$vbLabelText   $csharpLabel
  • 特定のテキストに対してラベルを予測する:
print(model.predict("Which baking dish is best for banana bread?"))
print(model.predict("Which baking dish is best for banana bread?"))
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'print(model.predict("Which baking dish is best for banana bread?"))
$vbLabelText   $csharpLabel

コード例

このコードは、FastTextを使用してテキスト分類モデルをトレーニングする方法を示しています。

import fasttext
# Training data file format: '__label__<label> <text>' with vocabulary words and out of vocabulary words
train_data = [
    "__label__positive I love this!",
    "__label__negative This movie is terrible.",
    "__label__positive Great job!",
    "__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
    for item in train_data:
        f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
    "I like it.",
    "Not good.",
    "Awesome!"
]
for text in texts:
    print(f"Input text: '{text}'")
    print("Predicted label:", model.predict(text))
    print()
import fasttext
# Training data file format: '__label__<label> <text>' with vocabulary words and out of vocabulary words
train_data = [
    "__label__positive I love this!",
    "__label__negative This movie is terrible.",
    "__label__positive Great job!",
    "__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
    for item in train_data:
        f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
    "I like it.",
    "Not good.",
    "Awesome!"
]
for text in texts:
    print(f"Input text: '{text}'")
    print("Predicted label:", model.predict(text))
    print()
#Training data file format: '__label__<label> <text>' with vocabulary words and out of vocabulary words
#Write the training data to a text file with enriching word vectors
#Train a supervised model with training sentence file input
#Testing the model
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import fasttext train_data = ["__label__positive I love this!", "__label__negative This movie is terrible.", "__label__positive Great job!", "__label__neutral The weather is okay."] @with TryCast(open('train.txt', "w"c, encoding='utf-8'), f): for item in train_data: f.write("%s" + vbLf % item) model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0) texts = ["I like it.", "Not good.", "Awesome!"] for text in texts: print(f"Input text: '{text}'") print("Predicted label:", model.predict(text)) print()
$vbLabelText   $csharpLabel

出力説明

  • トレーニング: この例は、小さなデータセットを使用してFastTextモデルを訓練します。(train_data). train_dataの各エントリーは、ラベルで始まり、その後にラベルが続きます。(肯定的、否定的、中立)および対応するテキスト。
  • 予測: トレーニング後、モデルはラベルを予測します(肯定的、否定的、中立)新しい入力テキスト用(テキスト). 各テキストは、学習済みモデルに基づいてラベルのいずれかに分類されます。

出力

fastText Python(動作の仕組み:開発者向けガイド):図1 - テキスト分類モデルの出力

IronPDFの紹介

fastText Python(使い方ガイド: 開発者向け): 図2 - IronPDF: Python PDFライブラリ

IronPDFは、HTML、CSS、画像、JavaScriptを使用してPDFドキュメントを作成、編集、電子署名するために作成された堅牢なPythonライブラリです。 最小限のメモリフットプリントを維持しながら、優れたパフォーマンスを発揮する。 主要な機能には次のものが含まれます:

  • HTMLからPDFへの変換: HTMLファイル、HTML文字列、URLをPDFドキュメントに変換し、Chrome PDFレンダラーを使用してウェブページをレンダリングする機能を備えています。
  • クロスプラットフォームサポート: Windows、Mac、Linux、および様々なクラウドプラットフォーム上でPython 3+に対応しています。 IronPDFは.NET、Java、Python、Node.js環境でもご利用いただけます。
  • 編集と署名: PDFプロパティをカスタマイズし、パスワードと権限でセキュリティを強化し、文書にデジタル署名を適用します。
  • ページテンプレートと設定: ヘッダー、フッター、ページ番号、調整可能なマージン、カスタム用紙サイズ、レスポンシブレイアウトでPDFをカスタマイズ。
  • 標準の準拠: PDF/AやPDF/UAなどのPDF標準に従うことを保証し、UTF-8文字エンコーディングをサポートし、画像、CSSスタイルシート、フォントなどのアセットをシームレスに管理します。

インストール

pip install fastText
pip install fastText
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'pip install fastText
$vbLabelText   $csharpLabel

IronPDFとFastTextを使用してPDFドキュメントを生成する

前提条件

  1. コードエディターとしてVisual Studio Codeがインストールされていることを確認してください

  2. Pythonバージョン3がインストールされている。

    まず始めに、スクリプトを追加するためのPythonファイルを作成しよう。

    Visual Studio Codeを開いて、ファイルfastTextDemo.pyを作成します。

    必要なライブラリをインストールする:

pip install fastText
pip install ironpdf
pip install fastText
pip install ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'pip install fastText pip install ironpdf
$vbLabelText   $csharpLabel

次に、IronPDFおよびFastText Pythonパッケージの使用法を示すために、以下のコードを追加します。

import fasttext
from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
# Create a PDF from a HTML string using Python
content = "<h1>Awesome Iron PDF with Fasttext</h1>"
# Training data file format to learn word vectors: '__label__<label> <text>' with vocabulary words,  rare words and out of vocabulary words
train_data = [
    "__label__positive I love this!",
    "__label__negative This movie is terrible.",
    "__label__positive Great job!",
    "__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
    for item in train_data:
        f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
    "I like it.",
    "Not good.",
    "Awesome!"
]
content += "<h2>Training data</h2>"
for data in train_data:
    print(data)
    content += f"<p>{data}</p>"
content += "<h2>Train a supervised model</h2>"
content += f"<p>model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)</p>"
content += "<h2>Testing the model</h2>"
for text in texts:
    print(f"Input text: '{text}'")
    print("Predicted label:", model.predict(text))
    print()
    content += f"<p>----------------------------------------------</p>"
    content += f"<p>Input text: '{text}</p>"
    content += f"<p>Predicted label:{model.predict(text)}</p>"
pdf = renderer.RenderHtmlAsPdf(content) 
    # Export to a file or Stream
pdf.SaveAs("DemoIronPDF-FastText.pdf")
import fasttext
from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
# Create a PDF from a HTML string using Python
content = "<h1>Awesome Iron PDF with Fasttext</h1>"
# Training data file format to learn word vectors: '__label__<label> <text>' with vocabulary words,  rare words and out of vocabulary words
train_data = [
    "__label__positive I love this!",
    "__label__negative This movie is terrible.",
    "__label__positive Great job!",
    "__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
    for item in train_data:
        f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
    "I like it.",
    "Not good.",
    "Awesome!"
]
content += "<h2>Training data</h2>"
for data in train_data:
    print(data)
    content += f"<p>{data}</p>"
content += "<h2>Train a supervised model</h2>"
content += f"<p>model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)</p>"
content += "<h2>Testing the model</h2>"
for text in texts:
    print(f"Input text: '{text}'")
    print("Predicted label:", model.predict(text))
    print()
    content += f"<p>----------------------------------------------</p>"
    content += f"<p>Input text: '{text}</p>"
    content += f"<p>Predicted label:{model.predict(text)}</p>"
pdf = renderer.RenderHtmlAsPdf(content) 
    # Export to a file or Stream
pdf.SaveAs("DemoIronPDF-FastText.pdf")
#Apply your license key
#Create a PDF from a HTML string using Python
#Training data file format to learn word vectors: '__label__<label> <text>' with vocabulary words, rare words and out of vocabulary words
#Write the training data to a text file with enriching word vectors
#Train a supervised model with training sentence file input
#Testing the model
	#Export to a file or Stream
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import fasttext from ironpdf import * License.LicenseKey = "key" content = "<h1>Awesome Iron PDF with Fasttext</h1>" train_data = ["__label__positive I love this!", "__label__negative This movie is terrible.", "__label__positive Great job!", "__label__neutral The weather is okay."] @with TryCast(open('train.txt', "w"c, encoding='utf-8'), f): for item in train_data: f.write("%s" + vbLf % item) model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0) texts = ["I like it.", "Not good.", "Awesome!"] content += "<h2>Training data</h2>" for data in train_data: print(data) content += f"<p>{data}</p>" content += "<h2>Train a supervised model</h2>" content += f"<p>model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)</p>" content += "<h2>Testing the model</h2>" for text in texts: print(f"Input text: '{text}'") print("Predicted label:", model.predict(text)) print() content += f"<p>----------------------------------------------</p>" content += f"<p>Input text: '{text}</p>" content += f"<p>Predicted label:{model.predict(text)}</p>" pdf = renderer.RenderHtmlAsPdf(content) pdf.SaveAs("DemoIronPDF-FastText.pdf")
$vbLabelText   $csharpLabel

出力

fastText Python(仕組み:開発者向けガイド):図3 - コンソール出力

PDF

fastText Python(開発者ガイド:動作の仕組み):図4 - PDF出力

IronPDFライセンス

IronPDFは、Python用のライセンスキーと連携しています。 IronPDF for Pythonは無料トライアルライセンスキーを使用して、ユーザーが無料で始められるようにします。

ライセンスキーをスクリプトの最初に配置してから使用してください。IronPDFパッケージ:

from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

結論

FastTextは、テキスト表現と分類のための軽量で効率的なライブラリです。 それは、サブワード情報を使用したWord埋め込みの学習に優れ、テキスト分類タスクを高速度かつスケーラブルにサポートし、複数の言語に対応した事前学習済みモデルを提供し、プロジェクトへの簡単な統合が可能なユーザーフレンドリーなPythonインターフェースを提供します。 IronPDFは、PDFドキュメントをプログラムで作成、編集、およびレンダリングするための包括的なPythonライブラリです。 これは、HTMLをPDFに変換したり、PDFにコンテンツや注釈を追加したり、ドキュメントのプロパティやセキュリティを管理したりするタスクを簡素化し、さまざまなオペレーティングシステムおよびプログラミング環境と互換性があります。 Pythonアプリケーション内でPDFを効率的に生成および操作するのに理想的です。

両方のライブラリを使用して、テキストモデルをトレーニングし、アーカイブ目的で出力結果をPDF形式で記録することができます。

Kannaopat Udonpant

カンナパット・ウドンパント

ソフトウェアエンジニア

 LinkedIn

ソフトウェアエンジニアになる前に、カンナパットは日本の北海道大学から環境資源学の博士号を取得しました。学位を取得する過程で、カンナパットはバイオプロダクション工学部に所属する車両ロボティクス研究所のメンバーにもなりました。2022年には、C#のスキルを活かしてIron Softwareのエンジニアリングチームに参加し、IronPDFに注力しています。カンナパットは、IronPDFで使用されているコードの大部分を作成した開発者から直接学べることに価値を見いだしています。同僚との学び合いに加えて、Iron Softwareで働くことの社会的側面も楽しんでいます。コードやドキュメントを書いていない時には、カンナパットは通常、PS5でゲームをしたり、『The Last of Us』を再視聴したりしています。
< 以前
Folium Python(動作のしくみ:開発者向けガイド)
次へ >
Bottle Python ((開発者向けガイド:動作の仕組み))