【Mistral Nemo】NVIDIAと共同開発LLM!Tekkenトークナイザーによる日本語力が強み!

Mistral-Nemo NVIDIA LLM Tekken トークナイザー 日本語力 強み!

WEELメディア事業部LLMライターのゆうやです。

Mistral Nemoは、フランスのMistral社が米Nvidia社と共同で開発した最新のオープンソースLLMです。

このモデルは、12Bのパラメータと128Kのコンテキストウィンドウを有しており、推論やコーディング能力などの点でGemma 2 9BやLlama 3 8Bを上回り、このクラスのモデルの中では最高の性能を持っています。

また、日本語を含む多言語対応や、様々なモデルで使用される標準アーキテクチャを採用しているので、幅広いタスクに利用できるほか、Mistral 7B等の前世代のモデルから簡単に交換できます。

今回は、Mistral Nemoの概要や使ってみた感想をお伝えします。

是非最後までご覧ください!

目次

Mistral Nemoの概要

Mistral社とNvidia社が共同で開発したMistral Nemoは、12Bのパラメータを持つ最新のオープンソースLLMで、128kのコンテキストウィンドを有しています。

このクラスのモデルとしては、最高クラスの性能を有しており、Gemma 2 9BやLlama 3 8Bなどの名だたるオープンソースモデルを上回ります。

以下の表は、Mistral NemoとGemma 2 9BおよびLlama 3 8Bのベースモデルのベンチマーク結果を比較した表です。

引用元:https://mistral.ai/news/mistral-nemo/

Mistral Nemoは、ほぼすべてのベンチマークで他の2つのモデルを上回る性能を示しています。

また、Instructモデルでのベンチマーク結果も公開されており、Mistral NemoのInstructモデルは、Mistral 7BおよびLlama 3 8BのInstructモデルよりはるかに優れた性能を有していることが分かります。

引用元:https://mistral.ai/news/mistral-nemo/

Mistral Nemoは、多言語アプリケーション向けに設計されており、日本語を含む多言語に対応しています。

対応する多くの言語で、Llama 3 8Bを上回る性能をベンチマークで示しており、その能力の高さが伺えます。

引用元:https://mistral.ai/news/mistral-nemo/

また、「Tekken」という従来のSentencePieceトークナイザーより効率的に自然言語テキストとソース コードを圧縮できるトークナイザーを採用しています。

これにより、従来のトークナイザーと比較して日本語で約1.56倍、マレーシア語ではなんと約3.90倍も効率的にトークン化を行うことができます。

引用元:https://mistral.ai/news/mistral-nemo/

ここからは、Mistral Nemoの使い方を解説します。

なお、Mistral AI発のコーディングAIについて詳しく知りたい方はこちらの記事をご覧ください。

Mistral Nemoのライセンス

Mistral Nemoは、Apache License 2.0のもとで提供されており、商用利用や配布等を行うことができます。

利用用途可否
商用利用⭕️
改変⭕️
配布⭕️
特許使用⭕️
私的使用⭕️
参考:https://huggingface.co/mistralai/Mistral-Nemo-Base-2407

Mistral Nemoの使い方

Mistral NemoをHugging Faceからダウンロードする場合は、まずモデルカードの先頭にある連絡先情報の共有に同意する必要があります。

Mistral Nemoの使用方法は、Mistral Inferenceを使う方法とtransformersを使う方法の2種類あり、それぞれ紹介します。

まずMistral Inferenceを使う方法ですが、以下のコマンドでMistral Inferenceをインストールします。

pip install mistral_inference

次に、以下のコマンドでモデルをダウンロードします。

from huggingface_hub import snapshot_download
from pathlib import Path

mistral_models_path = Path.home().joinpath('mistral_models', 'Nemo-Instruct')
mistral_models_path.mkdir(parents=True, exist_ok=True)

snapshot_download(repo_id="mistralai/Mistral-Nemo-Instruct-2407", allow_patterns=["params.json", "consolidated.safetensors", "tekken.json"], local_dir=mistral_models_path)

