다른 기사를 주제로 분류하는 Keras 모델을 작성하려고합니다. 각 기사에는 하나의 주제 만 있습니다. 나는 사용자 정의 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
?
편집 : 내가 좋아하는 훈련 데이터를로드하는 과정 변경하여 작업 모델의 훈련있어 : 그래서
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')
을,이를 사용하여 주어진 글에서 레이블을 예측할 수있는 방법 ? :