我试图让LSTM在Keras工作,但即使在第一个时代之后,准确性似乎太高(90%)而我担心没有正确训练,我从这篇文章中提出了一些想法:
https://machinelearningmastery.com/text-generation-lstm-recurrent-neural-networks-python-keras/
这是我的代码:
import numpy
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from keras.preprocessing.sequence import pad_sequences
from pandas import read_csv
import simplejson
numpy.random.seed(7)
dataset = read_csv("mydataset.csv", delimiter=",", quotechar='"').values
char_to_int = dict((c, i) for i, c in enumerate(dataset[:,1]))
int_to_char = dict((i, c) for i, c in enumerate(dataset[:,1]))
f = open('char_to_int_v2.txt', 'w')
simplejson.dump(char_to_int, f)
f.close()
f = open('int_to_char_v2.txt', 'w')
simplejson.dump(int_to_char, f)
f.close()
seq_length = 1
max_len = 5
dataX = []
dataY = []
for i in range(0, len(dataset) - seq_length, 1):
start = numpy.random.randint(len(dataset)-2)
end = numpy.random.randint(start, min(start+max_len,len(dataset)-1))
sequence_in = dataset[start:end+1]
sequence_out = dataset[end + 1]
dataX.append([[char[0], char_to_int[char[1]], char[2]] for char in sequence_in])
dataY.append([sequence_out[0], char_to_int[sequence_out[1]], sequence_out[2]])
X = pad_sequences(dataX, maxlen=max_len, dtype='float32')
X = numpy.reshape(X, (X.shape[0], max_len, 3))
y = numpy.reshape(dataY, (X.shape[0], 3))
batch_size = 1
model = Sequential()
model.add(LSTM(32, input_shape=(X.shape[1], X.shape[2])))
model.add(Dropout(0.2))
model.add(Dense(y.shape[1], activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
n_epoch = 1
for i in range(n_epoch):
model.fit(X, y, epochs=1, batch_size=batch_size, verbose=1, shuffle=False)
model.reset_states()
model.save_weights("weights.h5")
model.save('model.h5')
with open('model-params.json', 'w') as f:
f.write(model.to_json())
scores = model.evaluate(X, y, verbose=0)
print("Model Accuracy: %.2f%%" % (scores[1]*100))
这是我的数据集的样子:
"time_date","name","user_id"
1402,"Sugar",3012
1402,"Milk",3012
1802,"Tomatoes",3012
1802,"Cucumber",3012
etc...
根据我的理解,我的dataX将具有(n_samples,5,3)的形状,因为我在我的序列的左边填充了零,所以如果我将前3个结果构建成它将成为的东西(第二列基于char_to_int func,所以我把一个随机数作为示例):
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [1402, 5323, 3012], [1402, 5324, 3012]]
我的数据是:
[[1802, 3212, 3012]]
这是对的吗?如果是这样,其他一些东西肯定是错的,因为这是1个纪元后的输出:
9700/9700 [==============================] - 31s - loss: 10405.0951 - acc: 0.8544
Model Accuracy: 87.49%
我觉得我差不多有这个型号,但是我错过了一些重要的东西,我不知道它是什么,我将不胜感激。感谢。
答案 0 :(得分:1)
似乎我误解了如何塑造我的数据,因为我使用categorical_crossentropy
丢失,我不得不用to_categorical对我的dataY进行单热编码,这非常有效。但是,在尝试训练大型数据集时,我得到了非常着名的MemoryError
。谢谢djk47463。