ここまで完了したら、以下のようにmistral-chat CLIコマンドが使えるようになるので、こちらを実行してチャットを開始します。

mistral-chat $HOME/mistral_models/Nemo-Instruct --instruct --max_tokens 256 --temperature 0.35

次に、transformersを使用する方法ですが、まずはソースからtransformersをインストールします。

pip install git+https://github.com/huggingface/transformers.git

次に、以下のコードを実行してモデルのダウンロードと推論を実行します。

from transformers import pipeline

messages = [
    {"role": "system", "content": "You are a pirate chatbot who always responds in pirate speak!"},
    {"role": "user", "content": "Who are you?"},
]
chatbot = pipeline("text-generation", model="mistralai/Mistral-Nemo-Instruct-2407")
chatbot(messages)

ローカルでMistral Nemoを実行する際の注意点ですが、temperatureを従来のモデルより低い0.3に設定することが推奨されているので、忘れずに設定してください。

また、ローカルで実装する以外にも、Hugging Face Spaceでオンラインデモが公開されているので、そちらで気軽に試すこともできます。

Mistral Nemoを実際に使ってみた

以下のプロンプトを入力します。

Please tell me about typical image generation AIs and their characteristics

代表的な画像生成AIとその特徴を教えて

結果はこのようになりました。

結果はこちら

Sure, I’d be happy to provide an overview of some typical image generation AIs and their key characteristics. These models primarily use deep learning techniques, particularly Convolutional Neural Networks (CNNs) and Generative Adversarial Networks (GANs), to create images.

  1. Generative Adversarial Networks (GANs):
  • Characteristics: GANs consist of two neural networks, a Generator and a Discriminator, that are trained simultaneously. The Generator learns to produce images, while the Discriminator learns to tell real images apart from fake ones. They compete with each other, driving the Generator to improve its output.
  • Examples:
    • DeepConvolutional GAN (DCGAN): This is a type of GAN that uses convolutional layers for both the Generator and Discriminator. It’s known for its ability to generate high-quality images.
    • StyleGAN: Developed by NVIDIA, StyleGAN introduces style-based generator architecture, allowing it to generate diverse and high-quality images. Its latest version, StyleGAN2, improves upon this further.
    • CycleGAN: This variant of GAN can learn to translate images from one domain to another, like turning a photograph into a painting.
  1. Variational Autoencoders (VAEs):
  • Characteristics: VAEs are autoencoders that learn a continuous latent space representation of the data. They consist of an Encoder (recognition model) and a Decoder (generative model). The Encoder maps input data to a probability distribution in the latent space, and the Decoder generates new data from samples in the latent space.
  • Examples:
    • Beta-VAE: This variant of VAE encourages disentangled representations in the latent space, leading to more interpretable and diverse generations.
    • NVAE (Deep Hierarchical VAE): This model uses a deep, hierarchical structure to capture complex, multi-scale dependencies in the data.
  1. Autoregressive Models:
  • Characteristics: Autoregressive models generate images pixel by pixel, conditioning each prediction on the previously generated pixels. They often use transformer architectures or 1D convolutions to process the sequential data.
  • Examples:
    • Pixel Recurrent Neural Networks (PixelRNN/PixelCNN): These models use recurrent neural networks or convolutional neural networks to generate images autoregressively.
    • DALL-E (Diffusion Model): Developed by OpenAI, DALL-E uses diffusion models to generate high-resolution images conditioned on textual descriptions.
  1. Transformers for Image Synthesis:
  • Characteristics: Transformers, originally designed for natural language processing tasks, have also shown promise in image synthesis. They can capture long-range dependencies between image regions.
  • Examples:
    • DETR (End-to-End Object Detection with Transformers): While primarily used for object detection, DETR’s transformer architecture can also be adapted for image synthesis tasks.
    • Imagen: Developed by Google Research, Imagen uses a transformer-based model to generate high-resolution images from textual descriptions.

