10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

関連のある文章を見つける

Last updated at Posted at 2016-03-05

実践 機械学習
の3章まで来たのでメモ代わりに書いておこうかと思います。
3章では関連のある文章を見つけます。
ちなみにこの本、章が進むに連れて訓練用データが取得しにくくなります。
初版なので仕方ないですが、Twitterの投稿取得とかもう鬼畜レベルに難しいです。(データ集めが)Twitterは規制が厳しいので大変です。

具体例を示すと、Yahoo知恵袋,プログラミング専門のQ&Aサイトteratail
などに投稿された文章データを取得し、それらをグループ分けします。
文章から抽出された特徴ベクトルをグループ分けする手法は多く存在しそれらは下記の2つの手法どちらかに該当します。
/ フラットクラスタリング
/ 階層的クラスタリング
この本の3章で扱っているクラスタリング手法は前者のフラットクラスタリングであります。
両者ともwikipediaでは該当する情報はありませんでした。マニアックな手法なのでしょうか。

今回利用したデータですが、下記リンクからダウンロードできます。(登録必須)
http://mlcomp.org/datasets/379
日本語でもやってみたかったのですが、MeCabの関係で諦めました(インストール出来なかった)

下のコードで求めているのは下記文章に類似しているものです。
Disk drive problems. Hi, I have a problem with my hard disk.
After 1 year it is working only sporadically now.
I tried to format it, but now it doesn't boot any more.
Any ideas? Thanks.
結果ですが私の環境だときちんと動作しました。
下記写真が近いようです。

スクリーンショット 2016-03-05 11.54.35.png

ch02.py
import sklearn.datasets
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
import scipy as sp
import sys
import nltk.stem

MLCOMP_DIR = "" #ダウンロードしたデータのパス

groups = ['comp.graphics',
		'comp.os.ms-windows.misc',
		'comp.sys.ibm.pc.hardware',
		'comp.sys.mac.hardware',
		'comp.windows.x',
		'sci.space']

test_data = sklearn.datasets.load_mlcomp("20news-18828", "test", mlcomp_root=MLCOMP_DIR)
train_data = sklearn.datasets.load_mlcomp("20news-18828", "train", mlcomp_root=MLCOMP_DIR, categories=groups)

english_stemmer = nltk.stem.SnowballStemmer('english')

class StemmedTfidfVectorizer(TfidfVectorizer):

    def build_analyzer(self):
        analyzer = super(TfidfVectorizer, self).build_analyzer()
        return lambda doc: (
        	english_stemmer.stem(w) for w in analyzer(doc))

vectorizer = StemmedTfidfVectorizer(min_df=10, max_df=0.5,
									stop_words='english', decode_error='ignore')
vectorized = vectorizer.fit_transform(train_data.data)
num_samples, num_features = vectorized.shape
print("#samples: %d, #features: %d" % (num_samples, num_features))

num_clusters = 50
km = KMeans(n_clusters=num_clusters, init="random", n_init=1, verbose=1)
km.fit(vectorized)
print(km.labels_)
print(km.labels_.shape)

new_post = """Disk drive problems. Hi, I have a problem with my hard disk.
After 1 year it is working only sporadically now.
I tried to format it, but now it doesn't boot any more.
Any ideas? Thanks."""
new_post_vec = vectorizer.transform([new_post])
new_post_label = km.predict(new_post_vec)[0]

similar_indices = (km.labels_==new_post_label).nonzero()[0]
similar = []
for i in similar_indices:
	dist = sp.linalg.norm((new_post_vec - vectorized[i]).toarray())
	similar.append((dist, train_data.data[i]))

similar = sorted(similar)
print(len(similar))

show_at_1 = similar[0]
show_at_2 = similar[len(similar)/2]
show_at_3 = similar[-1]
print(show_at_1)
print(show_at_2)
print(show_at_3)
10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?