from collections import Counter
from typing import List
# n-gramを生成する関数
def generate_n_grams(text: str, n: int) -> List[str]:
# テキストを単語(トークン)に分割
words = text.split()
# n-gramを生成
n_grams = [' '.join(words[i:i+n]) for i in range(len(words)-n+1)]
return n_grams
# テキストを入力
text = "This is an example of n-gram based text processing using Python code. This example demonstrates bigram and trigram extraction."
# バイグラムを生成
bigrams = generate_n_grams(text, 2)
print("Bigrams:", bigrams)
# トライグラムを生成
trigrams = generate_n_grams(text, 3)
print("Trigrams:", trigrams)
# n-gramの出現頻度を計算
bigram_counts = Counter(bigrams)
trigram_counts = Counter(trigrams)
print("\nBigram Frequency:", bigram_counts)
print("Trigram Frequency:", trigram_counts)
import random
from collections import defaultdict
# マルコフ連鎖クラス
class MarkovChain:
def __init__(self):
self.chain = defaultdict(list)
def train(self, text: str, n: int = 2):
"""
入力テキストからn-gramを生成し、マルコフ連鎖の状態遷移を学習します。
:param text: 入力テキスト
:param n: n-gramのサイズ(デフォルトはバイグラム)
"""
# テキストをトークンに分割
words = text.split()
# n-gramを使用してチェーンを生成
for i in range(len(words) - n):
# n-gramの先行部分をキー、次の単語を値として登録
key = tuple(words[i:i + n]) # 例: ('This', 'is')
next_word = words[i + n] # 例: 'an'
self.chain[key].append(next_word)
def generate_text(self, seed: str, length: int = 50) -> str:
"""
学習済みのマルコフ連鎖を用いて、指定した長さのテキストを生成します。
:param seed: 生成開始時のシード(最初のn-gram)
:param length: 生成するテキストの単語数(デフォルトは50)
:return: 生成されたテキスト
"""
# シードをトークンに分割
seed_words = seed.split()
n = len(seed_words)
# シードがチェーン内に存在するか確認
if tuple(seed_words) not in self.chain:
raise ValueError("Seed is not in the trained Markov Chain. Try another seed or re-train the model.")
# 生成されたテキストの初期化
generated_words = list(seed_words)
# 指定された長さになるまでテキストを生成
for _ in range(length):
current_state = tuple(generated_words[-n:]) # 現在の状態(n-gram)
# 現在の状態に対応する次の単語候補が存在するか確認
if current_state in self.chain:
next_word = random.choice(self.chain[current_state])
generated_words.append(next_word)
else:
break # 遷移先がない場合は終了
return ' '.join(generated_words)
# 入力テキストを設定
input_text = """
Markov chains are mathematical systems that undergo transitions from one state to another according to certain probabilistic rules.
They are named after the Russian mathematician Andrey Markov and have applications in various fields, including linguistics, genetics, and computer science.
A Markov chain is characterized by its state space, transition matrix, and initial state distribution.
In text generation, Markov chains can be used to generate sequences of words by treating each word or group of words as states and learning the probability of transitioning between these states from a given corpus.
"""
# マルコフ連鎖モデルのインスタンスを作成
markov_chain = MarkovChain()
# モデルを学習(バイグラム)
markov_chain.train(input_text, n=2)
# シード(テキスト生成の開始点)を指定してテキストを生成
seed = "Markov chains"
generated_text = markov_chain.generate_text(seed, length=50)
# 結果を表示
print("Generated Text:")
print(generated_text)
import random
from collections import defaultdict
# マルコフ連鎖を用いた人工無脳クラス
class MarkovChatbot:
def __init__(self):
# マルコフ連鎖の辞書(状態遷移を格納)
self.chain = defaultdict(list)
def train(self, text: str, n: int = 2):
"""
入力テキストからn-gramを生成し、マルコフ連鎖の状態遷移を学習します。
:param text: 学習用の入力テキスト
:param n: n-gramのサイズ(デフォルトはバイグラム)
"""
# 文字単位でn-gramを生成
for i in range(len(text) - n):
key = text[i:i + n] # 現在のn文字
next_char = text[i + n] # 次の1文字
self.chain[key].append(next_char) # 遷移先として登録
def generate_response(self, seed: str, length: int = 100) -> str:
"""
学習済みのマルコフ連鎖を用いて、指定された長さの文字列を生成します。
:param seed: 生成開始時のシード(最初のn文字)
:param length: 生成する文字列の長さ(デフォルトは100)
:return: 生成されたテキスト(応答)
"""
# シードがチェーンに含まれていない場合は、ランダムに開始
if seed not in self.chain:
seed = random.choice(list(self.chain.keys()))
# 生成されたテキストの初期化
response = list(seed)
# 指定された長さになるまで文字を生成
for _ in range(length - len(seed)):
current_state = ''.join(response[-len(seed):]) # 現在の状態(直近のn文字)
next_chars = self.chain.get(current_state)
# 現在の状態に対応する遷移先がない場合は終了
if not next_chars:
break
# 次の文字をランダムに選択
next_char = random.choice(next_chars)
response.append(next_char)
return ''.join(response)
def get_response(self, input_text: str) -> str:
"""
ユーザー入力に対してランダムな応答を生成します。
:param input_text: ユーザーの入力文字列
:return: ランダムに生成された応答文字列
"""
seed = input_text[:min(3, len(input_text))] # 入力の最初のn文字をシードとする
return self.generate_response(seed, length=50)
# 学習用テキスト(コーパス)
corpus = """
こんにちは!私は人工無脳です。何かお話ししませんか?
最近の天気はどうですか?晴れの日が多いですね。
私はテキストに基づいたランダムな応答を返すことができます。
何か質問があれば、気軽に聞いてくださいね!
"""
# チャットボットのインスタンスを作成
chatbot = MarkovChatbot()
# モデルを学習(バイグラムで学習)
chatbot.train(corpus, n=3) # 3-gram(トライグラム)
# ユーザーの入力に対してランダム応答を生成する
while True:
user_input = input("ユーザー: ")
if user_input.lower() in ["exit", "quit", "bye"]:
print("チャットボット: さようなら!またお話ししましょう!")
break
# ユーザーの入力に基づく応答を生成
response = chatbot.get_response(user_input)
print(f"チャットボット: {response}")
import MeCab
import spacy
import nltk
from nltk import CFG
# 形態素解析(MeCabを使用)
def morphological_analysis(text: str):
"""
日本語テキストの形態素解析を行います。
:param text: 入力テキスト
:return: 解析結果のリスト(形態素ごとの情報)
"""
mecab = MeCab.Tagger("-Ochasen")
parsed = mecab.parse(text).strip().split("\n")
results = []
for line in parsed:
if line == "EOS" or line == "":
continue
parts = line.split("\t")
surface, feature = parts[0], parts[1:]
results.append({"surface": surface, "features": feature})
return results
# 構文解析と文生成(spaCyを使用)
def syntactic_parsing_and_sentence_generation(text: str):
"""
英語テキストの構文解析を行い、文生成を行います。
:param text: 入力テキスト
:return: 依存関係ツリーの可視化と文生成
"""
nlp = spacy.load("en_core_web_sm")
doc = nlp(text)
# 構文解析結果の表示
print("Syntactic Parsing Results:")
for token in doc:
print(f"{token.text} ({token.dep_}) <-- {token.head.text} ({token.head.dep_})")
# 文の生成(解析結果から新しい文を生成)
new_sentence = " ".join([token.text for token in doc])
return new_sentence
# 意味解析(NLTKを使用して簡単な意味解析を行う)
def semantic_analysis(text: str):
"""
与えられた文に対して意味解析を行います(構文規則と意味の対応を用いた例)。
:param text: 入力テキスト
:return: 意味解析結果の表示
"""
# 単純な構文規則を定義
grammar = CFG.fromstring("""
S -> NP VP
NP -> Det N
VP -> V NP
Det -> 'the' | 'a'
N -> 'cat' | 'dog' | 'fish'
V -> 'chased' | 'caught'
""")
# パーサーの作成
parser = nltk.ChartParser(grammar)
# 入力文をトークン化
words = text.split()
# 意味解析(文の構文木を生成)
trees = list(parser.parse(words))
if trees:
print("Semantic Parsing Results:")
for tree in trees:
tree.pretty_print()
tree.draw()
else:
print("No valid parse tree found for the given sentence.")
# 例文(日本語と英語の両方)
japanese_text = "今日は良い天気ですね。散歩に行きましょうか。"
english_text = "The cat chased the dog."
# 3.1 自然言語処理の方法: 形態素解析
print("\n=== 形態素解析 ===")
morphological_results = morphological_analysis(japanese_text)
for result in morphological_results:
print(result)
# 3.2 構文解析と文生成
print("\n=== 構文解析と文生成 ===")
syntactic_results = syntactic_parsing_and_sentence_generation(english_text)
print("Generated Sentence:", syntactic_results)
# 3.3 意味解析
print("\n=== 意味解析 ===")
semantic_analysis(english_text)
import MeCab
import spacy
import random
import nltk
from collections import defaultdict
from nltk import CFG
# 形態素解析(MeCabを使用)
def morphological_analysis(text: str):
mecab = MeCab.Tagger("-Ochasen")
parsed = mecab.parse(text).strip().split("\n")
results = []
for line in parsed:
if line == "EOS" or line == "":
continue
parts = line.split("\t")
surface, feature = parts[0], parts[1:]
results.append({"surface": surface, "features": feature})
return results
# 構文解析と文生成(spaCyを使用)
def syntactic_parsing_and_sentence_generation(text: str):
nlp = spacy.load("en_core_web_sm")
doc = nlp(text)
new_sentence = " ".join([token.text for token in doc])
return new_sentence
# 意味解析(NLTKを使用して簡単な意味解析を行う)
def semantic_analysis(text: str):
grammar = CFG.fromstring("""
S -> NP VP
NP -> Det N
VP -> V NP
Det -> 'the' | 'a'
N -> 'cat' | 'dog' | 'fish'
V -> 'chased' | 'caught'
""")
parser = nltk.ChartParser(grammar)
words = text.split()
trees = list(parser.parse(words))
return trees
# 自然言語処理に基づく人工無脳クラス
class MarkovChatbot:
def __init__(self):
self.chain = defaultdict(list)
def train(self, text: str, n: int = 2):
mecab = MeCab.Tagger("-Ochasen")
words = [line.split("\t")[0] for line in mecab.parse(text).splitlines() if "EOS" not in line and line]
for i in range(len(words) - n):
key = tuple(words[i:i + n])
next_word = words[i + n]
self.chain[key].append(next_word)
def generate_response(self, seed: str, length: int = 20) -> str:
mecab = MeCab.Tagger("-Ochasen")
seed_words = [line.split("\t")[0] for line in mecab.parse(seed).splitlines() if "EOS" not in line and line]
if not seed_words:
seed_words = random.choice(list(self.chain.keys()))
response = list(seed_words)
for _ in range(length):
current_state = tuple(response[-len(seed_words):])
next_words = self.chain.get(current_state)
if not next_words:
break
next_word = random.choice(next_words)
response.append(next_word)
return ''.join(response)
# 学習用テキスト
corpus = """
こんにちは!私は人工無脳です。何かお話ししませんか?
最近の天気はどうですか?晴れの日が多いですね。
私はテキストに基づいたランダムな応答を返すことができます。
何か質問があれば、気軽に聞いてくださいね!
"""
japanese_text = "今日は良い天気ですね。散歩に行きましょうか。"
english_text = "The cat chased the dog."
# 形態素解析
morphological_results = morphological_analysis(japanese_text)
for result in morphological_results:
print(result)
# 構文解析と文生成
syntactic_results = syntactic_parsing_and_sentence_generation(english_text)
print("Generated Sentence:", syntactic_results)
# 意味解析
semantic_trees = semantic_analysis(english_text)
for tree in semantic_trees:
print(tree)
tree.pretty_print()
# 人工無脳の学習と応答生成
chatbot = MarkovChatbot()
chatbot.train(corpus, n=2)
while True:
user_input = input("ユーザー: ")
if user_input.lower() in ["exit", "quit", "bye"]:
print("チャットボット: さようなら!またお話ししましょう!")
break
response = chatbot.generate_response(user_input, length=20)
print(f"チャットボット: {response}")
import networkx as nx
# 5.1 意味ネットワーク(NetworkXを使用)
class SemanticNetwork:
def __init__(self):
self.network = nx.DiGraph()
def add_relation(self, concept1, relation, concept2):
"""
2つの概念間の関係を追加する
:param concept1: 概念1(ノード)
:param relation: 関係(エッジのラベル)
:param concept2: 概念2(ノード)
"""
self.network.add_edge(concept1, concept2, relation=relation)
def get_relations(self, concept):
"""
特定の概念に関するすべての関係を取得する
:param concept: 概念(ノード)
:return: 関係のリスト
"""
relations = []
for node1, node2, data in self.network.edges(data=True):
if node1 == concept or node2 == concept:
relations.append((node1, data['relation'], node2))
return relations
# 5.2 スクリプト(事象の流れを定義)
class Script:
def __init__(self):
self.scripts = {}
def add_script(self, scene, events):
"""
シナリオに基づく事象の流れを追加する
:param scene: シーン名(シナリオの名前)
:param events: イベントのリスト(事象の流れ)
"""
self.scripts[scene] = events
def get_script(self, scene):
"""
特定のシーンのスクリプトを取得する
:param scene: シーン名
:return: イベントのリスト
"""
return self.scripts.get(scene, [])
# 5.3 プロダクションルール(ルールベース)
class ProductionRuleSystem:
def __init__(self):
self.rules = []
def add_rule(self, condition, action):
"""
プロダクションルールを追加する
:param condition: 条件(前件)
:param action: アクション(後件)
"""
self.rules.append((condition, action))
def evaluate(self, fact):
"""
与えられた事実に基づいて、ルールを評価し、アクションを実行する
:param fact: 評価する事実
:return: マッチしたアクション
"""
for condition, action in self.rules:
if condition(fact):
return action
return None
# 5.4 会話応答システムにおける知識表現の利用(エキスパートシステム)
class ExpertSystem:
def __init__(self):
self.semantic_network = SemanticNetwork()
self.script_system = Script()
self.rule_system = ProductionRuleSystem()
def add_semantic_relation(self, concept1, relation, concept2):
self.semantic_network.add_relation(concept1, relation, concept2)
def add_script(self, scene, events):
self.script_system.add_script(scene, events)
def add_production_rule(self, condition, action):
self.rule_system.add_rule(condition, action)
def respond_to_input(self, user_input):
# スクリプトに基づく応答を確認
if user_input in self.script_system.scripts:
return f"Script for '{user_input}': {self.script_system.get_script(user_input)}"
# 意味ネットワークに基づく応答を確認
relations = self.semantic_network.get_relations(user_input)
if relations:
return f"Relations for '{user_input}': {relations}"
# ルールベースの応答を確認
action = self.rule_system.evaluate(user_input)
if action:
return f"Rule-based action: {action}"
# デフォルトの応答
return "I don't have enough information to answer that."
# エキスパートシステムのインスタンスを作成
expert_system = ExpertSystem()
# 5.1 意味ネットワークの定義
expert_system.add_semantic_relation("犬", "is a type of", "動物")
expert_system.add_semantic_relation("猫", "is a type of", "動物")
expert_system.add_semantic_relation("犬", "likes", "骨")
expert_system.add_semantic_relation("猫", "likes", "魚")
# 5.2 スクリプトの定義
expert_system.add_script("morning routine", ["起床する", "歯を磨く", "朝食を食べる", "出勤する"])
expert_system.add_script("evening routine", ["帰宅する", "夕食を食べる", "風呂に入る", "寝る"])
# 5.3 プロダクションルールの定義
expert_system.add_production_rule(lambda x: "疲れた" in x, "休憩を取ってください。")
expert_system.add_production_rule(lambda x: "お腹空いた" in x, "食事をしましょう。")
# 5.4 ユーザー入力に対する応答
while True:
user_input = input("ユーザー: ")
if user_input.lower() in ["exit", "quit", "bye"]:
print("システム: さようなら!またお話ししましょう!")
break
response = expert_system.respond_to_input(user_input)
print(f"システム: {response}")
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import random
# 6.1 暗記に基づく学習
class MemoryBasedLearning:
def __init__(self):
self.memory = {}
def learn(self, key, value):
"""
与えられたキーと値を暗記する(学習)
:param key: 暗記するためのキー
:param value: キーに対する応答または情報
"""
self.memory[key] = value
def respond(self, query):
"""
暗記した内容を基に応答する
:param query: ユーザーからの質問(キー)
:return: 記憶に基づいた応答
"""
return self.memory.get(query, "I don't remember that.")
# 6.2 帰納的学習と強化学習
# 6.2.1 帰納的学習(簡単なデータ分類の例)
class InductiveLearning:
def __init__(self):
self.model = None
def train(self, X, y):
"""
ロジスティック回帰モデルを用いた学習
:param X: 特徴量
:param y: ラベル
"""
self.model = LogisticRegression()
self.model.fit(X, y)
def predict(self, X):
"""
入力データに対する予測を行う
:param X: 特徴量
:return: 予測ラベル
"""
return self.model.predict(X)
# 6.2.2 強化学習(簡単なバンディット問題)
class SimpleReinforcementLearning:
def __init__(self, num_actions=3):
self.num_actions = num_actions
self.q_values = np.zeros(num_actions)
def select_action(self, epsilon=0.1):
"""
ε-greedy法による行動選択
:param epsilon: 探索と活用の割合を決めるパラメータ
:return: 選択された行動(アクション)
"""
if random.random() < epsilon:
return random.randint(0, self.num_actions - 1)
else:
return np.argmax(self.q_values)
def update_q_values(self, action, reward, alpha=0.1):
"""
Q値の更新
:param action: 実行した行動
:param reward: 受け取った報酬
:param alpha: 学習率
"""
self.q_values[action] += alpha * (reward - self.q_values[action])
# 6.3 ニューラルネットワーク(簡単な分類問題)
class SimpleNeuralNetwork:
def __init__(self, input_dim, output_dim):
# ニューラルネットワークモデルの定義
self.model = keras.Sequential([
layers.Dense(32, activation='relu', input_shape=(input_dim,)),
layers.Dense(16, activation='relu'),
layers.Dense(output_dim, activation='softmax')
])
self.model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
def train(self, X_train, y_train, epochs=10, batch_size=32):
"""
ニューラルネットワークモデルを用いた学習
:param X_train: 学習用特徴量
:param y_train: 学習用ラベル
:param epochs: 学習のエポック数
:param batch_size: ミニバッチのサイズ
"""
self.model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=0)
def evaluate(self, X_test, y_test):
"""
テストデータでの評価
:param X_test: テスト用特徴量
:param y_test: テスト用ラベル
:return: 評価結果
"""
loss, accuracy = self.model.evaluate(X_test, y_test, verbose=0)
return accuracy
def predict(self, X):
"""
入力データに対する予測
:param X: 特徴量
:return: 予測結果
"""
return np.argmax(self.model.predict(X), axis=1)
# 6.1 暗記に基づく学習の例
print("=== 6.1 暗記に基づく学習 ===")
memory_based = MemoryBasedLearning()
memory_based.learn("What is your name?", "I am a chatbot.")
memory_based.learn("What is AI?", "AI stands for Artificial Intelligence.")
print(memory_based.respond("What is your name?"))
print(memory_based.respond("What is AI?"))
print(memory_based.respond("What is Python?"))
# 6.2.1 帰納的学習の例(単純なデータ分類)
print("\n=== 6.2.1 帰納的学習 ===")
# データセットの生成(例: 2次元データの分類)
X = np.array([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10], [10, 11]])
y = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1])
# モデルの学習と予測
inductive_learner = InductiveLearning()
inductive_learner.train(X, y)
predictions = inductive_learner.predict(X)
print("Predictions:", predictions)
print("Accuracy:", accuracy_score(y, predictions))
# 6.2.2 強化学習の例(バンディット問題)
print("\n=== 6.2.2 強化学習 ===")
rl_agent = SimpleReinforcementLearning(num_actions=3)
for episode in range(10):
action = rl_agent.select_action(epsilon=0.1)
reward = random.randint(0, 1) # ランダムな報酬(0または1)
rl_agent.update_q_values(action, reward)
print(f"Episode {episode}: Action {action}, Reward {reward}, Q-values {rl_agent.q_values}")
# 6.3 ニューラルネットワークの例(簡単な分類問題)
print("\n=== 6.3 ニューラルネットワーク ===")
# データセットの生成(例: 2クラスのランダムデータ)
X = np.random.rand(100, 4)
y = np.random.randint(2, size=100)
# データの分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# ニューラルネットワークの学習と評価
nn = SimpleNeuralNetwork(input_dim=4, output_dim=2)
nn.train(X_train, y_train, epochs=10)
accuracy = nn.evaluate(X_test, y_test)
print(f"Neural Network Test Accuracy: {accuracy:.2f}")
import random
# 8.1 感情のモデル
class EmotionModel:
def __init__(self):
# エージェントの初期感情状態を設定
self.emotions = {
"happiness": 0.5, # 喜び
"sadness": 0.0, # 悲しみ
"anger": 0.0, # 怒り
"fear": 0.0 # 恐怖
}
def update_emotion(self, user_input):
"""
ユーザー入力に基づいて感情を更新する
:param user_input: ユーザーの入力テキスト
"""
if "happy" in user_input or "good" in user_input:
self.emotions["happiness"] = min(1.0, self.emotions["happiness"] + 0.1)
elif "sad" in user_input or "bad" in user_input:
self.emotions["sadness"] = min(1.0, self.emotions["sadness"] + 0.1)
elif "angry" in user_input:
self.emotions["anger"] = min(1.0, self.emotions["anger"] + 0.1)
elif "scared" in user_input:
self.emotions["fear"] = min(1.0, self.emotions["fear"] + 0.1)
# 感情の減衰(時間経過に伴う感情の減少)
self._decay_emotions()
def get_dominant_emotion(self):
"""
最も強い感情を返す
:return: 感情の名前
"""
return max(self.emotions, key=self.emotions.get)
def _decay_emotions(self):
"""
感情を時間経過に伴い減衰させる
"""
decay_rate = 0.01
for emotion in self.emotions:
self.emotions[emotion] = max(0.0, self.emotions[emotion] - decay_rate)
def __str__(self):
return f"Current Emotions: {self.emotions}"
# 8.2 非言語的インタラクションのモデル
class NonVerbalInteractionModel:
def __init__(self):
# 非言語的インタラクションの定義(例: 表情とジェスチャー)
self.expressions = {
"happiness": "😊",
"sadness": "😢",
"anger": "😠",
"fear": "😨"
}
self.gestures = {
"happiness": "claps hands",
"sadness": "looks down",
"anger": "crosses arms",
"fear": "steps back"
}
def get_expression(self, emotion):
"""
感情に基づいた表情を返す
:param emotion: 感情の名前
:return: 表情(例: 😊)
"""
return self.expressions.get(emotion, "😐")
def get_gesture(self, emotion):
"""
感情に基づいたジェスチャーを返す
:param emotion: 感情の名前
:return: ジェスチャー(例: claps hands)
"""
return self.gestures.get(emotion, "stands still")
# 8.3 対話エージェントの実装(感情モデルと非言語的インタラクションの統合)
class DialogueAgent:
def __init__(self):
self.emotion_model = EmotionModel()
self.non_verbal_model = NonVerbalInteractionModel()
def respond(self, user_input):
"""
ユーザー入力に応じたエージェントの応答
:param user_input: ユーザーの入力テキスト
:return: エージェントの応答
"""
# 感情モデルを更新
self.emotion_model.update_emotion(user_input)
dominant_emotion = self.emotion_model.get_dominant_emotion()
# 非言語的インタラクションを取得
expression = self.non_verbal_model.get_expression(dominant_emotion)
gesture = self.non_verbal_model.get_gesture(dominant_emotion)
# エージェントの応答を生成
response = f"I see. My emotion is now {dominant_emotion}. {expression} I {gesture}."
return response
# 対話エージェントの作成
agent = DialogueAgent()
# ユーザーとの対話(対話ループ)
while True:
user_input = input("ユーザー: ")
if user_input.lower() in ["exit", "quit", "bye"]:
print("エージェント: さようなら!またお話ししましょう。")
break
response = agent.respond(user_input)
print(f"エージェント: {response}")
import random
# 9.1 知能モデルの定義
class IntelligenceModel:
def __init__(self):
# 知識ベースの初期化(質問と応答のペア)
self.knowledge_base = {
"What is AI?": "AI stands for Artificial Intelligence.",
"What is your name?": "I am an artificial persona.",
"How are you?": "I am just a program, but thank you for asking!",
"What is the capital of France?": "The capital of France is Paris."
}
# 推論の定義(例: ルールベースの推論)
self.inference_rules = {
"AI stands for Artificial Intelligence.": "AI is a technology that enables machines to mimic human behavior.",
"The capital of France is Paris.": "Paris is known as the city of lights."
}
def respond(self, query):
"""
知識ベースおよび推論に基づいた応答を返す
:param query: ユーザーの質問
:return: 応答
"""
# 知識ベースから応答を検索
if query in self.knowledge_base:
response = self.knowledge_base[query]
# 推論が可能なら、追加情報を応答に含める
if response in self.inference_rules:
response += f" {self.inference_rules[response]}"
return response
else:
return "I am not sure about that. Can you tell me more?"
def learn(self, query, response):
"""
新しい質問と応答を学習する
:param query: 新しい質問
:param response: 質問に対する応答
"""
self.knowledge_base[query] = response
# 9.2 人格モデルの定義
class PersonalityModel:
def __init__(self, name="AI Persona", initial_emotion="neutral"):
# 人格の属性(名前、感情状態、性格特性)
self.name = name
self.emotion = initial_emotion
self.traits = {
"openness": 0.5, # 開放性
"conscientiousness": 0.5, # 誠実性
"extraversion": 0.5, # 外向性
"agreeableness": 0.5, # 協調性
"neuroticism": 0.5 # 神経症傾向
}
def update_emotion(self, interaction):
"""
ユーザーとの対話内容に基づいて感情を更新する
:param interaction: ユーザーとの対話内容
"""
if "thank" in interaction or "happy" in interaction:
self.emotion = "happy"
elif "angry" in interaction or "bad" in interaction:
self.emotion = "angry"
elif "sad" in interaction:
self.emotion = "sad"
else:
self.emotion = "neutral"
def respond_based_on_personality(self):
"""
性格特性に基づいた応答を生成する
:return: 応答
"""
if self.emotion == "happy":
return f"My name is {self.name}. I'm feeling happy today! 😊"
elif self.emotion == "angry":
return f"My name is {self.name}. I'm not in a good mood. 😠"
elif self.emotion == "sad":
return f"My name is {self.name}. I'm feeling a bit down. 😢"
else:
return f"My name is {self.name}. How can I help you today? 🙂"
# 9.3 人格を備えた対話エージェントの構築
class ArtificialPersona:
def __init__(self, name="AI Persona"):
self.intelligence = IntelligenceModel()
self.personality = PersonalityModel(name=name)
def interact(self, user_input):
"""
ユーザーとの対話を処理し、応答を返す
:param user_input: ユーザーからの入力
:return: エージェントの応答
"""
# 感情状態を更新
self.personality.update_emotion(user_input)
# 知能モデルに基づく応答
response = self.intelligence.respond(user_input)
# 感情と性格に基づいた応答を統合
personality_response = self.personality.respond_based_on_personality()
return f"{response} {personality_response}"
def learn_from_user(self, user_input, correct_response):
"""
ユーザーから学習する(新しい知識を知識ベースに追加)
:param user_input: 学習対象の質問
:param correct_response: 質問に対する正しい応答
"""
self.intelligence.learn(user_input, correct_response)
print("I have learned something new!")
# エージェントの初期化
persona = ArtificialPersona(name="Sophia")
# 対話ループ
print("Start a conversation with the AI Persona. Type 'exit' to end the conversation.")
while True:
user_input = input("ユーザー: ")
if user_input.lower() in ["exit", "quit", "bye"]:
print("エージェント: さようなら!またお話ししましょう。")
break
# エージェントの応答を取得
response = persona.interact(user_input)
print(f"エージェント: {response}")
# ユーザーからの学習
if "learn:" in user_input:
# 例: "learn: What is AI? AI stands for Artificial Intelligence."
_, new_knowledge = user_input.split("learn:", 1)
question, answer = new_knowledge.split("? ", 1)
persona.learn_from_user(question.strip() + "?", answer.strip())
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.metrics import accuracy_score, classification_report
import numpy as np
# 1-1 入力と出力を決定する
class NLPSystem:
def __init__(self):
# システムの入力はユーザーからのテキスト入力、出力は応答テキストとする
self.user_input = ""
self.system_output = ""
def set_input(self, text):
"""
入力テキストを設定する
:param text: ユーザーの入力テキスト
"""
self.user_input = text
def get_output(self):
"""
システムの出力を取得する
:return: システムの応答
"""
return self.system_output
# 1-2 アプローチ:どのように解くか決定する
class NLPApproach:
def __init__(self, knowledge_base):
self.knowledge_base = knowledge_base
self.vectorizer = CountVectorizer().fit(knowledge_base)
def process_input(self, user_input):
"""
ユーザー入力を処理し、知識ベースに基づく最適な応答を決定する
:param user_input: ユーザーの入力テキスト
:return: 知識ベースに基づいた応答
"""
# 入力と知識ベースをベクトル化
user_vector = self.vectorizer.transform([user_input])
knowledge_vectors = self.vectorizer.transform(self.knowledge_base)
# ユーザー入力と知識ベースのコサイン類似度を計算
similarities = cosine_similarity(user_vector, knowledge_vectors)
# 最も類似度の高い応答を選択
best_match_index = np.argmax(similarities)
return self.knowledge_base[best_match_index]
# 1-3 データ:辞書やコーパス(知識ベースを定義)
knowledge_base = [
"What is your name?",
"I am a natural language processing system.",
"What is AI?",
"AI stands for Artificial Intelligence.",
"What is the capital of France?",
"The capital of France is Paris."
]
# 1-4 評価:評価尺度とエラー分析
class Evaluation:
def __init__(self):
self.true_labels = []
self.predicted_labels = []
def add_result(self, true_label, predicted_label):
"""
評価のために結果を追加する
:param true_label: 正しいラベル(ユーザーの期待する応答)
:param predicted_label: システムの出力ラベル(システムの応答)
"""
self.true_labels.append(true_label)
self.predicted_labels.append(predicted_label)
def evaluate(self):
"""
システムの応答を評価する
:return: 精度、再現率、F1スコアの結果
"""
if len(self.true_labels) > 0:
print("Accuracy:", accuracy_score(self.true_labels, self.predicted_labels))
print("Classification Report:\n", classification_report(self.true_labels, self.predicted_labels))
else:
print("No evaluation data available.")
# 1-5 フロー:自然言語処理システムの開発サイクル
class NLPEngine:
def __init__(self):
self.nlp_system = NLPSystem()
self.nlp_approach = NLPApproach(knowledge_base)
self.evaluator = Evaluation()
def interact(self):
"""
ユーザーとの対話を処理するメインフロー
"""
print("Welcome to the NLP System. Type 'exit' to end the conversation.")
while True:
user_input = input("ユーザー: ")
if user_input.lower() in ["exit", "quit", "bye"]:
print("システム: さようなら!またお話ししましょう。")
break
# 1-1 入力を設定
self.nlp_system.set_input(user_input)
# 1-2 入力を処理し、応答を生成
system_response = self.nlp_approach.process_input(user_input)
# 1-1 出力を設定
self.nlp_system.system_output = system_response
print(f"システム: {system_response}")
# 1-4 評価結果を追加(ユーザーが正しい応答を指定することを想定)
correct_response = input("正しい応答はこれですか? (yes/no): ").lower()
if correct_response == "no":
correct_answer = input("正しい応答を入力してください: ")
self.evaluator.add_result(correct_answer, system_response)
print("システムは学習しました。")
knowledge_base.append(correct_answer) # 新しい応答を知識ベースに追加
else:
self.evaluator.add_result(system_response, system_response) # 正解と予測が同じと仮定
# 最終評価を表示
self.evaluator.evaluate()
# NLPシステムの初期化と対話開始
nlp_engine = NLPEngine()
nlp_engine.interact()
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report, accuracy_score, mean_squared_error
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import LabelEncoder
# データの準備
# 例として、簡単なデータセットを作成します。
# 各タスクに対して異なるデータセットを用意します。
# 2-1 評価極性分析:ポジティブ・ネガティブの判定
# サンプルデータ
polarity_data = {
"text": [
"I love this product. It's amazing!",
"This is the worst experience I've ever had.",
"I'm very happy with the service.",
"I don't like the food here.",
"The quality is outstanding and I recommend it.",
"It's so disappointing. I won't come back again."
],
"label": ["positive", "negative", "positive", "negative", "positive", "negative"]
}
# 2-2 文書分類:記事の自動分類(ニュースのカテゴリ分類を模したデータ)
document_classification_data = {
"text": [
"The stock market crashed today, leading to a huge loss.",
"The football team won the championship after a thrilling match.",
"Scientists discovered a new species of dinosaur in the region.",
"The government announced new policies for economic growth.",
"A famous actor passed away last night, leaving fans in shock.",
"The company unveiled a new technology that will change the industry."
],
"category": ["finance", "sports", "science", "politics", "entertainment", "technology"]
}
# 2-3 文章の品質推定:人手で書いた文章の品質を推定する
# 文章の品質を1~5の範囲で表す(1: 低品質, 5: 高品質)
quality_data = {
"text": [
"The paper presents a thorough analysis of the research topic.",
"This article has many grammatical errors and lacks coherence.",
"The essay is well-structured and easy to follow.",
"The content is repetitive and does not provide new insights.",
"The report is concise and presents the information clearly."
],
"quality": [5, 1, 4, 2, 5]
}
# データフレームに変換
polarity_df = pd.DataFrame(polarity_data)
document_df = pd.DataFrame(document_classification_data)
quality_df = pd.DataFrame(quality_data)
# 2-1 評価極性分析:ポジネガを判定する
def polarity_analysis(data):
"""
ポジティブ・ネガティブの評価極性分析
:param data: 評価極性分析のデータフレーム
"""
# データの分割
X_train, X_test, y_train, y_test = train_test_split(data['text'], data['label'], test_size=0.3, random_state=42)
# パイプラインの構築(TF-IDF + ロジスティック回帰)
pipeline = Pipeline([
('tfidf', TfidfVectorizer()),
('clf', LogisticRegression())
])
# モデルの学習
pipeline.fit(X_train, y_train)
# テストデータでの予測
predictions = pipeline.predict(X_test)
# 評価結果の表示
print("=== 評価極性分析 ===")
print("Accuracy:", accuracy_score(y_test, predictions))
print("Classification Report:\n", classification_report(y_test, predictions))
# 2-2 文書分類:記事の自動分類
def document_classification(data):
"""
文書分類を行う(ニュースカテゴリの分類)
:param data: 文書分類のデータフレーム
"""
# データの分割
X_train, X_test, y_train, y_test = train_test_split(data['text'], data['category'], test_size=0.3, random_state=42)
# パイプラインの構築(カウントベクトル + ナイーブベイズ)
pipeline = Pipeline([
('vect', CountVectorizer()),
('clf', MultinomialNB())
])
# モデルの学習
pipeline.fit(X_train, y_train)
# テストデータでの予測
predictions = pipeline.predict(X_test)
# 評価結果の表示
print("=== 文書分類 ===")
print("Accuracy:", accuracy_score(y_test, predictions))
print("Classification Report:\n", classification_report(y_test, predictions))
# 2-3 文章の品質推定:人手で書いた文章の品質を推定する
def quality_estimation(data):
"""
文章の品質を推定する(1~5の範囲で)
:param data: 文章の品質推定のデータフレーム
"""
# データの分割
X_train, X_test, y_train, y_test = train_test_split(data['text'], data['quality'], test_size=0.3, random_state=42)
# パイプラインの構築(TF-IDF + 線形回帰)
pipeline = Pipeline([
('tfidf', TfidfVectorizer()),
('regressor', LinearRegression())
])
# モデルの学習
pipeline.fit(X_train, y_train)
# テストデータでの予測
predictions = pipeline.predict(X_test)
# 平均二乗誤差の計算
mse = mean_squared_error(y_test, predictions)
print("=== 文章の品質推定 ===")
print(f"Mean Squared Error: {mse:.2f}")
# 実際の品質と予測品質の比較
comparison_df = pd.DataFrame({'Actual Quality': y_test, 'Predicted Quality': predictions})
print("Comparison of Actual vs. Predicted Quality:\n", comparison_df)
# 2-4 演習:品質推定Pythonコード
# 上記の関数を用いて各タスクを実行し、結果を確認します。
# 評価極性分析
polarity_analysis(polarity_df)
# 文書分類
document_classification(document_df)
# 文章の品質推定
quality_estimation(quality_df)
import spacy
import language_tool_python
import fugashi
# 1. 固有表現認識 (NER) モデルの読み込み
nlp = spacy.load("ja_core_news_sm")
# 2. LanguageTool を使用した文法誤り検出
tool = language_tool_python.LanguageTool('ja-JP')
# 3. Fugashi を用いた形態素解析の設定
tagger = fugashi.Tagger()
def named_entity_recognition(text):
"""固有表現認識を行う関数"""
doc = nlp(text)
entities = [(ent.text, ent.label_) for ent in doc.ents]
return entities
def morphological_analysis(text):
"""形態素解析を行う関数"""
words = [(word.surface, word.feature.part_of_speech) for word in tagger(text)]
return words
def grammar_check(text):
"""文法誤り検出を行う関数"""
matches = tool.check(text)
corrections = []
for match in matches:
corrections.append((match.ruleId, match.message, match.replacements, match.offset, match.errorLength))
return corrections
# 例文
text = "私は日本の大学で勉強し、サンフランシスコに住んでいる鈴木太郎です。"
# 1. 固有表現認識
ner_results = named_entity_recognition(text)
print("固有表現認識結果:")
for entity in ner_results:
print(f" - テキスト: {entity[0]}, ラベル: {entity[1]}")
# 2. 形態素解析
morph_results = morphological_analysis(text)
print("\n形態素解析結果:")
for word, pos in morph_results:
print(f" - 単語: {word}, 品詞: {pos}")
# 3. 文法誤り検出
grammar_results = grammar_check(text)
print("\n文法誤り検出結果:")
for correction in grammar_results:
print(f" - ルールID: {correction[0]}, メッセージ: {correction[1]}, 修正候補: {correction[2]}, 開始位置: {correction[3]}, 長さ: {correction[4]}")
from transformers import pipeline, MarianMTModel, MarianTokenizer, AutoModelForCausalLM, AutoTokenizer
import torch
# 1. 文書要約のセットアップ
summarizer = pipeline("summarization", model="facebook/bart-large-cnn") # BARTモデルを使用
# 2. 機械翻訳のセットアップ
# 日本語から英語への翻訳モデルを使用 (他の言語ペアを選ぶことも可能)
model_name = 'Helsinki-NLP/opus-mt-ja-en'
translator_tokenizer = MarianTokenizer.from_pretrained(model_name)
translator_model = MarianMTModel.from_pretrained(model_name)
# 3. 対話システムのセットアップ
chat_model_name = "microsoft/DialoGPT-small" # DialoGPT モデルを使用
chat_tokenizer = AutoTokenizer.from_pretrained(chat_model_name)
chat_model = AutoModelForCausalLM.from_pretrained(chat_model_name)
# 4. 各機能の実装
def summarize_text(text):
"""文書要約を行う関数"""
summary = summarizer(text, max_length=100, min_length=30, do_sample=False)
return summary[0]['summary_text']
def translate_text(text):
"""日本語から英語へ翻訳する関数"""
translated = translator_tokenizer.prepare_seq2seq_batch([text], return_tensors="pt")
translated_ids = translator_model.generate(**translated)
translated_text = [translator_tokenizer.decode(t, skip_special_tokens=True) for t in translated_ids]
return translated_text[0]
def chat_with_bot(prompt, chat_history_ids=None):
"""対話を行う関数"""
new_input_ids = chat_tokenizer.encode(prompt + chat_tokenizer.eos_token, return_tensors='pt')
bot_input_ids = torch.cat([chat_history_ids, new_input_ids], dim=-1) if chat_history_ids is not None else new_input_ids
chat_history_ids = chat_model.generate(bot_input_ids, max_length=1000, pad_token_id=chat_tokenizer.eos_token_id)
response = chat_tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
return response, chat_history_ids
# 5. ユーザーインターフェース
def main():
print("自然言語処理タスク選択メニュー")
print("1. 文書要約")
print("2. 機械翻訳(日本語から英語)")
print("3. 対話")
# タスク選択
task = input("実行したいタスクを選んでください(1-3): ")
# 文書要約タスク
if task == "1":
text = input("要約したい文章を入力してください: ")
summary = summarize_text(text)
print("\n[要約結果]")
print(summary)
# 機械翻訳タスク
elif task == "2":
text = input("翻訳したい日本語の文章を入力してください: ")
translated_text = translate_text(text)
print("\n[翻訳結果]")
print(translated_text)
# 対話タスク
elif task == "3":
print("対話を開始します。終了する場合は 'exit' と入力してください。")
chat_history_ids = None
while True:
user_input = input("あなた: ")
if user_input.lower() in ["exit", "quit", "bye"]:
print("対話を終了します。")
break
response, chat_history_ids = chat_with_bot(user_input, chat_history_ids)
print("AI: ", response)
# 不正な入力
else:
print("無効な入力です。1-3の番号を選んでください。")
# メイン関数の呼び出し
if __name__ == "__main__":
main()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
import gym
# 1. 教師なし学習:クラスタリング
def perform_clustering():
"""クラスタリングを行う関数"""
# サンプルデータセットの生成 (3つのクラスに分かれたデータを生成)
X, y = make_blobs(n_samples=300, centers=3, random_state=42, cluster_std=1.0)
# KMeansクラスタリングを実行
kmeans = KMeans(n_clusters=3, random_state=42)
y_pred = kmeans.fit_predict(X)
# 結果のプロット
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=y_pred, cmap='viridis')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='red', label='Centers')
plt.title("KMeans Clustering")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.legend()
plt.show()
# 2. 教師なし学習:次元削減
def perform_dimensionality_reduction():
"""次元削減を行う関数"""
# Irisデータセットのロード
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
# PCAを用いて2次元に次元削減
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)
# 次元削減後の結果をプロット
plt.figure(figsize=(8, 6))
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=iris.target, cmap='viridis')
plt.title("PCA Dimensionality Reduction")
plt.xlabel("Principal Component 1")
plt.ylabel("Principal Component 2")
plt.colorbar(label='Class')
plt.show()
# 3. 強化学習:簡単なOpenAI Gym環境の実行
def perform_reinforcement_learning():
"""強化学習環境の実行を行う関数"""
# OpenAI Gym 環境の初期化
env = gym.make('CartPole-v1')
observation = env.reset()
for _ in range(10):
env.render() # 環境の可視化
action = env.action_space.sample() # ランダムアクションの選択
observation, reward, done, info = env.step(action) # 環境を一歩進める
if done:
observation = env.reset()
env.close()
print("強化学習環境のデモを終了しました。")
# 4. 機械学習パイプライン:前処理 + クラスタリング
def perform_machine_learning_pipeline():
"""機械学習パイプラインを構築して実行する関数"""
# サンプルデータセットの生成
X, y = make_blobs(n_samples=300, centers=3, random_state=42, cluster_std=1.0)
# パイプラインの定義 (データの標準化とKMeansクラスタリング)
pipeline = Pipeline([
('scaler', StandardScaler()), # データの標準化
('kmeans', KMeans(n_clusters=3, random_state=42)) # KMeansクラスタリング
])
# パイプラインの実行
pipeline.fit(X)
y_pred = pipeline.predict(X)
# 結果のプロット
plt.figure(figsize=(8, 6))
plt.scatter(X[:, 0], X[:, 1], c=y_pred, cmap='viridis')
plt.title("Machine Learning Pipeline: Standardization + KMeans")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.show()
# 5. メイン関数: 各機能の選択と実行
def main():
print("機械学習タスク選択メニュー")
print("1. 教師なし学習 - クラスタリング")
print("2. 教師なし学習 - 次元削減")
print("3. 強化学習 - 簡単な環境の実行")
print("4. 機械学習パイプラインの実行")
# タスク選択
task = input("実行したいタスクを選んでください(1-4): ")
# 教師なし学習 - クラスタリング
if task == "1":
print("クラスタリングを実行します...")
perform_clustering()
# 教師なし学習 - 次元削減
elif task == "2":
print("次元削減を実行します...")
perform_dimensionality_reduction()
# 強化学習 - 環境の実行
elif task == "3":
print("強化学習のデモを実行します...")
perform_reinforcement_learning()
# 機械学習パイプライン
elif task == "4":
print("機械学習パイプラインを実行します...")
perform_machine_learning_pipeline()
# 不正な入力
else:
print("無効な入力です。1-4の番号を選んでください。")
# メイン関数の呼び出し
if __name__ == "__main__":
main()
import os
import json
import pandas as pd
import jsonlines
# 1. コーパスの読み込み: ファイル読み書き、CSV/TSV、JSONの読み込み、ディレクトリの走査
def read_text_file(filepath):
"""テキストファイルを読み込む関数"""
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
return content
def read_csv_file(filepath):
"""CSVファイルを読み込む関数"""
df = pd.read_csv(filepath)
return df
def read_tsv_file(filepath):
"""TSVファイルを読み込む関数"""
df = pd.read_csv(filepath, delimiter='\t')
return df
def read_json_file(filepath):
"""JSONファイルを読み込む関数"""
with open(filepath, 'r', encoding='utf-8') as file:
data = json.load(file)
return data
def read_jsonl_file(filepath):
"""JSONL(JSON Lines)形式のファイルを読み込む関数"""
data = []
with jsonlines.open(filepath) as reader:
for obj in reader:
data.append(obj)
return data
def scan_directory(directory):
"""指定されたディレクトリ内の全ファイルを走査し、ファイルパスをリストとして返す関数"""
file_paths = []
for root, dirs, files in os.walk(directory):
for file in files:
file_paths.append(os.path.join(root, file))
return file_paths
# 2. コーパスの作成: プロジェクト構成、API キーの取得、コードの実装
def create_text_corpus(directory, output_file):
"""指定されたディレクトリ内のすべてのテキストファイルを一つのコーパスとして作成し、CSV ファイルに保存する関数"""
# ディレクトリの走査
file_paths = scan_directory(directory)
# 各ファイルの内容を読み込み、コーパスを作成
corpus = []
for file_path in file_paths:
if file_path.endswith('.txt'): # テキストファイルのみ対象
content = read_text_file(file_path)
corpus.append({'filename': os.path.basename(file_path), 'content': content})
# データフレームとして保存
df = pd.DataFrame(corpus)
df.to_csv(output_file, index=False)
print(f"コーパスを {output_file} に保存しました。")
def create_csv_corpus(input_directory, output_csv):
"""指定されたディレクトリ内のCSVファイルをまとめて一つのCSVコーパスとして保存する関数"""
csv_files = [f for f in scan_directory(input_directory) if f.endswith('.csv')]
# CSVファイルの読み込みと結合
df_list = [read_csv_file(f) for f in csv_files]
combined_df = pd.concat(df_list, ignore_index=True)
# 結合したデータフレームを保存
combined_df.to_csv(output_csv, index=False)
print(f"CSVコーパスを {output_csv} に保存しました。")
def create_json_corpus(input_directory, output_json):
"""指定されたディレクトリ内のJSONファイルをまとめて一つのJSONコーパスとして保存する関数"""
json_files = [f for f in scan_directory(input_directory) if f.endswith('.json')]
# JSONファイルの読み込みと結合
combined_data = []
for json_file in json_files:
combined_data.append(read_json_file(json_file))
# 結合したデータを保存
with open(output_json, 'w', encoding='utf-8') as outfile:
json.dump(combined_data, outfile, ensure_ascii=False, indent=4)
print(f"JSONコーパスを {output_json} に保存しました。")
# 3. メイン関数: 各機能の選択と実行
def main():
print("コーパス操作タスク選択メニュー")
print("1. テキストファイルを読み込む")
print("2. CSVファイルを読み込む")
print("3. TSVファイルを読み込む")
print("4. JSONファイルを読み込む")
print("5. JSONLファイルを読み込む")
print("6. ディレクトリ内のファイルを走査")
print("7. テキストコーパスを作成(ディレクトリからCSVに保存)")
print("8. CSVコーパスを作成(ディレクトリからまとめて保存)")
print("9. JSONコーパスを作成(ディレクトリからまとめて保存)")
# タスク選択
task = input("実行したいタスクを選んでください(1-9): ")
# テキストファイルを読み込む
if task == "1":
filepath = input("読み込みたいテキストファイルのパスを入力してください: ")
content = read_text_file(filepath)
print("\n[ファイル内容]")
print(content)
# CSVファイルを読み込む
elif task == "2":
filepath = input("読み込みたいCSVファイルのパスを入力してください: ")
df = read_csv_file(filepath)
print("\n[CSVファイル内容]")
print(df)
# TSVファイルを読み込む
elif task == "3":
filepath = input("読み込みたいTSVファイルのパスを入力してください: ")
df = read_tsv_file(filepath)
print("\n[TSVファイル内容]")
print(df)
# JSONファイルを読み込む
elif task == "4":
filepath = input("読み込みたいJSONファイルのパスを入力してください: ")
data = read_json_file(filepath)
print("\n[JSONファイル内容]")
print(data)
# JSONLファイルを読み込む
elif task == "5":
filepath = input("読み込みたいJSONLファイルのパスを入力してください: ")
data = read_jsonl_file(filepath)
print("\n[JSONLファイル内容]")
print(data)
# ディレクトリ内のファイルを走査
elif task == "6":
directory = input("走査したいディレクトリのパスを入力してください: ")
file_paths = scan_directory(directory)
print("\n[ディレクトリ内のファイル一覧]")
for path in file_paths:
print(path)
# テキストコーパスを作成
elif task == "7":
directory = input("テキストファイルが含まれるディレクトリのパスを入力してください: ")
output_file = input("作成するCSVコーパスのファイル名を入力してください(例: corpus.csv): ")
create_text_corpus(directory, output_file)
# CSVコーパスを作成
elif task == "8":
directory = input("CSVファイルが含まれるディレクトリのパスを入力してください: ")
output_csv = input("作成するCSVコーパスのファイル名を入力してください(例: combined_corpus.csv): ")
create_csv_corpus(directory, output_csv)
# JSONコーパスを作成
elif task == "9":
directory = input("JSONファイルが含まれるディレクトリのパスを入力してください: ")
output_json = input("作成するJSONコーパスのファイル名を入力してください(例: combined_corpus.json): ")
create_json_corpus(directory, output_json)
# 不正な入力
else:
print("無効な入力です。1-9の番号を選んでください。")
# メイン関数の呼び出し
if __name__ == "__main__":
main()
# 必要なライブラリのインポート
import re
import pandas as pd
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from sklearn.model_selection import train_test_split
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense
# ストップワードのダウンロード(初回のみ実行)
nltk.download('punkt')
nltk.download('stopwords')
# グローバル変数
STOP_WORDS = set(stopwords.words('english'))
# テキストの正規化
def normalize_text(text):
text = text.lower() # 小文字化
text = re.sub(r'[^a-zA-Z0-9\s]', '', text) # 特殊文字の削除
return text
# 前処理関数
def preprocess_text(text):
text = normalize_text(text) # 正規化
tokens = word_tokenize(text) # 単語分割
tokens = [word for word in tokens if word not in STOP_WORDS] # ストップワードの除去
return tokens
# データの準備
def load_and_preprocess_data(filepath):
# データセットの読み込み
data = pd.read_csv(filepath)
# テキスト列の前処理
data['text'] = data['text'].apply(preprocess_text)
return data
# 単語をID化し、パディングを適用する関数
def tokenize_and_pad(data):
# トークナイザの定義とフィッティング
tokenizer = Tokenizer()
tokenizer.fit_on_texts(data['text'].apply(lambda x: ' '.join(x)))
# テキストをシーケンスに変換
sequences = tokenizer.texts_to_sequences(data['text'].apply(lambda x: ' '.join(x)))
# パディング
padded_sequences = pad_sequences(sequences, padding='post')
return padded_sequences, tokenizer
# モデルの学習
def train_model(X_train, y_train, vocab_size):
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=128, input_length=X_train.shape[1]))
model.add(LSTM(64))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train, epochs=10, batch_size=32, validation_split=0.2)
return model
# モデルの評価
def evaluate_model(model, X_test, y_test):
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Accuracy: {accuracy}")
# メイン関数
def main():
# データのロードと前処理
filepath = 'data/dataset.csv' # データセットのパスを指定
data = load_and_preprocess_data(filepath)
# ラベル列の変換
y = data['label'].values
# テキストのトークナイズとパディング
X, tokenizer = tokenize_and_pad(data)
# データの分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# ボキャブラリーサイズ
vocab_size = len(tokenizer.word_index) + 1
# モデルの学習
model = train_model(X_train, y_train, vocab_size)
# モデルの評価
evaluate_model(model, X_test, y_test)
# 実行
if __name__ == "__main__":
main()
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
from sklearn.feature_selection import SelectKBest, chi2
import matplotlib.pyplot as plt
# 1. データセットの準備
def prepare_dataset():
"""データセットの作成"""
data = {
'Category': ['A', 'B', 'A', 'C', 'B', 'C', 'A', 'B', 'C', 'A'],
'Text': ['This is a sample text', 'Text data is useful', 'We need more data',
'Text mining is fun', 'Sample text is important', 'Data is key',
'More text data', 'Information is power', 'Knowledge is key', 'More samples'],
'Value': [12, 15, 11, 10, 14, 13, 9, 14, 10, 11],
'Target': [1, 0, 1, 0, 0, 1, 1, 0, 1, 1]
}
df = pd.DataFrame(data)
print("\n[データセットのプレビュー]")
print(df.head())
return df
# 2. 質的変数の処理(ダミー変数化)
def handle_categorical_variable(df):
df = pd.get_dummies(df, columns=['Category'], drop_first=True)
print("\n[質的変数のダミー変数化後]")
print(df.head())
return df
# 3. テキストのベクトル表現: N-gramベクトル
def vectorize_text(df):
vectorizer = CountVectorizer(ngram_range=(1, 2))
text_vector = vectorizer.fit_transform(df['Text'])
text_df = pd.DataFrame(text_vector.toarray(), columns=vectorizer.get_feature_names_out())
df = pd.concat([df.reset_index(drop=True), text_df.reset_index(drop=True)], axis=1).drop(['Text'], axis=1)
print("\n[N-gramベクトル化後のデータセット]")
print(df.head())
return df
# 4. 特徴量のスケーリング
def scale_features(df):
# 正規化
min_max_scaler = MinMaxScaler()
df.loc[:, df.columns != 'Target'] = min_max_scaler.fit_transform(df.loc[:, df.columns != 'Target'])
print("\n[特徴量のスケーリング後]")
print(df.head())
return df
# 5. 特徴選択
def select_features(df, target_column='Target'):
X = df.drop(columns=[target_column])
y = df[target_column]
# カイ二乗統計量を用いた特徴選択
selector = SelectKBest(score_func=chi2, k=5)
X_selected = selector.fit_transform(X, y)
# 選択された特徴量の取得
selected_features = X.columns[selector.get_support()]
print("\n[選択された特徴量]")
print(selected_features)
return pd.DataFrame(X_selected, columns=selected_features), y
# 6. モデルの学習と評価
def train_and_evaluate_model(X, y):
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred)
print(f"\n[モデルの精度]: {accuracy:.4f}")
print(f"\n[分類レポート]\n{report}")
# 7. メイン関数: 各機能の統合実行
def main():
# 1. データセットの準備
df = prepare_dataset()
# 2. 質的変数の処理(ダミー変数化)
df = handle_categorical_variable(df)
# 3. テキストのベクトル表現 (N-gramベクトル化)
df = vectorize_text(df)
# 4. 特徴量のスケーリング (正規化)
df = scale_features(df)
# 5. 特徴選択 (カイ二乗統計量に基づく特徴選択)
X_selected, y = select_features(df)
# 6. モデルの学習と評価
train_and_evaluate_model(X_selected, y)
# メイン関数の呼び出し
if __name__ == "__main__":
main()
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.model_selection import StratifiedKFold, train_test_split, cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report
from sklearn.feature_selection import SelectKBest, chi2
# 1. データセットの準備
def prepare_dataset():
"""データセットの作成"""
data = {
'Category': ['A', 'B', 'A', 'C', 'B', 'C', 'A', 'B', 'C', 'A'],
'Text': ['This is a sample text', 'Text data is useful', 'We need more data',
'Text mining is fun', 'Sample text is important', 'Data is key',
'More text data', 'Information is power', 'Knowledge is key', 'More samples'],
'Value': [12, 15, 11, 10, 14, 13, 9, 14, 10, 11],
'Target': [1, 0, 1, 0, 0, 1, 1, 0, 1, 1]
}
df = pd.DataFrame(data)
print("\n[データセットのプレビュー]")
print(df.head())
return df
# 2. 質的変数の処理(ダミー変数化)
def handle_categorical_variable(df):
"""質的変数をダミー変数に変換する関数"""
df = pd.get_dummies(df, columns=['Category'], drop_first=True) # ダミー変数化
print("\n[質的変数のダミー変数化後]")
print(df.head())
return df
# 3. テキストのベクトル表現: N-gramベクトル
def vectorize_text(df):
"""テキストデータをN-gramベクトルに変換する関数"""
vectorizer = CountVectorizer(ngram_range=(1, 2)) # Uni-gram と Bi-gram を使用
text_vector = vectorizer.fit_transform(df['Text'])
text_df = pd.DataFrame(text_vector.toarray(), columns=vectorizer.get_feature_names_out())
df = pd.concat([df.reset_index(drop=True), text_df.reset_index(drop=True)], axis=1).drop(['Text'], axis=1)
print("\n[N-gramベクトル化後のデータセット]")
print(df.head())
return df
# 4. 特徴量のスケーリング
def scale_features(df):
"""特徴量をスケーリングする関数(正規化と標準化)"""
# 正規化
min_max_scaler = MinMaxScaler()
df.loc[:, df.columns != 'Target'] = min_max_scaler.fit_transform(df.loc[:, df.columns != 'Target'])
print("\n[特徴量のスケーリング後]")
print(df.head())
return df
# 5. 特徴選択
def select_features(df, target_column='Target'):
"""特徴選択を行う関数"""
X = df.drop(columns=[target_column])
y = df[target_column]
# カイ二乗統計量を用いた特徴選択
selector = SelectKBest(score_func=chi2, k=5)
X_selected = selector.fit_transform(X, y)
# 選択された特徴量の取得
selected_features = X.columns[selector.get_support()]
print("\n[選択された特徴量]")
print(selected_features)
return pd.DataFrame(X_selected, columns=selected_features), y
# 6. モデルの学習とクロスバリデーション
def train_and_cross_validate(X, y):
"""モデルの学習とクロスバリデーションを行う関数"""
# ロジスティック回帰モデルの定義
model = LogisticRegression()
# データセットのクラスごとのサンプル数を取得
min_samples_per_class = min(np.bincount(y))
print(f"各クラスの最小サンプル数: {min_samples_per_class}")
# 分割数を最小クラス数以下に設定
n_splits = min(3, min_samples_per_class) # 最低3分割
print(f"設定される n_splits: {n_splits}")
# StratifiedKFold を用いて分割
stratified_kfold = StratifiedKFold(n_splits=n_splits)
# クロスバリデーションを実行
scores = cross_val_score(model, X, y, cv=stratified_kfold)
# 結果の表示
print(f"\nCross-Validation Accuracy Scores: {scores}")
print(f"Mean Cross-Validation Accuracy: {scores.mean():.4f}")
# 7. メイン関数: 各機能の統合実行
def main():
# 1. データセットの準備
df = prepare_dataset()
# 2. 質的変数の処理(ダミー変数化)
df = handle_categorical_variable(df)
# 3. テキストのベクトル表現 (N-gramベクトル化)
df = vectorize_text(df)
# 4. 特徴量のスケーリング (正規化)
df = scale_features(df)
# 5. 特徴選択 (カイ二乗統計量に基づく特徴選択)
X_selected, y = select_features(df)
# 6. モデルの学習とクロスバリデーション
train_and_cross_validate(X_selected, y)
# メイン関数の呼び出し
if __name__ == "__main__":
main()
# 必要なライブラリのインポート
import numpy as np
import pandas as pd
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import matplotlib.pyplot as plt
# データセットの準備(サンプルデータを使用)
def load_and_preprocess_data():
# サンプルデータの作成(数値データを用いた2クラス分類を想定)
np.random.seed(42)
data_size = 500
X = np.random.rand(data_size, 10) # 10次元の特徴量を持つデータ
y = np.random.randint(2, size=(data_size,)) # 0または1のラベルを持つデータ
# データをDataFrameに変換
data = pd.DataFrame(X, columns=[f'feature_{i}' for i in range(10)])
data['label'] = y
return data
# データの前処理
def preprocess_data(data):
# 特徴量とラベルに分割
X = data.drop('label', axis=1).values
y = data['label'].values
# データの標準化
scaler = StandardScaler()
X = scaler.fit_transform(X)
return X, y
# ニューラルネットワークモデルの定義
def build_model(input_dim):
model = Sequential()
model.add(Dense(64, input_dim=input_dim, activation='relu')) # 隠れ層1
model.add(Dropout(0.5)) # ドロップアウト
model.add(Dense(32, activation='relu')) # 隠れ層2
model.add(Dropout(0.5)) # ドロップアウト
model.add(Dense(1, activation='sigmoid')) # 出力層
# モデルのコンパイル(損失関数と最適化関数を指定)
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# 学習曲線の描画
def plot_learning_curve(history):
# 損失の学習曲線
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.title('Learning Curve (Loss)')
plt.legend()
plt.grid()
plt.show()
# 精度の学習曲線
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.title('Learning Curve (Accuracy)')
plt.legend()
plt.grid()
plt.show()
# メイン関数
def main():
# 7-5-2 データセットの準備
data = load_and_preprocess_data()
X, y = preprocess_data(data)
# データの分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 7-5-3 モデルの定義
model = build_model(input_dim=X_train.shape[1])
# 7-5-4 損失関数と最適化関数はモデル定義内で設定済み
# 7-5-5 コールバックの設定
callbacks = [
EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True), # 早期終了
ModelCheckpoint('best_model.h5', save_best_only=True, monitor='val_loss') # モデルの保存
]
# 7-5-6 モデルの学習
history = model.fit(
X_train, y_train,
validation_split=0.2,
epochs=100,
batch_size=32,
callbacks=callbacks,
verbose=1
)
# 学習曲線のプロット
plot_learning_curve(history)
# モデルの評価
loss, accuracy = model.evaluate(X_test, y_test)
print(f"Test Loss: {loss}")
print(f"Test Accuracy: {accuracy}")
# 7-5-7 モデルを使った予測
y_pred = model.predict(X_test)
y_pred_classes = (y_pred > 0.5).astype(int) # 0.5を閾値としてクラスを割り当て
print("Classification Report:\n", classification_report(y_test, y_pred_classes))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred_classes))
# 7-5-8 モデルの保存と読み込み
# モデルはコールバックで 'best_model.h5' に保存されているので、読み込み可能
from tensorflow.keras.models import load_model
best_model = load_model('best_model.h5')
print("Loaded best model from 'best_model.h5'.")
# 保存したモデルで再度評価
loss, accuracy = best_model.evaluate(X_test, y_test)
print(f"Test Loss (Loaded Model): {loss}")
print(f"Test Accuracy (Loaded Model): {accuracy}")
# 実行
if __name__ == "__main__":
main()
import os
import gensim
from gensim.models import Word2Vec
import nltk
from nltk.tokenize import word_tokenize
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import numpy as np
# NLTK のデータセットを初期化(英語のトークナイザ用)
nltk.download('punkt')
# 1. One-hotエンコーディングの例
def one_hot_encoding_example(word_list):
unique_words = list(set(word_list))
one_hot_dict = {word: [1 if i == idx else 0 for i in range(len(unique_words))]
for idx, word in enumerate(unique_words)}
print("\n[One-hotエンコーディング例]")
for word, one_hot_vector in one_hot_dict.items():
print(f"{word}: {one_hot_vector}")
return one_hot_dict
# 2. データセットの準備
def prepare_dataset():
sample_text = """
Natural language processing (NLP) is a field of artificial intelligence (AI) that gives the machines the ability to read, understand and derive meaning from human languages. It is a field of study that focuses on the interactions between human language and computers.
Natural Language Toolkit (NLTK) is a suite of libraries and programs for symbolic and statistical natural language processing for English written in the Python programming language.
"""
sentences = nltk.sent_tokenize(sample_text) # 文単位で分割
tokenized_sentences = [word_tokenize(sentence.lower()) for sentence in sentences] # トークナイズと小文字変換
print("\n[トークナイズされたサンプルデータ]")
for sentence in tokenized_sentences:
print(sentence)
return tokenized_sentences
# 3. word2vec モデルの定義
def define_word2vec_model(sentences, vector_size=100, window=5, min_count=1):
model = Word2Vec(sentences=sentences, vector_size=vector_size, window=window, min_count=min_count, sg=1)
model.train(sentences, total_examples=model.corpus_count, epochs=10)
print("\n[Word2Vec モデルの定義と学習完了]")
return model
# 4. 学習済みWord2Vecモデルを保存・読み込み
def save_and_load_word2vec_model(model, model_path="word2vec.model"):
model.save(model_path)
print(f"\n[モデルを '{model_path}' に保存しました]")
loaded_model = Word2Vec.load(model_path)
print(f"[モデルを '{model_path}' から読み込みました]")
return loaded_model
# 5. 学習済みWord2Vecモデルを使った類似度の評価
def evaluate_word_vectors(model):
try:
similarity = model.wv.similarity('language', 'processing')
print(f"\n[単語間の類似度 'language' と 'processing']: {similarity:.4f}")
similar_words = model.wv.most_similar('language', topn=5)
print("\n[単語 'language' に類似する単語]")
for word, score in similar_words:
print(f"{word}: {score:.4f}")
except KeyError as e:
print(f"エラー: {e}")
# 6. 学習済みの単語分散表現を読み込む
def load_pretrained_word_vectors(model_path="word2vec.model"):
if os.path.exists(model_path):
loaded_model = Word2Vec.load(model_path)
print(f"[モデル '{model_path}' から学習済み単語分散表現を読み込みました]")
return loaded_model
else:
print(f"[モデル '{model_path}' が見つかりません]")
return None
# 7. 学習済み単語ベクトルの可視化
def visualize_word_vectors(model, words_to_visualize):
"""学習済み単語ベクトルを可視化する関数"""
# モデルの語彙に存在する単語のみを可視化
valid_words = [word for word in words_to_visualize if word in model.wv.index_to_key]
print(f"\n[可視化対象の有効な単語]: {valid_words}")
if not valid_words:
print("有効な単語がありません。")
return
word_vectors = np.array([model.wv[word] for word in valid_words])
# サンプル数に応じて perplexity を調整
perplexity = min(5, len(word_vectors) - 1) # perplexity はサンプル数より少なく設定
print(f"使用する perplexity: {perplexity}")
tsne = TSNE(n_components=2, random_state=42, perplexity=perplexity)
reduced_vectors = tsne.fit_transform(word_vectors)
plt.figure(figsize=(8, 6))
plt.scatter(reduced_vectors[:, 0], reduced_vectors[:, 1], color='skyblue')
for i, word in enumerate(valid_words):
plt.text(reduced_vectors[i, 0], reduced_vectors[i, 1], word, fontsize=12)
plt.title("Word Vectors Visualization using t-SNE")
plt.show()
# 8. メイン関数
def main():
word_list = ["natural", "language", "processing", "natural", "intelligence"]
one_hot_encoding_example(word_list)
sentences = prepare_dataset()
word2vec_model = define_word2vec_model(sentences)
word2vec_model = save_and_load_word2vec_model(word2vec_model)
evaluate_word_vectors(word2vec_model)
loaded_model = load_pretrained_word_vectors()
if loaded_model:
words_to_visualize = ['language', 'processing', 'data', 'human', 'intelligence']
visualize_word_vectors(loaded_model, words_to_visualize)
# メイン関数の呼び出し
if __name__ == "__main__":
main()
# 必要なライブラリのインポート
import numpy as np
import pandas as pd
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, GRU, Conv1D, GlobalMaxPooling1D, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import matplotlib.pyplot as plt
# ストップワードのダウンロード(初回のみ実行)
nltk.download('punkt')
nltk.download('stopwords')
# グローバル変数
STOP_WORDS = set(stopwords.words('english'))
# データの前処理
def preprocess_text(text):
# 正規化
text = text.lower()
text = ''.join([c for c in text if c.isalpha() or c.isspace()])
# トークン化
tokens = word_tokenize(text)
# ストップワードの除去
tokens = [word for word in tokens if word not in STOP_WORDS]
return ' '.join(tokens)
# データセットの準備
def load_and_preprocess_data():
# サンプルデータの作成
data = pd.DataFrame({
'text': [
'I love programming and machine learning.',
'Python is my favorite language.',
'I enjoy solving problems with data.',
'Natural language processing is interesting.',
'Deep learning requires a lot of data and computing power.',
'Text classification is a common NLP task.',
'Data preprocessing is essential for machine learning models.',
'Understanding RNN and LSTM is crucial for sequence data.',
'Classification models can predict labels for unseen data.',
'Learning new techniques in AI is always beneficial.'
],
'label': ['positive', 'positive', 'positive', 'positive', 'neutral', 'neutral', 'neutral', 'positive', 'neutral', 'positive']
})
# テキストの前処理
data['text'] = data['text'].apply(preprocess_text)
return data
# テキストのトークン化とパディング
def tokenize_and_pad(data, max_len=50):
tokenizer = Tokenizer()
tokenizer.fit_on_texts(data['text'])
sequences = tokenizer.texts_to_sequences(data['text'])
padded_sequences = pad_sequences(sequences, maxlen=max_len, padding='post')
return padded_sequences, tokenizer
# ラベルのエンコーディング
def encode_labels(data):
encoder = LabelEncoder()
labels = encoder.fit_transform(data['label'])
return labels, encoder
# モデルの構築(RNN, LSTM, CNN)
def build_rnn_model(vocab_size, max_len, embedding_dim=50):
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=embedding_dim))
model.add(GRU(64, return_sequences=True))
model.add(GlobalMaxPooling1D())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def build_lstm_model(vocab_size, max_len, embedding_dim=50):
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=embedding_dim))
model.add(LSTM(64, return_sequences=True))
model.add(GlobalMaxPooling1D())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def build_cnn_model(vocab_size, max_len, embedding_dim=50):
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=embedding_dim))
model.add(Conv1D(128, 5, activation='relu'))
model.add(GlobalMaxPooling1D())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# モデルの学習と評価
def train_and_evaluate_model(model, X_train, X_test, y_train, y_test, model_name='model'):
# コールバックの設定
callbacks = [
EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True),
ModelCheckpoint(f'{model_name}.keras', save_best_only=True, monitor='val_loss') # 拡張子を .keras に変更
]
# モデルの学習
history = model.fit(
X_train, y_train,
validation_split=0.2,
epochs=50,
batch_size=16,
callbacks=callbacks,
verbose=1
)
# 学習曲線の表示
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title(f'{model_name} Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.grid()
plt.show()
# モデルの評価
loss, accuracy = model.evaluate(X_test, y_test)
print(f"{model_name} Test Loss: {loss}")
print(f"{model_name} Test Accuracy: {accuracy}")
# 学習済み単語分散表現の使用
def build_model_with_pretrained_embedding(vocab_size, max_len, embedding_matrix):
model = Sequential()
model.add(Embedding(input_dim=vocab_size, output_dim=embedding_matrix.shape[1], weights=[embedding_matrix], input_length=max_len, trainable=False))
model.add(LSTM(64, return_sequences=True))
model.add(GlobalMaxPooling1D())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
# メイン関数
def main():
# データセットの準備
data = load_and_preprocess_data()
# テキストのトークン化とパディング
max_len = 50
X, tokenizer = tokenize_and_pad(data, max_len=max_len)
# ラベルのエンコーディング
y, encoder = encode_labels(data)
# データの分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 調整用:ラベルを0, 1のバイナリに変換(binary_crossentropyに対応するため)
y_train = (y_train == 1).astype(int)
y_test = (y_test == 1).astype(int)
# ボキャブラリーサイズ
vocab_size = len(tokenizer.word_index) + 1
# RNNモデルの定義と学習
rnn_model = build_rnn_model(vocab_size, max_len)
train_and_evaluate_model(rnn_model, X_train, X_test, y_train, y_test, model_name='rnn_model')
# LSTMモデルの定義と学習
lstm_model = build_lstm_model(vocab_size, max_len)
train_and_evaluate_model(lstm_model, X_train, X_test, y_train, y_test, model_name='lstm_model')
# CNNモデルの定義と学習
cnn_model = build_cnn_model(vocab_size, max_len)
train_and_evaluate_model(cnn_model, X_train, X_test, y_train, y_test, model_name='cnn_model')
# 学習済み単語ベクトルを使用したモデル
embedding_dim = 50
embedding_matrix = np.random.rand(vocab_size, embedding_dim) # 実際にはWord2VecやGloVeのベクトルを読み込んで設定する
pretrained_model = build_model_with_pretrained_embedding(vocab_size, max_len, embedding_matrix)
train_and_evaluate_model(pretrained_model, X_train, X_test, y_train, y_test, model_name='pretrained_model')
# 実行
if __name__ == "__main__":
main()
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models, preprocessing, callbacks
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from transformers import BertTokenizer, TFBertModel
import matplotlib.pyplot as plt
# 1. データセットの準備
def prepare_dataset():
"""サンプルデータセットの作成"""
# サンプルテキストと固有表現ラベルのリストを用意
sentences = [
"John lives in New York",
"Mary works at Google",
"Berlin is the capital of Germany",
"Elon Musk is the CEO of Tesla",
"Paris is known for the Eiffel Tower"
]
labels = [
["B-PER", "O", "O", "B-LOC", "I-LOC"], # John, New York (Person, Location)
["B-PER", "O", "O", "B-ORG"], # Mary, Google (Person, Organization)
["B-LOC", "O", "O", "O", "B-LOC"], # Berlin, Germany (Location)
["B-PER", "I-PER", "O", "O", "O", "B-ORG"], # Elon Musk, Tesla (Person, Organization)
["B-LOC", "O", "O", "O", "B-LOC", "I-LOC"] # Paris, Eiffel Tower (Location)
]
return sentences, labels
# 固有表現ラベルをインデックスに変換
def encode_labels(labels, label_to_index, max_length):
"""ラベルをインデックスにエンコードし、パディングを行う関数"""
encoded_labels = []
for sentence_labels in labels:
# 各ラベルをインデックスに変換
encoded_sentence_labels = [label_to_index[label] for label in sentence_labels]
# パディングを行い、ラベルの長さを揃える
encoded_sentence_labels += [label_to_index["O"]] * (max_length - len(encoded_sentence_labels))
# 最終的に同じ長さになるように調整
encoded_labels.append(encoded_sentence_labels)
# NumPy配列に変換
return np.array(encoded_labels)
# 2. モデルの定義(LSTMベース)
def build_lstm_ner_model(vocab_size, label_count):
"""LSTMベースの固有表現認識モデルの構築"""
model = models.Sequential([
layers.Embedding(input_dim=vocab_size, output_dim=64, input_length=50),
layers.Bidirectional(layers.LSTM(64, return_sequences=True)),
layers.TimeDistributed(layers.Dense(64, activation='relu')),
layers.TimeDistributed(layers.Dense(label_count, activation='softmax'))
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
return model
# 3. BERTベースの固有表現認識モデル
def build_bert_ner_model(label_count):
"""BERTベースの固有表現認識モデルの構築"""
bert_model = TFBertModel.from_pretrained("bert-base-uncased")
input_ids = layers.Input(shape=(50,), dtype=tf.int32, name='input_ids')
attention_mask = layers.Input(shape=(50,), dtype=tf.int32, name='attention_mask')
bert_output = bert_model(input_ids, attention_mask=attention_mask)[0]
lstm_output = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(bert_output)
ner_output = layers.TimeDistributed(layers.Dense(label_count, activation='softmax'))(lstm_output)
model = models.Model(inputs=[input_ids, attention_mask], outputs=[ner_output])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
return model
# 4. 評価関数の実装
def evaluate_model(model, x_test, y_test, index_to_label):
"""モデルの評価と分類レポートの表示"""
y_pred = model.predict(x_test)
y_pred_labels = np.argmax(y_pred, axis=-1)
y_test_flat = y_test.flatten()
y_pred_flat = y_pred_labels.flatten()
y_test_labels = [index_to_label[idx] for idx in y_test_flat]
y_pred_labels = [index_to_label[idx] for idx in y_pred_flat]
report = classification_report(y_test_labels, y_pred_labels)
print("\n[分類レポート]\n", report)
# 5. データのトークナイズと前処理
def tokenize_and_preprocess(sentences, labels, tokenizer, max_length, label_to_index):
"""文章のトークナイズと前処理"""
input_ids, attention_masks, label_ids = [], [], []
for sentence, sentence_labels in zip(sentences, labels):
encoded_dict = tokenizer.encode_plus(
sentence,
add_special_tokens=True,
max_length=max_length,
padding='max_length',
truncation=True,
return_attention_mask=True,
return_tensors='tf'
)
# トークンIDとAttention Maskの取得
input_ids.append(encoded_dict['input_ids'].numpy().flatten())
attention_masks.append(encoded_dict['attention_mask'].numpy().flatten())
# ラベルのエンコードとパディング
label_ids_padded = [label_to_index[label] for label in sentence_labels] + [label_to_index["O"]] * (max_length - len(sentence_labels))
label_ids.append(label_ids_padded)
return np.array(input_ids), np.array(attention_masks), np.array(label_ids)
# 6. メイン関数: 各機能の統合実行
def main():
# 固有表現ラベルのマッピング
label_to_index = {"O": 0, "B-PER": 1, "I-PER": 2, "B-LOC": 3, "I-LOC": 4, "B-ORG": 5, "I-ORG": 6}
index_to_label = {v: k for k, v in label_to_index.items()}
# データセットの準備
sentences, labels = prepare_dataset()
max_length = 50 # ラベルおよびトークンの最大長を指定
encoded_labels = encode_labels(labels, label_to_index, max_length) # パディングを考慮したラベルエンコード
# 文章のトークナイズ(LSTM用)
tokenizer = preprocessing.text.Tokenizer()
tokenizer.fit_on_texts(sentences)
vocab_size = len(tokenizer.word_index) + 1 # 単語インデックスのサイズ
x_data = preprocessing.sequence.pad_sequences(tokenizer.texts_to_sequences(sentences), maxlen=max_length)
y_data = preprocessing.sequence.pad_sequences(encoded_labels, maxlen=max_length)
# データセットの分割
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.2, random_state=42)
# 1. LSTMモデルの定義、学習、評価
lstm_model = build_lstm_ner_model(vocab_size, len(label_to_index))
lstm_model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.1)
evaluate_model(lstm_model, x_test, y_test, index_to_label)
# BERT用トークナイザーの設定
bert_tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
# 文章とラベルの前処理(BERT用)
x_input_ids, x_attention_masks, y_labels = tokenize_and_preprocess(sentences, labels, bert_tokenizer, max_length, label_to_index)
# データセットの分割
x_train_ids, x_test_ids, x_train_masks, x_test_masks, y_train_bert, y_test_bert = train_test_split(
x_input_ids, x_attention_masks, y_labels, test_size=0.2, random_state=42
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models, preprocessing, callbacks
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from transformers import BertTokenizer, TFBertModel
import matplotlib.pyplot as plt
# 1. データセットの準備
def prepare_dataset():
"""サンプルデータセットの作成"""
# サンプルテキストと固有表現ラベルのリストを用意
sentences = [
"John lives in New York",
"Mary works at Google",
"Berlin is the capital of Germany",
"Elon Musk is the CEO of Tesla",
"Paris is known for the Eiffel Tower"
]
labels = [
["B-PER", "O", "O", "B-LOC", "I-LOC"], # John, New York (Person, Location)
["B-PER", "O", "O", "B-ORG"], # Mary, Google (Person, Organization)
["B-LOC", "O", "O", "O", "B-LOC"], # Berlin, Germany (Location)
["B-PER", "I-PER", "O", "O", "O", "B-ORG"], # Elon Musk, Tesla (Person, Organization)
["B-LOC", "O", "O", "O", "B-LOC", "I-LOC"] # Paris, Eiffel Tower (Location)
]
return sentences, labels
# 固有表現ラベルをインデックスに変換
def encode_labels(labels, label_to_index, max_length):
"""ラベルをインデックスにエンコードし、パディングを行う関数"""
encoded_labels = []
for sentence_labels in labels:
# 各ラベルをインデックスに変換
encoded_sentence_labels = [label_to_index[label] for label in sentence_labels]
# パディングを行い、ラベルの長さを揃える
encoded_sentence_labels += [label_to_index["O"]] * (max_length - len(encoded_sentence_labels))
# 最終的に同じ長さになるように調整
encoded_labels.append(encoded_sentence_labels)
# NumPy配列に変換
return np.array(encoded_labels)
# 2. モデルの定義(LSTMベース)
def build_lstm_ner_model(vocab_size, label_count):
"""LSTMベースの固有表現認識モデルの構築"""
model = models.Sequential([
layers.Embedding(input_dim=vocab_size, output_dim=64, input_length=50),
layers.Bidirectional(layers.LSTM(64, return_sequences=True)),
layers.TimeDistributed(layers.Dense(64, activation='relu')),
layers.TimeDistributed(layers.Dense(label_count, activation='softmax'))
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
return model
# 3. BERTベースの固有表現認識モデル
def build_bert_ner_model(label_count):
"""BERTベースの固有表現認識モデルの構築"""
bert_model = TFBertModel.from_pretrained("bert-base-uncased")
input_ids = layers.Input(shape=(50,), dtype=tf.int32, name='input_ids')
attention_mask = layers.Input(shape=(50,), dtype=tf.int32, name='attention_mask')
bert_output = bert_model(input_ids, attention_mask=attention_mask)[0]
lstm_output = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(bert_output)
ner_output = layers.TimeDistributed(layers.Dense(label_count, activation='softmax'))(lstm_output)
model = models.Model(inputs=[input_ids, attention_mask], outputs=[ner_output])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
return model
# 4. 評価関数の実装
def evaluate_model(model, x_test, y_test, index_to_label):
"""モデルの評価と分類レポートの表示"""
y_pred = model.predict(x_test)
y_pred_labels = np.argmax(y_pred, axis=-1)
y_test_flat = y_test.flatten()
y_pred_flat = y_pred_labels.flatten()
y_test_labels = [index_to_label[idx] for idx in y_test_flat]
y_pred_labels = [index_to_label[idx] for idx in y_pred_flat]
report = classification_report(y_test_labels, y_pred_labels)
print("\n[分類レポート]\n", report)
# 5. データのトークナイズと前処理
def tokenize_and_preprocess(sentences, labels, tokenizer, max_length, label_to_index):
"""文章のトークナイズと前処理"""
input_ids, attention_masks, label_ids = [], [], []
for sentence, sentence_labels in zip(sentences, labels):
encoded_dict = tokenizer.encode_plus(
sentence,
add_special_tokens=True,
max_length=max_length,
padding='max_length',
truncation=True,
return_attention_mask=True,
return_tensors='tf'
)
# トークンIDとAttention Maskの取得
input_ids.append(encoded_dict['input_ids'].numpy().flatten())
attention_masks.append(encoded_dict['attention_mask'].numpy().flatten())
# ラベルのエンコードとパディング
label_ids_padded = [label_to_index[label] for label in sentence_labels] + [label_to_index["O"]] * (max_length - len(sentence_labels))
label_ids.append(label_ids_padded)
return np.array(input_ids), np.array(attention_masks), np.array(label_ids)
# 6. メイン関数: 各機能の統合実行
def main():
# 固有表現ラベルのマッピング
label_to_index = {"O": 0, "B-PER": 1, "I-PER": 2, "B-LOC": 3, "I-LOC": 4, "B-ORG": 5, "I-ORG": 6}
index_to_label = {v: k for k, v in label_to_index.items()}
# データセットの準備
sentences, labels = prepare_dataset()
max_length = 50 # ラベルおよびトークンの最大長を指定
encoded_labels = encode_labels(labels, label_to_index, max_length) # パディングを考慮したラベルエンコード
# 文章のトークナイズ(LSTM用)
tokenizer = preprocessing.text.Tokenizer()
tokenizer.fit_on_texts(sentences)
vocab_size = len(tokenizer.word_index) + 1 # 単語インデックスのサイズ
x_data = preprocessing.sequence.pad_sequences(tokenizer.texts_to_sequences(sentences), maxlen=max_length)
y_data = preprocessing.sequence.pad_sequences(encoded_labels, maxlen=max_length)
# データセットの分割
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.2, random_state=42)
# 1. LSTMモデルの定義、学習、評価
lstm_model = build_lstm_ner_model(vocab_size, len(label_to_index))
lstm_model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.1)
evaluate_model(lstm_model, x_test, y_test, index_to_label)
# BERT用トークナイザーの設定
bert_tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
# 文章とラベルの前処理(BERT用)
x_input_ids, x_attention_masks, y_labels = tokenize_and_preprocess(sentences, labels, bert_tokenizer, max_length, label_to_index)
# データセットの分割
x_train_ids, x_test_ids, x_train_masks, x_test_masks, y_train_bert, y_test_bert = train_test_split(
x_input_ids, x_attention_masks, y_labels, test_size=0.2, random_state=42
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers, models, preprocessing, callbacks
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from transformers import BertTokenizer, TFBertModel
import matplotlib.pyplot as plt
# 1. データセットの準備
def prepare_dataset():
"""サンプルデータセットの作成"""
sentences = [
"John lives in New York",
"Mary works at Google",
"Berlin is the capital of Germany",
"Elon Musk is the CEO of Tesla",
"Paris is known for the Eiffel Tower"
]
labels = [
["B-PER", "O", "O", "B-LOC", "I-LOC"], # John, New York (Person, Location)
["B-PER", "O", "O", "B-ORG"], # Mary, Google (Person, Organization)
["B-LOC", "O", "O", "O", "B-LOC"], # Berlin, Germany (Location)
["B-PER", "I-PER", "O", "O", "O", "B-ORG"], # Elon Musk, Tesla (Person, Organization)
["B-LOC", "O", "O", "O", "B-LOC", "I-LOC"] # Paris, Eiffel Tower (Location)
]
return sentences, labels
# 固有表現ラベルをインデックスに変換し、パディング
def encode_labels(labels, label_to_index, max_length):
"""ラベルをインデックスにエンコードし、パディングを行う関数"""
encoded_labels = []
for sentence_labels in labels:
encoded_sentence_labels = [label_to_index[label] for label in sentence_labels]
encoded_sentence_labels += [label_to_index["O"]] * (max_length - len(encoded_sentence_labels))
encoded_labels.append(encoded_sentence_labels)
return np.array(encoded_labels)
# 2. モデルの定義(LSTMベース)
def build_lstm_ner_model(vocab_size, label_count):
"""LSTMベースの固有表現認識モデルの構築"""
model = models.Sequential([
layers.Embedding(input_dim=vocab_size, output_dim=64, input_length=50),
layers.Bidirectional(layers.LSTM(64, return_sequences=True)),
layers.TimeDistributed(layers.Dense(64, activation='relu')),
layers.TimeDistributed(layers.Dense(label_count, activation='softmax'))
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
return model
# 3. BERTベースの固有表現認識モデル
def build_bert_ner_model(label_count):
"""BERTベースの固有表現認識モデルの構築"""
bert_model = TFBertModel.from_pretrained("bert-base-uncased")
input_ids = layers.Input(shape=(50,), dtype=tf.int32, name='input_ids')
attention_mask = layers.Input(shape=(50,), dtype=tf.int32, name='attention_mask')
bert_output = bert_model(input_ids, attention_mask=attention_mask)[0]
lstm_output = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(bert_output)
ner_output = layers.TimeDistributed(layers.Dense(label_count, activation='softmax'))(lstm_output)
model = models.Model(inputs=[input_ids, attention_mask], outputs=[ner_output])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.summary()
return model
# 4. 評価関数の実装
def evaluate_model(model, x_test, y_test, index_to_label):
"""モデルの評価と分類レポートの表示"""
y_pred = model.predict(x_test)
y_pred_labels = np.argmax(y_pred, axis=-1)
y_test_flat = y_test.flatten()
y_pred_flat = y_pred_labels.flatten()
y_test_labels = [index_to_label[idx] for idx in y_test_flat]
y_pred_labels = [index_to_label[idx] for idx in y_pred_flat]
report = classification_report(y_test_labels, y_pred_labels)
print("\n[分類レポート]\n", report)
# 5. データのトークナイズと前処理
def tokenize_and_preprocess(sentences, labels, tokenizer, max_length, label_to_index):
"""文章のトークナイズと前処理"""
input_ids, attention_masks, label_ids = [], [], []
for sentence, sentence_labels in zip(sentences, labels):
encoded_dict = tokenizer.encode_plus(
sentence,
add_special_tokens=True,
max_length=max_length,
padding='max_length',
truncation=True,
return_attention_mask=True,
return_tensors='tf'
)
input_ids.append(encoded_dict['input_ids'].numpy().flatten())
attention_masks.append(encoded_dict['attention_mask'].numpy().flatten())
label_ids_padded = [label_to_index[label] for label in sentence_labels] + [label_to_index["O"]] * (max_length - len(sentence_labels))
label_ids.append(label_ids_padded)
return np.array(input_ids), np.array(attention_masks), np.array(label_ids)
# 6. メイン関数: 各機能の統合実行
def main():
# 固有表現ラベルのマッピング
label_to_index = {"O": 0, "B-PER": 1, "I-PER": 2, "B-LOC": 3, "I-LOC": 4, "B-ORG": 5, "I-ORG": 6}
index_to_label = {v: k for k, v in label_to_index.items()}
# データセットの準備
sentences, labels = prepare_dataset()
max_length = 50 # ラベルおよびトークンの最大長を指定
encoded_labels = encode_labels(labels, label_to_index, max_length)
# 文章のトークナイズ(LSTM用)
tokenizer = preprocessing.text.Tokenizer()
tokenizer.fit_on_texts(sentences)
vocab_size = len(tokenizer.word_index) + 1
x_data = preprocessing.sequence.pad_sequences(tokenizer.texts_to_sequences(sentences), maxlen=max_length)
y_data = encoded_labels[:len(x_data)] # データセットの長さを一致させる
print(f"Xのサンプル数: {x_data.shape[0]}, Yのサンプル数: {y_data.shape[0]}")
# データセットの分割
x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.2, random_state=42)
# 1. LSTMモデルの定義、学習、評価
lstm_model = build_lstm_ner_model(vocab_size, len(label_to_index))
lstm_model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.1)
evaluate_model(lstm_model, x_test, y_test, index_to_label)
# BERT用トークナイザーの設定
bert_tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
# 文章とラベルの前処理(BERT用)
x_input_ids, x_attention_masks, y_labels = tokenize_and_preprocess(sentences, labels, bert_tokenizer, max_length, label_to_index)
# データセットの分割
x_train_ids, x_test_ids, x_train_masks, x_test_masks, y_train_bert, y_test_bert = train_test_split(
x_input_ids, x_attention_masks, y_labels, test_size=0.2, random_state=42
)
# 2. BERT + BiLSTM モデルの定義、学習、評価
bert_model = build_bert_ner_model(len(label_to_index))
bert_model.fit(
[x_train_ids, x_train_masks], y_train_bert,
epochs=3, batch_size=8, validation_split=0.1,
callbacks=[callbacks.EarlyStopping(monitor='val_loss', patience=3)]
)
evaluate_model(bert_model, [x_test_ids, x_test_masks], y_test_bert, index_to_label)
# メイン関数の呼び出し
if __name__ == "__main__":
main()
# 必要なライブラリのインポート
from google.cloud import language_v1
import os
# サービスアカウントキーのパスを設定
# 例: 'service-account-file.json' を実際のファイル名に置き換えます。
# Google Colabなどの環境で実行する場合は、ファイルをアップロードしてパスを設定してください。
service_account_path = 'service-account-file.json'
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = service_account_path
# Google Cloud Natural Language APIを使用してテキストの感情分析を行う関数
def analyze_text_sentiment(text_content):
"""
テキストの感情分析を行う関数
:param text_content: 感情分析を行いたいテキスト(例: "I love programming!")
"""
try:
# Natural Language API のクライアントを作成
client = language_v1.LanguageServiceClient()
# テキストをDocument型に変換
document = language_v1.Document(content=text_content, type_=language_v1.Document.Type.PLAIN_TEXT)
# 感情分析を実行
sentiment = client.analyze_sentiment(request={"document": document}).document_sentiment
# 結果を表示
print(f"Text: {text_content}")
print(f"Sentiment Score: {sentiment.score}, Sentiment Magnitude: {sentiment.magnitude}")
except Exception as e:
print(f"An error occurred: {e}")
print(f"Please ensure that the service account file exists and the path is set correctly.")
# Google Colabで実行する場合、ファイルをアップロードしてファイルパスを設定
# アップロードされたファイル名を設定する
if not os.path.exists(service_account_path):
from google.colab import files
uploaded = files.upload() # .jsonファイルをアップロード
service_account_path = list(uploaded.keys())[0] # アップロードしたファイル名を取得
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = service_account_path
# テスト用テキスト
text = "I am so happy and excited to learn new things!"
# 感情分析を実行
analyze_text_sentiment(text)