Each of these models has its own strengths and weaknesses, and they are often chosen based on the specific task and dataset at hand.

もちろん、典型的な画像生成AIの概要と主な特徴についてご説明いたします。これらのモデルは主に、ディープラーニング技術、特に畳み込みニューラルネットワーク(CNN)と生成対立ネットワーク(GAN)を使用して画像を生成します。

  1. 生成対立ネットワーク(GAN)
  • 特徴:GANは、生成器と識別器の2つのニューラルネットワークで構成されており、同時にトレーニングされます。ジェネレーターは画像の生成を学習し、識別器は本物と偽物の画像を区別することを学習します。 両者は互いに競い合い、ジェネレーターは出力を改善するようになります。
  • :
    • DeepConvolutional GAN (DCGAN): これはジェネレーターと識別器の双方に畳み込み層を使用するGANの一種です。 高品質な画像を生成できることで知られています。
    • StyleGAN: NVIDIAが開発したStyleGANは、スタイルベースのジェネレーターアーキテクチャを導入し、多様で高品質な画像の生成を可能にします。その最新バージョンであるStyleGAN2は、これをさらに改善しています。
    • CycleGAN:このGANのバリエーションは、写真を絵画に変換するなど、あるドメインの画像を別のドメインの画像に変換することを学習することができます。
  1. Variational Autoencoders (VAEs)
  • 特徴: VAEは、データの連続的な潜在空間表現を学習するオートエンコーダーです。エンコーダー(認識モデル)とデコーダー(生成モデル)で構成されています。エンコーダーは入力データを潜在空間の確率分布にマッピングし、デコーダーは潜在空間のサンプルから新しいデータを生成します。
  • :
    • Beta-VAE: この VAE のバリエーションは、潜在空間における分離された表現を推奨し、より解釈しやすく多様な生成につながります。
    • NVAE (Deep Hierarchical VAE): このモデルは、データ内の複雑でマルチスケールの依存関係を捉えるために、深層かつ階層的な構造を使用しています。
  1. 自己回帰モデル:
  • 特徴: 自己回帰モデルは、ピクセルごとに画像を生成し、各予測を以前に生成されたピクセルに条件付けます。これらのモデルでは、トランスフォーマーアーキテクチャや1D畳み込みニューラルネットワークが、時系列データの処理にしばしば使用されます。
  • :
  • Pixel Recurrent Neural Networks (PixelRNN/PixelCNN): これらのモデルは、再帰ニューラルネットワークまたは畳み込みニューラルネットワークを使用して、画像を自己回帰的に生成します。
  • DALL-E (Diffusion Model): OpenAIが開発したDALL-Eは、拡散モデルを使用して、テキスト記述を条件として高解像度の画像を生成します。
  1. 画像合成用トランスフォーマー
  • 特徴:もともと自然言語処理タスク用に設計されたトランスフォーマーは、画像合成でも有望な結果を見せています。画像領域間の長距離依存性を捉えることができます。
    • DETR (End-to-End Object Detection with Transformers):主に物体検出に使用されていますが、DETRのトランスフォーマーアーキテクチャは画像合成タスクにも適応できます。
    • Imagen: Google Researchが開発したImagenは、テキスト記述から高解像度の画像を生成するために、トランスフォーマーベースのモデルを使用しています。

これらのモデルにはそれぞれ長所と短所があり、多くの場合、特定のタスクやデータセットに基づいて選択されます。

様々な種類の画像生成AIについて、その技術の特徴と実例を分かりやすくまとめてくれています。

十分すぎる情報量ですね。

Mistral Nemoを実行するのに必要なスペック

