Esempio n. 1
0
x_data = []
y_data = []


# 디렉터리 내부의 파일 목록 불러와 데이터셋에 추가하기 --- (*1)
def read_files(path, label, n_limit=None):
    limit_str = '' if n_limit is None else f'(Limit to {n_limit} samples)'
    print(f">>> read_files from {path} {limit_str}")
    files = glob.glob(path + "/*.txt")[:n_limit]
    for f in files:
        if os.path.basename(f) == 'LICENSE.txt': continue
        tfidf.add_file(f)
        y_data.append(label)


# 기사를 넣은 디렉터리 읽어 들이기 --- ( ※ 2)
text_labels = sorted(glob.glob(sys.argv[1] +
                               '/*'))  # path to each label's directory
n_limit = int(sys.argv[2]) if len(
    sys.argv) == 3 else None  # number of samples per class (limitation)
for idx, path in enumerate(text_labels):
    read_files(path=path, label=idx, n_limit=n_limit)

# TF-IDF 벡터로 변환하기 --- (*3)
x_data = tfidf.calc_files()

# 저장하기 --- (*4)
os.makedirs('source_output/', exist_ok=True)
pickle.dump([y_data, x_data], open('source_output/news_category.pickle', 'wb'))
tfidf.save_dic('source_output/news_category_tdidf.dic')
print('ok')
Esempio n. 2
0
import os, glob, pickle
import tfidf

# 변수 초기화
y = []
x = []

# 디렉터리 내부의 파일 목록 전체에 대해 처리하기 --- (*1)
def read_files(path, label):
    print("read_files=", path)
    files = glob.glob(path + "/*.txt")
    for f in files:
        if os.path.basename(f) == 'LICENSE.txt': continue
        tfidf.add_file(f)
        y.append(label)

# 기사를 넣은 디렉터리 읽어 들이기 --- ( ※ 2)
read_files('text/100', 0)
read_files('text/101', 1)
read_files('text/103', 2)
read_files('text/105', 3)


# TF-IDF 벡터로 변환하기 --- (*3)
x = tfidf.calc_files()

# 저장하기 --- (*4)
pickle.dump([y, x], open('text/genre.pickle', 'wb'))
tfidf.save_dic('text/genre-tdidf.dic')
print('ok')
#カテゴリごとに分かれたディレクトリ内にあるデータに対してラベル付けを行う
read_files('data/text/sports-watch', 0)
read_files('data/text/it-life-hack', 1)
read_files('data/text/movie-enter', 2)
read_files('data/text/international', 3)

#TFIDFでそれぞれの単語をベクトルに変換(辞書更新も行う)
x = tfidf.calc_files()

#pickleファイルを格納するフォルダディレクトリ
dir_for_pkls = 'data/pkl/'
#上記のディレクリを再帰的に作成する
os.makedirs(dir_for_pkls, exist_ok=True)
#データ格納用pickleファイル
pkl_for_data = "data.pkl"
#入力値とラベルを追加したリストを上記のpickleファイルに格納(バイナリ形式)
pickle.dump([y, x], open(dir_for_pkls + pkl_for_data, 'wb'))
if os.path.exists(dir_for_pkls + pkl_for_data):
    print('データpickleファイルの保存完了')
else:
    print('データpickleファイルの保存に失敗しました')

#辞書格納用pickleファイル
pkl_for_dic = 'dic.pkl'
#[word_dic, dt_dic, files]をpickleファイルに格納(バイナリ形式)
tfidf.save_dic(dir_for_pkls + pkl_for_dic)
if os.path.exists(dir_for_pkls + pkl_for_dic):
    print('辞書pickleファイルの保存完了')
else:
    print('辞書pickleファイルの保存に失敗しました')
Esempio n. 4
0
bar_pair2.close()

# ヘッダー作成
keys = list(tfidf.word_dic.keys())
keys.remove("_id")
header = keys.copy()
extend_features = ["LENGTH", "TOKENLENGTH"]
header.extend(extend_features)
header.extend(keys.copy())
header.extend(extend_features)
header.append("LABEL")

# 非盗作ペアのみシャッフル
perm = np.random.permutation(len(nonplag_code_vec))
nonplag_code_vec = np.array(nonplag_code_vec)[perm]

# CSVに出力
print("CSV作成中...")
csv_data = np.concatenate([plag_code_vec, nonplag_code_vec])
with open("./tfidf.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerow(header)
    writer.writerows(csv_data.tolist())

with open("./std_mean.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerows([[len_mean, len_std], [tok_mean, tok_std]])

# dicファイル作成
tfidf.save_dic("./tfidf.dic")
Esempio n. 5
0
import os, glob, pickle
import tfidf

y = []
x = []

def read_files(path, label):
    print("read_files=", path)
    files = glob.glob(path + "/*.txt")
    for f in files:
        if os.path.basename(f) == 'LICENSE.txt': continue
        tfidf.add_file(f)
        y.append(label)

read_files('./ok', 0)
read_files('./spam', 1)


x = tfidf.calc_files()

pickle.dump([y, x], open('./spam.pickle', 'wb'))
tfidf.save_dic('./spam-tdidf.dic')
print('ok')

print(len(x))
print(len(y))