ステップ 1: 必要なライブラリをインポートする
```python
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import precision_score
from sklearn.model_selection import train_test_split
```
ステップ 2: データを準備する
2 つのカテゴリ (ポジティブとネガティブ) を含むサンプル データセットと、各カテゴリのテキストの例を使用します。Pandas ライブラリを使用してデータを読み取り、いくつかのサンプル データを確認します。
```python
#データの読み取り
data = pd.read_csv('data.csv')
# 最初の 5 つのテキスト データを表示
print(data.head())
```
ステップ 3: 特徴ベクトルとターゲット変数を作成する
モデルをトレーニングするには、テキストを数値に変換する必要があります。CountVectorizer を使用してテキストを数値特徴ベクトルに変換します。また、ターゲット変数 (つまり、カテゴリラベル) を数値に変換する必要があります。
```python
#CountVectorizer を使用して特徴ベクトルを作成します
Vectorizer = CountVectorizer(stop_words='english')
X = Vectorizer.fit_transform(data.text)
#対象変数を数値に変換
y = pd.factorize(data.label)[0]
``
ステップ 4: データセットを分割する
トレーニング中にモデルを評価するには、データセットをトレーニング セットとテスト セットに分割する必要があります。この機能を実現するには、train_test_split 関数を使用します。
```python
#データセットをトレーニングセットとテストセットに分割します
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``
`
ステップ 5: モデルをトレーニングする
私たちのモデルは MultinomialNB を使用してトレーニングできます。MultinomialNB は、テキスト分類に一般的に使用される単純なベイズ アルゴリズムです。
```python
#トレーニングモデル
clf = MultinomialNB()
clf.fit(X_train, y_train)
```
ステップ 6: モデルを評価する
モデルの精度を評価するには、accuracy_score を使用します。
```python
#评估モデル
y_pred = clf.predict(X_test)
精度 = precision_score(y_test, y_pred)
print("精度:", 精度)
```
完全なコードは次のようになります。
```python
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import precision_score
from sklearn.model_selection import train_test_split
#データ読み込み
data = pd.read_csv('data.csv')
#最初の 5 つのテキスト データを表示します
print(data.head())
#CountVectorizer を使用して特徴ベクトルを作成します
Vectorizer = CountVectorizer(stop_words='english')
X = Vectorizer.fit_transform(data.text)
#対象変数を数値に変換
y = pd.factorize(data.label)[0]
#データセットをトレーニングセットとテストセットに分割します
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
#トレーニングモデル
clf = MultinomialNB()
clf.fit(X_train, y_train)
#评估モデル
y_pred = clf.predict(X_test)
精度 = precision_score(y_test, y_pred)
print("精度:", 精度)
```