公式から必要スペックに関する情報は公開されていませんが、一般的に12Bクラスのモデルを動かす場合はこのようなスペックが必要になります。

  • GPU
    • メモリ容量: 最低でも24GBのGPUメモリが必要。
    • 推奨GPU: NVIDIA RTX 3090(24GB)やRTX 4090(24GB)。NVIDIA A100 (40GB/80GB)やそれ以上の性能のGPUなら尚可
  • CPU:8コア以上でクロック速度3.0 GHz以上
  • RAM: 最低でも32GB
  • ストレージ: 1TB以上のNVMe SSD推奨

Mistral NemoをLlama 3 8BとGPT-4oと比較してみた

ここからは、Mistral NemoをLlama 3 8BとGPT-4oと以下の項目で比較していきます。

  • ビジネスメールの作成(日本語)
  • コーディング(形態素解析)

早速検証をしていきましょう!

ビジネスメールの作成(日本語)

まずは、日本語能力を比較検証するために、日本語でのビジネスメールの作成を行います。

以下のプロンプトを入力します。

日本語でクライアントに送信する丁寧語・謙譲語を正しく使用したビジネスメールを作成してください。

結果はこのようになりました。

Mistral Nemoの結果はこちら

以下は、クライアントに送信するビジネスメールの例です。丁寧語・謙譲語を適切に使用しています。

件名: ご注文の確認の件

Dear [クライアントの名前],

この度は、当社の製品・サービスについてお問い合わせいただき、誠にありがとうございます。
以下のご注文を受け付けましたので、ご確認いただけますでしょうか。

【ご注文内容】
- 製品名:[製品名]
- 数量:[数量]
- ご請求先:[請求先の住所]

当社では、上記の製品を早速ご用意させていただき、来週中に発送いたします。万一、ご注文内容に異なる箇所がございましたら、至急ご連絡ください。

また、本メールは送信者アドレスから直接返信いただくことができます。何かご質問やご不明な点がございましたら、お気軽にお尋ねください。

今後とも、当社の製品・サービスを宜しくお使いいただき、ありがとうございます。

Best regards,

[自分の名前]
[自分の役職]
[会社名]

このメールでは、丁寧語として「誠にありがとうございます」、「ご確認いただけますでしょうか」、「早速」、「万一」、「至急」などを使用しています。また、謙譲語として「宜しくお使いいただき」を使用しています。

Llama 3 8Bの結果はこちら

I’d be happy to help you create a polite and humble business email in Japanese for your client. Here’s a sample email:


件名:[Subject] regard to our previous discussion
本文:
尊敬した[Client’s Name]様
お客様との前回の話合いにおいて、[Topic]についての件に取り組むことをお約束したところ、以下のような進捗状況になりました。
[Progress report]
一方、現時点では、以下のような課題や要望がありました。
[Challenges or requests]
これらの点を踏まえ、我々は以下のような提案を行うことを検討しています。
[Proposal]
お客様のご意見やご指摘をいただき、更に改善することを目指しています。期限は[Deadline]までにお願いします。
以上の内容で、我々の進捗状況を報告したいと思います。何かお問い合わせやご意見がありましたら、必ずお知らせください。
よろしくお願いします。


Sincerely,
[Your Name]
Translation:
Subject: [Subject] regarding our previous discussion
Text:
Dear [Client’s Name],
As we had discussed previously regarding [Topic], we would like to report on the progress we have made so far.
[Progress report]
However, we have encountered the following challenges and requests:
[Challenges or requests]
Taking these points into consideration, we are considering the following proposal:
[Proposal]
We would like to hear your thoughts and opinions and make further improvements. The deadline is [Deadline]. We would appreciate it if you could let us know if you have any questions or comments.
We would like to report on our progress to you. If you have any questions or comments, please do not hesitate to let us know.
Thank you for your understanding.
Sincerely,
[Your Name]
Note:

  • 丁寧語 (teineigo) is used throughout the email to show respect and politeness.
  • 謙譲語 (kenjōgo) is used to express humility and modesty, such as using the phrase “” (yoroshiku onegaishimasu) to express gratitude and politeness.
  • The tone is formal and professional, suitable for a business email.
  • The email includes a clear and concise summary of the progress, challenges, and proposal, and shows a willingness to listen to the client’s feedback and opinions.
