时间序列坐标的Python二进制RNN分类

时间:2019-01-18 22:17:54

标签: python time-series coordinates recurrent-neural-network

我一直在尝试创建RNN。我总共有一个包含1661个单独“条目”的数据集,其中每个条目都有158个时间序列坐标。

以下是一个条目的一小部分:

0.00000000e+00  1.92609687e-04  3.85219375e-04  5.77829062e-04
3.00669864e-04  2.35106660e-05 -7.33379576e-04 -1.49026982e-03

这只是158个时间序列值的数组。

现在,我想对值数组是属于条件A还是条件B进行分类。

我看了很多博客,keras文档和youtube视频,并想到了以下网络:

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.embeddings import Embedding
from sklearn.model_selection import train_test_split
import numpy as  np
import matplotlib.pyplot as plt

# Set data and labels

# Somehow find a way to 'unpack' the data
datarnn = np.copy(normalized_data)
datarnn = np.array(rearrange_data(datarnn))
print(len(datarnn))

# Convert labels to binary labels
targetrnn = np.asarray(['1' if 'A' in str(x) else '0' for x in spineMidData_clean[:,0][1:]])

# Split data for training and testing
x_training,x_testing,y_training,y_testing = train_test_split(datarnn,targetrnn,test_size=0.2,random_state=4)

model=Sequential()

# Input layer
model.add(Embedding(1661, 1))

# Hidden layer
model.add(LSTM(3))

# Output layer with binary classification
model.add(Dense(1, activation='sigmoid'))

# Set training settings
model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])

# Model diagnostics
model.summary()

history = model.fit(x_training,y_training,epochs=20,validation_data=(x_testing,y_testing))

# Predict the test data
results = model.predict(x_testing)

我很高兴终于看到它起作用。但是,我似乎无法提高准确性,仍然保持在50%左右。有没有办法使这个网络更准确?例如。我要添加更多的层,还是以错误/低效的方式配置了现有的层?

1 个答案:

答案 0 :(得分:2)

确实 ,添加更多图层应有助于提高准确性。我记得曾经写过 ...更大深度的文章似乎可以带来更好的概括性

因此,来看看我一起准备的一个不错的keras设置。

from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
batch_size = 128
num_classes = 10
epochs = 12
img_rows, img_cols = 28, 28
(x_train, y_train), (x_test, y_test) = mnist.load_data()
if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])
model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
model.save("Model")

一如既往,另一种选择是增大训练数据的大小。

希望这会有所帮助!

干杯!