u++の備忘録

言語処理100本ノック 2020「57. 特徴量の重みの確認」

問題文

nlp100.github.io

問題の概要

ロジスティック回帰を用いた場合は「.coef_」で特徴量の重みを確認できます。今回は値の絶対値に興味があるので、事前にソートした上で上位・下位10個の特徴量を出力します。

import joblib


clf = joblib.load('ch06/model.joblib')
vocabulary_ = joblib.load('ch06/vocabulary_.joblib')
coefs = clf.coef_

for c in coefs:
    d = dict(zip(vocabulary_, c))
    d_top = sorted(d.items(), key=lambda x: abs(x[1]), reverse=True)[:10]
    print(d_top)
    d_bottom = sorted(d.items(), key=lambda x: abs(x[1]), reverse=False)[:10]
    print(d_bottom)

言語処理100本ノック 2020「56. 適合率,再現率,F1スコアの計測」

問題文

nlp100.github.io

問題の概要

適合率,再現率,F1スコアはそれぞれ「precision_score()」「recall_score()」「f1_score()」で計算できます。「average」には「'micro'」「'macro'」などが指定可能*1です。

import pandas as pd
import joblib
from sklearn.metrics import recall_score, precision_score, f1_score


X_train = pd.read_table('ch06/train.feature.txt', header=None)
X_test = pd.read_table('ch06/test.feature.txt', header=None)
y_train = pd.read_table('ch06/train.txt', header=None)[1]
y_test = pd.read_table('ch06/test.txt', header=None)[1]

clf = joblib.load('ch06/model.joblib')
y_pred = clf.predict(X_test)

print(f'test recall of None: {recall_score(y_test, y_pred, average=None)}')
print(f'test recall of micro: {recall_score(y_test, y_pred, average="micro")}')
print(f'test recall of macro: {recall_score(y_test, y_pred, average="macro")}')
print(f'test precision of None: {precision_score(y_test, y_pred, average=None)}')
print(f'test precision of micro: {precision_score(y_test, y_pred, average="micro")}')
print(f'test precision of macro: {precision_score(y_test, y_pred, average="macro")}')
print(f'test f1 of None: {f1_score(y_test, y_pred, average=None)}')
print(f'test f1 of micro: {f1_score(y_test, y_pred, average="micro")}')
print(f'test f1 of macro: {f1_score(y_test, y_pred, average="macro")}')

言語処理100本ノック 2020「55. 混同行列の作成」

問題文

nlp100.github.io

問題の概要

混同行列は「confusion_matrix()」で作成できます。

import pandas as pd
import joblib
from sklearn.metrics import confusion_matrix


X_train = pd.read_table('ch06/train.feature.txt', header=None)
X_test = pd.read_table('ch06/test.feature.txt', header=None)
y_train = pd.read_table('ch06/train.txt', header=None)[1]
y_test = pd.read_table('ch06/test.txt', header=None)[1]

clf = joblib.load('ch06/model.joblib')

print(f'train confusion matrix:\n {confusion_matrix(y_train, clf.predict(X_train))}')
print(f'test confusion matrix:\n {confusion_matrix(y_test, clf.predict(X_test))}')

言語処理100本ノック 2020「54. 正解率の計測」

問題文

nlp100.github.io

問題の概要

正答率は「accuracy_score()」で計算できます。

import pandas as pd
import joblib
from sklearn.metrics import accuracy_score


X_train = pd.read_table('ch06/train.feature.txt', header=None)
X_test = pd.read_table('ch06/test.feature.txt', header=None)
y_train = pd.read_table('ch06/train.txt', header=None)[1]
y_test = pd.read_table('ch06/test.txt', header=None)[1]

clf = joblib.load('ch06/model.joblib')

print(f'train acc: {accuracy_score(y_train, clf.predict(X_train))}')
print(f'test acc: {accuracy_score(y_test, clf.predict(X_test))}')

言語処理100本ノック 2020「53. 予測」

問題文

nlp100.github.io

問題の概要

学習を終えたモデルは、予測値が未知の特徴量(X_test)を与えて予測させることができます。

import pandas as pd
from sklearn.linear_model import LogisticRegression


X_train = pd.read_table('ch06/train.feature.txt', header=None)
y_train = pd.read_table('ch06/train.txt', header=None)[1]

clf = LogisticRegression(penalty='l2', solver='sag', random_state=0)
clf.fit(X_train, y_train)
y_train = clf.predict(X_train)

言語処理100本ノック 2020「52. 学習」

問題文

nlp100.github.io

問題の概要

用意した特徴量と予測の対象のペアから、機械学習アルゴリズムを用いて予測器を学習させましょう。

f:id:upura:20200726000350p:plain

import pandas as pd
import joblib
from sklearn.linear_model import LogisticRegression


X_train = pd.read_table('ch06/train.feature.txt', header=None)
y_train = pd.read_table('ch06/train.txt', header=None)[1]

clf = LogisticRegression(penalty='l2', solver='sag', random_state=0)
clf.fit(X_train, y_train)
joblib.dump(clf, 'ch06/model.joblib')

言語処理100本ノック 2020「51. 特徴量抽出」

問題文

nlp100.github.io

問題の概要

カテゴリ分類に有用そうな特徴量を抽出します。ここでは、問題文の指示通りの最低限の特徴量を作ります。sklearnに用意されている「CountVectorizer()」が利用可能です。

記事の見出しを単語列に変換したものが最低限のベースラインとなるであろう.

データセット内に「TMP」という一時的なカラムを作成し、X_train・X_valid・X_testを結合しておくことで、特徴量抽出の処理を一度で済ましています。

import joblib
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer


X_train = pd.read_table('ch06/train.txt', header=None)
X_valid = pd.read_table('ch06/valid.txt', header=None)
X_test = pd.read_table('ch06/test.txt', header=None)
use_cols = ['TITLE', 'CATEGORY']
X_train.columns = use_cols
X_valid.columns = use_cols
X_test.columns = use_cols
X_train['TMP'] = 'train'
X_valid['TMP'] = 'valid'
X_test['TMP'] = 'test'

data = pd.concat([X_train, X_valid, X_test]).reset_index(drop=True)
vectorizer = CountVectorizer(token_pattern=u'(?u)\\b\\w+\\b')
bag = vectorizer.fit_transform(data['TITLE'])
data = pd.concat([data, pd.DataFrame(bag.toarray())], axis=1)

joblib.dump(vectorizer.vocabulary_, 'ch06/vocabulary_.joblib')

X_train = data.query('TMP=="train"').drop(use_cols + ['TMP'], axis=1)
X_valid = data.query('TMP=="valid"').drop(use_cols + ['TMP'], axis=1)
X_test = data.query('TMP=="test"').drop(use_cols + ['TMP'], axis=1)

X_train.to_csv('ch06/train.feature.txt', sep='\t', index=False, header=None)
X_valid.to_csv('ch06/valid.feature.txt', sep='\t', index=False, header=None)
X_test.to_csv('ch06/test.feature.txt', sep='\t', index=False, header=None)