GPT-4oの結果はこちら

もちろんです。以下に、クライアントに送信するビジネスメールの例を作成しました。


件名:新製品のご提案について

株式会社〇〇〇〇
〇〇部 〇〇 様

平素より大変お世話になっております。株式会社〇〇の△△と申します。

さて、この度は弊社の新製品「〇〇〇〇」につきまして、ご提案をさせていただきたく、ご連絡を差し上げました。本製品は、従来品に比べ、性能面及びコストパフォーマンスにおいて大幅な改善を実現しており、貴社のニーズにお応えできるものと確信しております。

つきましては、ぜひ一度直接お会いして詳しくご説明させていただきたく存じます。ご都合のよろしい日時をお知らせいただけますと幸いです。なお、弊社オフィスにお越しいただくことも可能でございますし、オンラインミーティングの設定も承っております。

ご多忙のところ恐れ入りますが、何卒ご検討のほどよろしくお願い申し上げます。

敬具


株式会社〇〇
△△(名前)
メール:example@example.com
電話番号:123-456-7890


ご質問や追加のご要望がございましたら、お気軽にお知らせください。

Mistral NemoとLlama 3 8Bを比較すると、Mistral Nemoのほうがかなり自然な日本語になっており、高い日本語能力をもつことが分かります。

ただ、「今後とも、当社の製品・サービスを宜しくお使いいただき、ありがとうございます。 」など、不自然な部分があるので、完璧とは言えません。

GPT-4oと比較しても、その差は明確ですが、12Bクラスの海外製モデルと考えればとても良い結果だと思います。

コーディング(形態素解析)

続いて、以下のプロンプトを入力して英語のテキストを日本語に翻訳して形態素解析するコードを生成してもらいます。

Generate a program that translates English text into Japanese and performs morphological analysis.

英語のテキストを日本語に翻訳して形態素解析まで行うプログラムを生成して

結果はこのようになりました。

Mistral Nemoの結果はこちら

Here’s a Python program using the googletrans library for translation and japanese-morphy for morphological analysis. Make sure to install the required libraries using pip install googletrans japanese-morphy.

from googletrans import Translator
import japanese_morphy

def translate_and_analyze(text):
    # Translate text to Japanese
    translator = Translator()
    translation = translator.translate(text, dest='ja')
    japanese_text = translation.text

    # Perform morphological analysis
    morph_analyzer = japanese_morphy.MorphAnalyzer()
    analyzed_text = morph_analyzer.analyze(japanese_text)

    return japanese_text, analyzed_text

# Example usage:
english_text = "Hello, how are you?"
japanese_text, analyzed_text = translate_and_analyze(english_text)

print(f"Translated Text: {japanese_text}")
print("\nMorphological Analysis:")
for word, morphs in analyzed_text.items():
    print(f"{word}:")
    for morph in morphs:
        print(f"- {morph.surface} ({morph.reading}, {morph.part_of_speech})")

When you run this script with the example usage, it will output:

Translated Text: はじめまして、おげんきですか?

Morphological Analysis:
はじめまして:
- はじめまして (はじめまして, 固有名詞)
おげんきですか:
- お (お, 助詞)
- gegnki (げんき, 名詞)
- desu ka (ですか, 助動詞)

This shows the translated Japanese text and the morphological analysis of each word, including its surface form, reading, and part of speech.

以下は、英語テキストを日本語に翻訳し、形態素解析を行うPythonプログラムです。必要なライブラリをpip install googletrans japanese-morphyを使用してインストールしてください。

from googletrans import Translator
import japanese_morphy

def translate_and_analyze(text):
    # テキストを日本語に翻訳
    translator = Translator()
    translation = translator.translate(text, dest='ja')
    japanese_text = translation.text

    # 形態素解析を行う
    morph_analyzer = japanese_morphy.MorphAnalyzer()
    analyzed_text = morph_analyzer.analyze(japanese_text)

    return japanese_text, analyzed_text

