-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprep_data.py
More file actions
64 lines (47 loc) · 2 KB
/
prep_data.py
File metadata and controls
64 lines (47 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
'''
このクラスでは名前のCSVファイルを読み込み、CountVectorizerで
BagOfWordsを用いて名前データをベクトル化し、機械学習モデルが
使えるように加工する。
必要なパッケージは:
- os
- pandas
- numpy
- scikit learn
'''
import os
import pickle
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
class nameToVector(object):
def __init__(self):
# このPythonファイルがあるフォルダのパス
self.cur_PATH = os.path.dirname(os.path.realpath(__file__))
self.PATH = os.path.join(self.cur_PATH, 'data')
print(self.PATH)
def load_data(self, japanese_name, foreign_name):
# 日本、外国人の名前のファイル名
jp_fname = japanese_name
f_fname = foreign_name
# データを読み込む
jp = pd.read_csv(os.path.join(self.PATH, jp_fname))
fr = pd.read_csv(os.path.join(self.PATH, f_fname))
# ラベルを追加
jp['label'] = int(1)
fr['label'] = int(0)
self.data = pd.concat([jp, fr], axis=0)
def get_name_vector(self):
# 読んだCSVをベクトル化, Vectorizerも保つ
# SklearnのCountVectorizerを利用し、単語(姓、名)の頻度に基づきベクトル化
vectorizer = CountVectorizer()
self.name_vec = vectorizer.fit_transform(self.data['name'])
self.y = self.data['label'].values
print('shape of the vectorized data is: ', self.name_vec.shape)
def load_name_vector(self, file_name):
# 保存されているCountVectorを読み込む??
self.name_vec = pickle.load(open(os.path.join(self.cur_PATH, file_name), 'rb'))
def transform(self, name):
# 新しい名前をStringでうけとり、ベクトル化
# name: 名前のStringを含むPandasのSeriesかPythonリスト
return self.name_vec.transform(name)