2017-09-05 10 views
0

異なる記事をトピックに分類するためにKerasモデルを構築しようとしています。各記事には1つのトピックしかありません。 csvファイルからのデータがまだあることを処理していなかったので、私は、このデータセットのための私のモデルを訓練しようとしているが、残念ながら、私はエラーを取得するKerasテキスト分類csvからのカスタムデータセット

"topic1","article1" 
"topic2","article2" 

:私は、次のような構造を持つカスタムcsvファイルを持っていますベクター。

これは私のコードです:

from __future__ import print_function 
import csv 
import numpy as np 
import keras 
import os 
from keras.models import Sequential 
from keras.layers import Dense, Dropout, Activation 
from keras.preprocessing.text import Tokenizer 

max_words = 1000 
batch_size = 32 
epochs = 5 
model_file_name = 'model.h5' 


def load_data(word_max, test_split): 
    xs = [] 
    labels = [] 
    counter = 0 
    with open('data.csv', 'r') as f: 
     reader = csv.reader(f) 
     for line in reader: 
      if counter > word_max: 
       break 
      xs.append(line[1]) 
      labels.append(line[0]) 
      counter += 1 
    idx = int(len(xs) * (1 - test_split)) 
    train_x, train_y = np.array(xs[:idx]), np.array(labels[:idx]) 
    test_x, test_y = np.array(xs[idx:]), np.array(labels[idx:]) 
    return (train_x, train_y), (test_x, test_y) 


print('Loading data...') 
(x_train, y_train), (x_test, y_test) = load_data(max_words, 0.3) 

print(len(x_train), 'train sequences') 
print(len(x_test), 'test sequences') 

num_classes = np.max(y_train) + 1 
print(num_classes, 'classes') 

print('Vectorizing sequence data...') 
tokenizer = Tokenizer(num_words=max_words) 
x_train = tokenizer.sequences_to_matrix(x_train, mode='binary') 
x_test = tokenizer.sequences_to_matrix(x_test, mode='binary') 
print('x_train shape:', x_train.shape) 
print('x_test shape:', x_test.shape) 

print('Convert class vector to binary class matrix ' 
     '(for use with categorical_crossentropy)') 
y_train = keras.utils.to_categorical(y_train, num_classes) 
y_test = keras.utils.to_categorical(y_test, num_classes) 
print('y_train shape:', y_train.shape) 
print('y_test shape:', y_test.shape) 

if os.path.isfile(model_file_name): 
    model = keras.models.load_model(model_file_name) 
else: 
    print('Building model...') 
    model = Sequential() 
    model.add(Dense(512, input_shape=(max_words,))) 
    model.add(Activation('relu')) 
    model.add(Dropout(0.35)) 
    model.add(Dense(num_classes)) 
    model.add(Activation('softmax')) 

    model.compile(loss='categorical_crossentropy', 
        optimizer='adam', 
        metrics=['accuracy']) 

    history = model.fit(x_train, y_train, 
         batch_size=batch_size, 
         epochs=epochs, 
         verbose=1, 
         validation_split=0.1) 
    score = model.evaluate(x_test, y_test, 
          batch_size=batch_size, verbose=1) 
    print('Test score:', score[0]) 
    print('Test accuracy:', score[1]) 
    model.save(model_file_name) 

どのように私は私のモデルを訓練するために正しく自分のデータを読み込むことができますか?また、テキストのトピックを予測するにはどうすればmodel.predictとなりますか?

EDIT: は、私のようなトレーニングデータをロードするプロセス変更することで、作業モデルの訓練持っている:だから

print('Loading data...') 
(x_train, y_train), (x_test, y_test) = load_data(max_words, 0.3) 

tokenizer = Tokenizer(num_words=max_words) 
tokenizer.fit_on_texts(x_train) 
x_train = tokenizer.texts_to_sequences(x_train) 
tokenizer.fit_on_texts(y_train) 
y_train = tokenizer.texts_to_sequences(y_train) 
tokenizer.fit_on_texts(x_test) 
x_test = tokenizer.texts_to_sequences(x_test) 
tokenizer.fit_on_texts(y_test) 
y_test = tokenizer.texts_to_sequences(y_test) 

print(len(x_train), 'train sequences') 
print(len(x_test), 'test sequences') 

を、私はこれを使用して、特定の記事からラベルを予測する方法?:

model = keras.models.load_model(model_file_name) 
to_predict = np.array(['The sun is shining.']) 
# Predict label from example article 
label = model.predict(...) 
print(label) 

答えて

1

記事をnumpy配列に直接変換できませんでした。同じトークナイザを使用して記事をnumpy配列に変換する必要があります。 (あなたは、ソフトマックス関数を使用するため)

array = tokenizer.texts_to_sequences([title]) # the tokenizer must be same with the training tokenizer 
array = np.asanyarray(array) 
array = sequence.pad_sequences(array, maxlen=max_words, padding='post', truncating='post') 
array = np.asarray(array) 
result = model.predict(array) 

そして、結果は、確率のベクトルとなり、[0.3,0.7]のように、各要素は、対応するトピックに確率を表します。確率が最も高いトピックが予測になります。

関連する問題