# 例として使用する英語テキスト
english_text = "Hello, how are you?"
japanese_text, analyzed_text = translate_and_analyze(english_text)

print(f"翻訳テキスト: {japanese_text}")
print("\n形態素解析:")
for word, morphs in analyzed_text.items():
    print(f"{word}:")
    for morph in morphs:
        print(f"- {morph.surface} ({morph.reading}, {morph.part_of_speech})")

このスクリプトを実行すると、以下のような出力が得られます。

翻訳テキスト: はじめまして、おげんきですか?

形態素解析:
はじめまして:
- はじめまして (はじめまして,固有名詞)
おげんきですか:
- お (お,助詞)
- gegnki (げんき,名詞)
- desu ka (ですか,助動詞)

これは、翻訳された日本語テキストと各単語の形態素解析結果(表層形、読み方、品詞)を示しています。

Llama 3 8Bの結果はこちら

Here is a Python program that uses the MeCab library to perform morphological analysis on English text and translate it into Japanese using the Googletrans library:

import MeCab
from googletrans import Translator
def translate_and_analyze(text):
# Initialize MeCab
mecab = MeCab.Tagger('-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd')
mecab.parse('') # Initialize the tagger
# Initialize Googletrans
translator = Translator()
# Translate the text
japanese_text = translator.translate(text, dest='ja').text
# Perform morphological analysis
nodes = mecab.parse(japanese_text)
# Print the morphological analysis
for node in nodes:
features = node.split('\t')
if len(features) > 1:
print(features[0], features[1])
return japanese_text
# Test the function
text = "Hello, world!"
japanese_text = translate_and_analyze(text)
print(japanese_text)

This program translates the input text into Japanese and then performs morphological analysis on the Japanese text using MeCab. The morphological analysis is then printed to the console.
Note that you need to install the MeCab and Googletrans libraries to run this program. You can install them using pip:

pip install mecab-python mecab-ipadic-neologd googletrans

Also, make sure to replace the path /usr/local/lib/mecab/dic/mecab-ipadic-neologd with the actual path to the MeCab dictionary on your system.
Please note that the translation and morphological analysis may not be perfect, as these are complex tasks that require sophisticated natural language processing techniques.

MeCabライブラリを使用して英語のテキストを形態素解析し、Googletransライブラリを使用して日本語に翻訳するPythonプログラムです:

import MeCab
from googletrans import Translator
def translate_and_analyze(text):
# Initialize MeCab
mecab = MeCab.Tagger('-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd')
mecab.parse('') # Initialize the tagger
# Initialize Googletrans
translator = Translator()
# Translate the text
japanese_text = translator.translate(text, dest='ja').text
# Perform morphological analysis
nodes = mecab.parse(japanese_text)
# Print the morphological analysis
for node in nodes:
features = node.split('\t')
if len(features) > 1:
print(features[0], features[1])
return japanese_text
# Test the function
text = "Hello, world!"
japanese_text = translate_and_analyze(text)
print(japanese_text)

このプログラムは、入力テキストを日本語に翻訳し、MeCab を使用して日本語テキストの形態素解析を行います。形態素解析結果はコンソールに出力されます。
このプログラムを実行するには、MeCab および Googletrans ライブラリをインストールする必要があります。pip を使用してインストールできます:

pip install mecab-python mecab-ipadic-neologd googletrans

また、/usr/local/lib/mecab/dic/mecab-ipadic-neologd というパスを、お使いのシステム上の MeCab 辞書への実際のパスに置き換えてください。
翻訳と形態素解析は、高度な自然言語処理技術が必要な複雑な作業であるため、完璧ではない可能性があることにご注意ください。

GPT-4oの結果はこちら

To create a program that translates English text into Japanese and performs morphological analysis, we can use a combination of Google Translate API for translation and MeCab (a morphological analyzer for Japanese) for the analysis. Below is an example program using Python to achieve this:

  1. Install Required Libraries:
  • googletrans for translation.
  • mecab-python3 for morphological analysis.

You can install these libraries using pip:

pip install googletrans==4.0.0-rc1 mecab-python3
  1. Program Implementation:
import sys
from googletrans import Translator
import MeCab

def translate_text(text, src_lang='en', dest_lang='ja'):
    translator = Translator()
    translated = translator.translate(text, src=src_lang, dest=dest_lang)
    return translated.text

def perform_morphological_analysis(text):
    tagger = MeCab.Tagger()
    parsed_text = tagger.parse(text)
    return parsed_text

def main():
    # Example English text
    english_text = "This is a sample text to be translated into Japanese and analyzed morphologically."

    # Step 1: Translate English text to Japanese
    japanese_text = translate_text(english_text)
    print("Translated Text: ", japanese_text)

    # Step 2: Perform morphological analysis on the translated Japanese text
    analyzed_text = perform_morphological_analysis(japanese_text)
    print("Morphological Analysis: \n", analyzed_text)

if __name__ == "__main__":
    main()
  1. Explanation:
  • translate_text(text, src_lang, dest_lang): This function uses the googletrans library to translate the input text from the source language (src_lang, default is ‘en’ for English) to the destination language (dest_lang, default is ‘ja’ for Japanese).
  • perform_morphological_analysis(text): This function uses the MeCab library to perform morphological analysis on the input Japanese text and returns the parsed text.
  • main(): The main function where an example English text is translated into Japanese and then analyzed morphologically.
  1. Running the Program:
  • Save the program as translate_and_analyze.py.
  • Run the program using Python:
python translate_and_analyze.py

This program will output the translated Japanese text and its morphological analysis. The morphological analysis will include information about each word, such as its base form, reading, and part of speech.

Make sure you have MeCab installed on your system, and the necessary dictionaries (like ipadic) are configured correctly for mecab-python3 to work. You can usually install MeCab and the dictionaries using your system’s package manager. For example, on Ubuntu, you can use:

sudo apt install mecab libmecab-dev mecab-ipadic-utf8

英語テキストを日本語に翻訳し、形態素解析を行うプログラムを作成するには、Google翻訳API(翻訳)とMeCab(日本語形態素解析)を組み合わせることができます。Pythonを使用した例を以下に示します

  1. 必要なライブラリのインストール:
  • 翻訳には googletrans を使用します。
  • 形態素解析には mecab-python3 を使用します。

これらのライブラリを pip でインストールします:

pip install googletrans==4.0.0-rc1 mecab-python3
  1. プログラムの実装:
import sys
from googletrans import Translator
import MeCab

def translate_text(text, src_lang='en', dest_lang='ja'):
    translator = Translator()
    translated = translator.translate(text, src=src_lang, dest=dest_lang)
    return translated.text

def perform_morphological_analysis(text):
    tagger = MeCab.Tagger()
    parsed_text = tagger.parse(text)
    return parsed_text

def main():
    # 例の英語テキスト
    english_text = "This is a sample text to be translated into Japanese and analyzed morphologically."

    # ステップ1: 英語テキストを日本語に翻訳
    japanese_text = translate_text(english_text)
    print("Translated Text: ", japanese_text)

    # ステップ2: 翻訳された日本語テキストを形態素解析
    analyzed_text = perform_morphological_analysis(japanese_text)
    print("Morphological Analysis: \n", analyzed_text)

if __name__ == "__main__":
    main()
  1. 説明:
  • translate_text(text, src_lang, dest_lang): この関数は googletrans ライブラリを使用して、入力テキストをソース言語(デフォルトは英語 ‘en’)から目的言語(デフォルトは日本語 ‘ja’)に翻訳します。
  • perform_morphological_analysis(text): この関数は MeCab ライブラリを使用して、入力された日本語テキストの形態素解析を行い、解析されたテキストを返します。
  • main(): 主要な関数で、例の英語テキストを日本語に翻訳し、その後形態素解析を行います。
  1. プログラムの実行:
  • プログラムを translate_and_analyze.py として保存します。
  • Python を使用してプログラムを実行します:
python translate_and_analyze.py

このプログラムは、翻訳された日本語テキストとその形態素解析を出力します。形態素解析には、各単語の基本形、読み、および品詞などの情報が含まれます。

mecab-python3 を使用するために、システムに MeCab がインストールされていることと、必要な辞書(例えば ipadic)が正しく設定されていることを確認してください。システムのパッケージマネージャを使用して MeCab と辞書をインストールできます。例えば、Ubuntu では次のコマンドを使用します:

sudo apt install mecab libmecab-dev mecab-ipadic-utf8

Mistral Nemoの生成したコードは、japanese-morphyという存在しないライブラリを用いており、そのままでは全く動作しません。

Llama 3 8Bも、そのままでは動作せず、Mecabのインストール方法も誤りです。

唯一正しく動作する回答をしたのがGPT-4oで、やはり当然ではありますが明確に差が表れています。

存在しない架空のライブラリを使ったコードを生成するのは、想定外であり、Llama 3 8Bよりも悪い結果だと感じます。

今回の検証の結果、Mistral Nemoは豊富な知識と高い日本語能力を持っていますが、コーディング能力はLlama 3 8Bと同等かそれ以下の性能で、完全に誤った回答をする場合があることが分かりました。

なお、Llama 3について詳しく知りたい方はこちらの記事をご覧ください。

Mistral NemoはMistral 7Bを代替する高性能モデル

Mistral Nemoは、Mistral社とNvidia社が協力して開発した最新の12Bモデルであり、同程度の規模を持つGemma 2 9BやLlama 3 8Bを上回る性能を有しています。

このモデルは多言語アプリケーション向けに設計されており、日本語を含む多言語に対応しています。

また、Tekkenという新しいトークナイザーを採用することで、従来より1.5~3倍ほど効率的にトークン化が行えるのも特徴です。

実際に使ってみたところ、豊富な知識と高い日本語能力を持つことは確認できましたが、コーディング能力に関しては同規模のLlama 3 8Bと同等かそれ以下の性能で、完全に誤った回答をする場合があることが分かりました。

Mistral Nemoは、Mistral 7Bを代替する目的で開発され、簡単に代替できるように共通のアーキテクチャを採用しているので、もし今Mistral 7Bを使用されている方はMistral Nemoに代替することを強くお勧めします。

サービス紹介資料

生成系AIの業務活用なら!

・生成系AIを活用したPoC開発

・生成系AIのコンサルティング

・システム間API連携

最後に

いかがだったでしょうか?

弊社では

・マーケティングやエンジニアリングなどの専門知識を学習させたAI社員の開発
・要件定義・業務フロー作成を80%自動化できる自律型AIエージェントの開発
・生成AIとRPAを組み合わせた業務自動化ツールの開発
・社内人事業務を99%自動化できるAIツールの開発
ハルシネーション対策AIツールの開発
自社専用のAIチャットボットの開発

などの開発実績がございます。

まずは、「無料相談」にてご相談を承っておりますので、ご興味がある方はぜひご連絡ください。

➡︎生成AIを使った業務効率化、生成AIツールの開発について相談をしてみる。

生成AIを社内で活用していきたい方へ
無料相談

「生成AIを社内で活用したい」「生成AIの事業をやっていきたい」という方に向けて、生成AI社内セミナー・勉強会をさせていただいております。

セミナー内容や料金については、ご相談ください。

また、サービス紹介資料もご用意しておりますので、併せてご確認ください。

投稿者

  • ゆうや

    ロボット工学専攻。 大学時代は、対話ロボットのための画像キャプションの自動生成について研究。 趣味は、サウナとドライブ。

  • URLをコピーしました!
  • URLをコピーしました!
目次