Sequence classification using oneClass SVM Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Moderator Election Q&A - Questionnaire 2019 Community Moderator Election ResultsValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (0,)For stateful LSTM, does sequence length matter?TimeDistributed with different input / output sequence lengthFace Recognition Using HOG+SVMSequential Modelling: Multiple Sequence to One or Sequence to SequenceWhat should the size of the decoder output be in a sequence to sequence modelAnomaly detection on text data using one Class SVMtrain_test_split function error. ValueError: Found input variables with inconsistent numbers of samples: [6, 27696]Adding context in a sequence to sequence problemUsing VAE with Sequence to Sequence Approach

Why is the AVR GCC compiler using a full `CALL` even though I have set the `-mshort-calls` flag?

Amount of permutations on an NxNxN Rubik's Cube

Can the Great Weapon Master feat's damage bonus and accuracy penalty apply to attacks from the Spiritual Weapon spell?

How to compare two different files line by line in unix?

Is a ledger board required if the side of my house is wood?

AppleTVs create a chatty alternate WiFi network

Take 2! Is this homebrew Lady of Pain warlock patron balanced?

How to write the following sign?

How can I reduce the gap between left and right of cdot with a macro?

Sum letters are not two different

How fail-safe is nr as stop bytes?

Why is it faster to reheat something than it is to cook it?

Using audio cues to encourage good posture

Putting class ranking in CV, but against dept guidelines

How does Python know the values already stored in its memory?

An adverb for when you're not exaggerating

Drawing without replacement: why is the order of draw irrelevant?

Significance of Cersei's obsession with elephants?

A term for a woman complaining about things/begging in a cute/childish way

How to react to hostile behavior from a senior developer?

Why should I vote and accept answers?

What are the diatonic extended chords of C major?

Selecting user stories during sprint planning

How to tell that you are a giant?



Sequence classification using oneClass SVM



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
2019 Moderator Election Q&A - Questionnaire
2019 Community Moderator Election ResultsValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (0,)For stateful LSTM, does sequence length matter?TimeDistributed with different input / output sequence lengthFace Recognition Using HOG+SVMSequential Modelling: Multiple Sequence to One or Sequence to SequenceWhat should the size of the decoder output be in a sequence to sequence modelAnomaly detection on text data using one Class SVMtrain_test_split function error. ValueError: Found input variables with inconsistent numbers of samples: [6, 27696]Adding context in a sequence to sequence problemUsing VAE with Sequence to Sequence Approach










1












$begingroup$


In the code below, I'm using a sequence to sequence approach as a prediction model for anomaly detection, The data set I'm working with is ADFA-LD. The training phase is done using only normal sequences. After predicting the next sequence , I want to add a classifier, which will detect abnormal sequences (the test data contains normal and abnormal sequences). To do this, I used oneClass SVM as a classifier.
I don't know why but, the program run normally sometimes and display this error sometimes else:




ValueError: setting an array element with a sequence




at line: fraud_pred = oneclass.predict(np.array(x_test))



The code:
# Train - Test Split
X=lines[['eng','Class1']]
y=lines[['fr','Class2']]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)



#fonction pour charger le data par lot (batch size)
#séquence du générateur utilisée pour entraîner le réseau de neurones
def generate_batch(X = X_train, y = y_train, batch_size = 128):
''' Generate a batch of data '''

encoder_inputs = Input(shape=(None,))
en_x= Embedding(num_encoder_tokens, embedding_size,mask_zero = True)
(encoder_inputs) #convertit chaque mot en un vecteur de taille fix
encoder = GRU(256, return_state=True)
encoder_outputs, state_h = encoder(en_x)
decoder_inputs = Input(shape=(None,))
dex= Embedding(num_decoder_tokens, embedding_size,mask_zero =
True)#convertit chaque mot en un vecteur de taille fix
final_dex= dex(decoder_inputs)
decoder_gru = GRU(256, return_sequences=True)
decoder_gru2 = GRU(256, return_sequences=True,return_state=True)
decoder_outputs= decoder_gru(final_dex,initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
start = time.time()
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=
['acc'])

train_samples = len(X_train)
val_samples = len(X_test)

batch_size = 128
epochs = 1
mod_train=model.fit_generator(generator = generate_batch(X_train, y_train,
batch_size = batch_size),
steps_per_epoch = train_samples//batch_size,
epochs=epochs,
validation_data = generate_batch(X_test, y_test, batch_size
= batch_size),
validation_steps = val_samples//batch_size)
df_history = pd.DataFrame (mod_train.history)
print(df_history)
#####################################
#modeles de prédiction
# define inference encoder
encoder_model = Model(encoder_inputs,encoder_states)
# define inference decoder
decoder_state_input_h = Input(shape=(256,))
decoder_states_inputs = [decoder_state_input_h]
final_dex2= dex(decoder_inputs)
print(final_dex2)
decoder_outputs2,state_h2 = decoder_gru2(final_dex2,
initial_state=decoder_states_inputs)
decoder_states2 = [state_h2]
decoder_outputs2 = decoder_dense(decoder_outputs2)
decoder_model = Model([decoder_inputs] + decoder_states_inputs,
[decoder_outputs2] + decoder_states2)



def decode_sequence(input_seq):
# Encode the input as state vectors.
states_value = encoder_model.predict(input_seq)
print(len(states_value),states_value.shape)
# Generate empty target sequence of length 1.
target_seq = np.zeros((1,1))
# Populate the first word of target sequence with the start word.
target_seq[0,0] = target_token_index['0000']

stop_condition = False
decoded_sentence = ''
while not stop_condition:
output_tokens,h= decoder_model.predict([target_seq]+[states_value])
sampled_token_index = np.argmax(output_tokens[0, -1, :])
sampled_char = reverse_target_char_index[sampled_token_index]
decoded_sentence +=' '+sampled_char

# Exit condition: either hit max length
# or find stop character.
if (sampled_char =='1111' or len(decoded_sentence.split(' '))>
max_len_fr-2):#critere d'arret (la fin de la phrase en français)
stop_condition = True

# Update the target sequence (of length 1).
target_seq = np.zeros((1,1))
target_seq[0] = sampled_token_index

# Update states
states_value = h
return decoded_sentence

y_true=[]
NN=[]
test_gen = generate_batch(X_train, y_train, batch_size = 1)
k=0
while k<300:
(input_seq, actual_output), _ = next(test_gen)
decoded_sentence = decode_sequence(input_seq)
exp=map(float, str(decoded_sentence).split())
NN.append(list(exp))
k+=1

#seq_preditN = np.transpose(NN)
seq_preditN = NN
"""------Classification--- """

seq_preditA=[]
path1="abnormal.csv"
abnor_data=load_data(path1)
abnor_data.insert(1, 'Class1',1)
abnor_data.insert(3, 'Class2',1)
X_attck=abnor_data[['eng','Class1']]
y_attck=abnor_data[['fr','Class2']]
#X_trainA, X_testA, y_trainA, y_testA = train_test_split(X, y, test_size =
0.2)

test_gen = generate_batch(X_attck, y_attck, batch_size = 1)
k=-1
k+=1
while k<300:
(input_seq, actual_output), _ = next(test_gen)
decoded_sentence = decode_sequence(input_seq)
print('Input English sentence:', X_attck[k:k+1].values[0])
print('Actual Marathi Translation:', y_attck.fr[k:k+1].values[0])
print('Predicted Marathi Translation:', decoded_sentence)
exp=map(float, str(decoded_sentence).split())
seq_preditA.append(list(exp))
k+=1
#seq_preditN = seq_preditN[0:300]
#seq_preditA = np.transpose(seq_preditA)

X_test = seq_preditA + seq_preditN
X_test = np.transpose(X_test)
#X_test = np.concatenate((seq_preditA, seq_preditN), axis =0)
print ("X_test")
print (X_test)
print("kkkkkkk", len(X_test))

oneclass = svm.OneClassSVM(kernel='linear', gamma=0.001, nu=0.95)
y=np.array([np.array(item) for item in seq_preditN])
oneclass.fit(np.array(y))
fraud_pred = oneclass.predict(np.array(X_test))
unique, counts = np.unique(fraud_pred, return_counts=True)
print (np.asarray((unique, counts)).T)
fraud_pred = pd.DataFrame(fraud_pred)
print("fraus.......",fraud_pred)
y1=y_attck.Class2[0:300]
y2=y_test.Class2[0:300]
Y_test=y1.append(y2)
print(Y_test)


If anyone can help me , I'll be sooo thankful










share|improve this question









$endgroup$
















    1












    $begingroup$


    In the code below, I'm using a sequence to sequence approach as a prediction model for anomaly detection, The data set I'm working with is ADFA-LD. The training phase is done using only normal sequences. After predicting the next sequence , I want to add a classifier, which will detect abnormal sequences (the test data contains normal and abnormal sequences). To do this, I used oneClass SVM as a classifier.
    I don't know why but, the program run normally sometimes and display this error sometimes else:




    ValueError: setting an array element with a sequence




    at line: fraud_pred = oneclass.predict(np.array(x_test))



    The code:
    # Train - Test Split
    X=lines[['eng','Class1']]
    y=lines[['fr','Class2']]
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)



    #fonction pour charger le data par lot (batch size)
    #séquence du générateur utilisée pour entraîner le réseau de neurones
    def generate_batch(X = X_train, y = y_train, batch_size = 128):
    ''' Generate a batch of data '''

    encoder_inputs = Input(shape=(None,))
    en_x= Embedding(num_encoder_tokens, embedding_size,mask_zero = True)
    (encoder_inputs) #convertit chaque mot en un vecteur de taille fix
    encoder = GRU(256, return_state=True)
    encoder_outputs, state_h = encoder(en_x)
    decoder_inputs = Input(shape=(None,))
    dex= Embedding(num_decoder_tokens, embedding_size,mask_zero =
    True)#convertit chaque mot en un vecteur de taille fix
    final_dex= dex(decoder_inputs)
    decoder_gru = GRU(256, return_sequences=True)
    decoder_gru2 = GRU(256, return_sequences=True,return_state=True)
    decoder_outputs= decoder_gru(final_dex,initial_state=encoder_states)
    decoder_dense = Dense(num_decoder_tokens, activation='softmax')
    decoder_outputs = decoder_dense(decoder_outputs)
    model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
    start = time.time()
    model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=
    ['acc'])

    train_samples = len(X_train)
    val_samples = len(X_test)

    batch_size = 128
    epochs = 1
    mod_train=model.fit_generator(generator = generate_batch(X_train, y_train,
    batch_size = batch_size),
    steps_per_epoch = train_samples//batch_size,
    epochs=epochs,
    validation_data = generate_batch(X_test, y_test, batch_size
    = batch_size),
    validation_steps = val_samples//batch_size)
    df_history = pd.DataFrame (mod_train.history)
    print(df_history)
    #####################################
    #modeles de prédiction
    # define inference encoder
    encoder_model = Model(encoder_inputs,encoder_states)
    # define inference decoder
    decoder_state_input_h = Input(shape=(256,))
    decoder_states_inputs = [decoder_state_input_h]
    final_dex2= dex(decoder_inputs)
    print(final_dex2)
    decoder_outputs2,state_h2 = decoder_gru2(final_dex2,
    initial_state=decoder_states_inputs)
    decoder_states2 = [state_h2]
    decoder_outputs2 = decoder_dense(decoder_outputs2)
    decoder_model = Model([decoder_inputs] + decoder_states_inputs,
    [decoder_outputs2] + decoder_states2)



    def decode_sequence(input_seq):
    # Encode the input as state vectors.
    states_value = encoder_model.predict(input_seq)
    print(len(states_value),states_value.shape)
    # Generate empty target sequence of length 1.
    target_seq = np.zeros((1,1))
    # Populate the first word of target sequence with the start word.
    target_seq[0,0] = target_token_index['0000']

    stop_condition = False
    decoded_sentence = ''
    while not stop_condition:
    output_tokens,h= decoder_model.predict([target_seq]+[states_value])
    sampled_token_index = np.argmax(output_tokens[0, -1, :])
    sampled_char = reverse_target_char_index[sampled_token_index]
    decoded_sentence +=' '+sampled_char

    # Exit condition: either hit max length
    # or find stop character.
    if (sampled_char =='1111' or len(decoded_sentence.split(' '))>
    max_len_fr-2):#critere d'arret (la fin de la phrase en français)
    stop_condition = True

    # Update the target sequence (of length 1).
    target_seq = np.zeros((1,1))
    target_seq[0] = sampled_token_index

    # Update states
    states_value = h
    return decoded_sentence

    y_true=[]
    NN=[]
    test_gen = generate_batch(X_train, y_train, batch_size = 1)
    k=0
    while k<300:
    (input_seq, actual_output), _ = next(test_gen)
    decoded_sentence = decode_sequence(input_seq)
    exp=map(float, str(decoded_sentence).split())
    NN.append(list(exp))
    k+=1

    #seq_preditN = np.transpose(NN)
    seq_preditN = NN
    """------Classification--- """

    seq_preditA=[]
    path1="abnormal.csv"
    abnor_data=load_data(path1)
    abnor_data.insert(1, 'Class1',1)
    abnor_data.insert(3, 'Class2',1)
    X_attck=abnor_data[['eng','Class1']]
    y_attck=abnor_data[['fr','Class2']]
    #X_trainA, X_testA, y_trainA, y_testA = train_test_split(X, y, test_size =
    0.2)

    test_gen = generate_batch(X_attck, y_attck, batch_size = 1)
    k=-1
    k+=1
    while k<300:
    (input_seq, actual_output), _ = next(test_gen)
    decoded_sentence = decode_sequence(input_seq)
    print('Input English sentence:', X_attck[k:k+1].values[0])
    print('Actual Marathi Translation:', y_attck.fr[k:k+1].values[0])
    print('Predicted Marathi Translation:', decoded_sentence)
    exp=map(float, str(decoded_sentence).split())
    seq_preditA.append(list(exp))
    k+=1
    #seq_preditN = seq_preditN[0:300]
    #seq_preditA = np.transpose(seq_preditA)

    X_test = seq_preditA + seq_preditN
    X_test = np.transpose(X_test)
    #X_test = np.concatenate((seq_preditA, seq_preditN), axis =0)
    print ("X_test")
    print (X_test)
    print("kkkkkkk", len(X_test))

    oneclass = svm.OneClassSVM(kernel='linear', gamma=0.001, nu=0.95)
    y=np.array([np.array(item) for item in seq_preditN])
    oneclass.fit(np.array(y))
    fraud_pred = oneclass.predict(np.array(X_test))
    unique, counts = np.unique(fraud_pred, return_counts=True)
    print (np.asarray((unique, counts)).T)
    fraud_pred = pd.DataFrame(fraud_pred)
    print("fraus.......",fraud_pred)
    y1=y_attck.Class2[0:300]
    y2=y_test.Class2[0:300]
    Y_test=y1.append(y2)
    print(Y_test)


    If anyone can help me , I'll be sooo thankful










    share|improve this question









    $endgroup$














      1












      1








      1





      $begingroup$


      In the code below, I'm using a sequence to sequence approach as a prediction model for anomaly detection, The data set I'm working with is ADFA-LD. The training phase is done using only normal sequences. After predicting the next sequence , I want to add a classifier, which will detect abnormal sequences (the test data contains normal and abnormal sequences). To do this, I used oneClass SVM as a classifier.
      I don't know why but, the program run normally sometimes and display this error sometimes else:




      ValueError: setting an array element with a sequence




      at line: fraud_pred = oneclass.predict(np.array(x_test))



      The code:
      # Train - Test Split
      X=lines[['eng','Class1']]
      y=lines[['fr','Class2']]
      X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)



      #fonction pour charger le data par lot (batch size)
      #séquence du générateur utilisée pour entraîner le réseau de neurones
      def generate_batch(X = X_train, y = y_train, batch_size = 128):
      ''' Generate a batch of data '''

      encoder_inputs = Input(shape=(None,))
      en_x= Embedding(num_encoder_tokens, embedding_size,mask_zero = True)
      (encoder_inputs) #convertit chaque mot en un vecteur de taille fix
      encoder = GRU(256, return_state=True)
      encoder_outputs, state_h = encoder(en_x)
      decoder_inputs = Input(shape=(None,))
      dex= Embedding(num_decoder_tokens, embedding_size,mask_zero =
      True)#convertit chaque mot en un vecteur de taille fix
      final_dex= dex(decoder_inputs)
      decoder_gru = GRU(256, return_sequences=True)
      decoder_gru2 = GRU(256, return_sequences=True,return_state=True)
      decoder_outputs= decoder_gru(final_dex,initial_state=encoder_states)
      decoder_dense = Dense(num_decoder_tokens, activation='softmax')
      decoder_outputs = decoder_dense(decoder_outputs)
      model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
      start = time.time()
      model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=
      ['acc'])

      train_samples = len(X_train)
      val_samples = len(X_test)

      batch_size = 128
      epochs = 1
      mod_train=model.fit_generator(generator = generate_batch(X_train, y_train,
      batch_size = batch_size),
      steps_per_epoch = train_samples//batch_size,
      epochs=epochs,
      validation_data = generate_batch(X_test, y_test, batch_size
      = batch_size),
      validation_steps = val_samples//batch_size)
      df_history = pd.DataFrame (mod_train.history)
      print(df_history)
      #####################################
      #modeles de prédiction
      # define inference encoder
      encoder_model = Model(encoder_inputs,encoder_states)
      # define inference decoder
      decoder_state_input_h = Input(shape=(256,))
      decoder_states_inputs = [decoder_state_input_h]
      final_dex2= dex(decoder_inputs)
      print(final_dex2)
      decoder_outputs2,state_h2 = decoder_gru2(final_dex2,
      initial_state=decoder_states_inputs)
      decoder_states2 = [state_h2]
      decoder_outputs2 = decoder_dense(decoder_outputs2)
      decoder_model = Model([decoder_inputs] + decoder_states_inputs,
      [decoder_outputs2] + decoder_states2)



      def decode_sequence(input_seq):
      # Encode the input as state vectors.
      states_value = encoder_model.predict(input_seq)
      print(len(states_value),states_value.shape)
      # Generate empty target sequence of length 1.
      target_seq = np.zeros((1,1))
      # Populate the first word of target sequence with the start word.
      target_seq[0,0] = target_token_index['0000']

      stop_condition = False
      decoded_sentence = ''
      while not stop_condition:
      output_tokens,h= decoder_model.predict([target_seq]+[states_value])
      sampled_token_index = np.argmax(output_tokens[0, -1, :])
      sampled_char = reverse_target_char_index[sampled_token_index]
      decoded_sentence +=' '+sampled_char

      # Exit condition: either hit max length
      # or find stop character.
      if (sampled_char =='1111' or len(decoded_sentence.split(' '))>
      max_len_fr-2):#critere d'arret (la fin de la phrase en français)
      stop_condition = True

      # Update the target sequence (of length 1).
      target_seq = np.zeros((1,1))
      target_seq[0] = sampled_token_index

      # Update states
      states_value = h
      return decoded_sentence

      y_true=[]
      NN=[]
      test_gen = generate_batch(X_train, y_train, batch_size = 1)
      k=0
      while k<300:
      (input_seq, actual_output), _ = next(test_gen)
      decoded_sentence = decode_sequence(input_seq)
      exp=map(float, str(decoded_sentence).split())
      NN.append(list(exp))
      k+=1

      #seq_preditN = np.transpose(NN)
      seq_preditN = NN
      """------Classification--- """

      seq_preditA=[]
      path1="abnormal.csv"
      abnor_data=load_data(path1)
      abnor_data.insert(1, 'Class1',1)
      abnor_data.insert(3, 'Class2',1)
      X_attck=abnor_data[['eng','Class1']]
      y_attck=abnor_data[['fr','Class2']]
      #X_trainA, X_testA, y_trainA, y_testA = train_test_split(X, y, test_size =
      0.2)

      test_gen = generate_batch(X_attck, y_attck, batch_size = 1)
      k=-1
      k+=1
      while k<300:
      (input_seq, actual_output), _ = next(test_gen)
      decoded_sentence = decode_sequence(input_seq)
      print('Input English sentence:', X_attck[k:k+1].values[0])
      print('Actual Marathi Translation:', y_attck.fr[k:k+1].values[0])
      print('Predicted Marathi Translation:', decoded_sentence)
      exp=map(float, str(decoded_sentence).split())
      seq_preditA.append(list(exp))
      k+=1
      #seq_preditN = seq_preditN[0:300]
      #seq_preditA = np.transpose(seq_preditA)

      X_test = seq_preditA + seq_preditN
      X_test = np.transpose(X_test)
      #X_test = np.concatenate((seq_preditA, seq_preditN), axis =0)
      print ("X_test")
      print (X_test)
      print("kkkkkkk", len(X_test))

      oneclass = svm.OneClassSVM(kernel='linear', gamma=0.001, nu=0.95)
      y=np.array([np.array(item) for item in seq_preditN])
      oneclass.fit(np.array(y))
      fraud_pred = oneclass.predict(np.array(X_test))
      unique, counts = np.unique(fraud_pred, return_counts=True)
      print (np.asarray((unique, counts)).T)
      fraud_pred = pd.DataFrame(fraud_pred)
      print("fraus.......",fraud_pred)
      y1=y_attck.Class2[0:300]
      y2=y_test.Class2[0:300]
      Y_test=y1.append(y2)
      print(Y_test)


      If anyone can help me , I'll be sooo thankful










      share|improve this question









      $endgroup$




      In the code below, I'm using a sequence to sequence approach as a prediction model for anomaly detection, The data set I'm working with is ADFA-LD. The training phase is done using only normal sequences. After predicting the next sequence , I want to add a classifier, which will detect abnormal sequences (the test data contains normal and abnormal sequences). To do this, I used oneClass SVM as a classifier.
      I don't know why but, the program run normally sometimes and display this error sometimes else:




      ValueError: setting an array element with a sequence




      at line: fraud_pred = oneclass.predict(np.array(x_test))



      The code:
      # Train - Test Split
      X=lines[['eng','Class1']]
      y=lines[['fr','Class2']]
      X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)



      #fonction pour charger le data par lot (batch size)
      #séquence du générateur utilisée pour entraîner le réseau de neurones
      def generate_batch(X = X_train, y = y_train, batch_size = 128):
      ''' Generate a batch of data '''

      encoder_inputs = Input(shape=(None,))
      en_x= Embedding(num_encoder_tokens, embedding_size,mask_zero = True)
      (encoder_inputs) #convertit chaque mot en un vecteur de taille fix
      encoder = GRU(256, return_state=True)
      encoder_outputs, state_h = encoder(en_x)
      decoder_inputs = Input(shape=(None,))
      dex= Embedding(num_decoder_tokens, embedding_size,mask_zero =
      True)#convertit chaque mot en un vecteur de taille fix
      final_dex= dex(decoder_inputs)
      decoder_gru = GRU(256, return_sequences=True)
      decoder_gru2 = GRU(256, return_sequences=True,return_state=True)
      decoder_outputs= decoder_gru(final_dex,initial_state=encoder_states)
      decoder_dense = Dense(num_decoder_tokens, activation='softmax')
      decoder_outputs = decoder_dense(decoder_outputs)
      model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
      start = time.time()
      model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=
      ['acc'])

      train_samples = len(X_train)
      val_samples = len(X_test)

      batch_size = 128
      epochs = 1
      mod_train=model.fit_generator(generator = generate_batch(X_train, y_train,
      batch_size = batch_size),
      steps_per_epoch = train_samples//batch_size,
      epochs=epochs,
      validation_data = generate_batch(X_test, y_test, batch_size
      = batch_size),
      validation_steps = val_samples//batch_size)
      df_history = pd.DataFrame (mod_train.history)
      print(df_history)
      #####################################
      #modeles de prédiction
      # define inference encoder
      encoder_model = Model(encoder_inputs,encoder_states)
      # define inference decoder
      decoder_state_input_h = Input(shape=(256,))
      decoder_states_inputs = [decoder_state_input_h]
      final_dex2= dex(decoder_inputs)
      print(final_dex2)
      decoder_outputs2,state_h2 = decoder_gru2(final_dex2,
      initial_state=decoder_states_inputs)
      decoder_states2 = [state_h2]
      decoder_outputs2 = decoder_dense(decoder_outputs2)
      decoder_model = Model([decoder_inputs] + decoder_states_inputs,
      [decoder_outputs2] + decoder_states2)



      def decode_sequence(input_seq):
      # Encode the input as state vectors.
      states_value = encoder_model.predict(input_seq)
      print(len(states_value),states_value.shape)
      # Generate empty target sequence of length 1.
      target_seq = np.zeros((1,1))
      # Populate the first word of target sequence with the start word.
      target_seq[0,0] = target_token_index['0000']

      stop_condition = False
      decoded_sentence = ''
      while not stop_condition:
      output_tokens,h= decoder_model.predict([target_seq]+[states_value])
      sampled_token_index = np.argmax(output_tokens[0, -1, :])
      sampled_char = reverse_target_char_index[sampled_token_index]
      decoded_sentence +=' '+sampled_char

      # Exit condition: either hit max length
      # or find stop character.
      if (sampled_char =='1111' or len(decoded_sentence.split(' '))>
      max_len_fr-2):#critere d'arret (la fin de la phrase en français)
      stop_condition = True

      # Update the target sequence (of length 1).
      target_seq = np.zeros((1,1))
      target_seq[0] = sampled_token_index

      # Update states
      states_value = h
      return decoded_sentence

      y_true=[]
      NN=[]
      test_gen = generate_batch(X_train, y_train, batch_size = 1)
      k=0
      while k<300:
      (input_seq, actual_output), _ = next(test_gen)
      decoded_sentence = decode_sequence(input_seq)
      exp=map(float, str(decoded_sentence).split())
      NN.append(list(exp))
      k+=1

      #seq_preditN = np.transpose(NN)
      seq_preditN = NN
      """------Classification--- """

      seq_preditA=[]
      path1="abnormal.csv"
      abnor_data=load_data(path1)
      abnor_data.insert(1, 'Class1',1)
      abnor_data.insert(3, 'Class2',1)
      X_attck=abnor_data[['eng','Class1']]
      y_attck=abnor_data[['fr','Class2']]
      #X_trainA, X_testA, y_trainA, y_testA = train_test_split(X, y, test_size =
      0.2)

      test_gen = generate_batch(X_attck, y_attck, batch_size = 1)
      k=-1
      k+=1
      while k<300:
      (input_seq, actual_output), _ = next(test_gen)
      decoded_sentence = decode_sequence(input_seq)
      print('Input English sentence:', X_attck[k:k+1].values[0])
      print('Actual Marathi Translation:', y_attck.fr[k:k+1].values[0])
      print('Predicted Marathi Translation:', decoded_sentence)
      exp=map(float, str(decoded_sentence).split())
      seq_preditA.append(list(exp))
      k+=1
      #seq_preditN = seq_preditN[0:300]
      #seq_preditA = np.transpose(seq_preditA)

      X_test = seq_preditA + seq_preditN
      X_test = np.transpose(X_test)
      #X_test = np.concatenate((seq_preditA, seq_preditN), axis =0)
      print ("X_test")
      print (X_test)
      print("kkkkkkk", len(X_test))

      oneclass = svm.OneClassSVM(kernel='linear', gamma=0.001, nu=0.95)
      y=np.array([np.array(item) for item in seq_preditN])
      oneclass.fit(np.array(y))
      fraud_pred = oneclass.predict(np.array(X_test))
      unique, counts = np.unique(fraud_pred, return_counts=True)
      print (np.asarray((unique, counts)).T)
      fraud_pred = pd.DataFrame(fraud_pred)
      print("fraus.......",fraud_pred)
      y1=y_attck.Class2[0:300]
      y2=y_test.Class2[0:300]
      Y_test=y1.append(y2)
      print(Y_test)


      If anyone can help me , I'll be sooo thankful







      python neural-network anomaly-detection recurrent-neural-net






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 29 mins ago









      KikioKikio

      8810




      8810




















          0






          active

          oldest

          votes












          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "557"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdatascience.stackexchange.com%2fquestions%2f49560%2fsequence-classification-using-oneclass-svm%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Data Science Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdatascience.stackexchange.com%2fquestions%2f49560%2fsequence-classification-using-oneclass-svm%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Францішак Багушэвіч Змест Сям'я | Біяграфія | Творчасць | Мова Багушэвіча | Ацэнкі дзейнасці | Цікавыя факты | Спадчына | Выбраная бібліяграфія | Ушанаванне памяці | У філатэліі | Зноскі | Літаратура | Спасылкі | НавігацыяЛяхоўскі У. Рупіўся дзеля Бога і людзей: Жыццёвы шлях Лявона Вітан-Дубейкаўскага // Вольскі і Памідораў з песняй пра немца Адвакат, паэт, народны заступнік Ашмянскі веснікВ Минске появится площадь Богушевича и улица Сырокомли, Белорусская деловая газета, 19 июля 2001 г.Айцец беларускай нацыянальнай ідэі паўстаў у бронзе Сяргей Аляксандравіч Адашкевіч (1918, Мінск). 80-я гады. Бюст «Францішак Багушэвіч».Яўген Мікалаевіч Ціхановіч. «Партрэт Францішка Багушэвіча»Мікола Мікалаевіч Купава. «Партрэт зачынальніка новай беларускай літаратуры Францішка Багушэвіча»Уладзімір Іванавіч Мелехаў. На помніку «Змагарам за родную мову» Барэльеф «Францішак Багушэвіч»Памяць пра Багушэвіча на Віленшчыне Страчаная сталіца. Беларускія шыльды на вуліцах Вільні«Krynica». Ideologia i przywódcy białoruskiego katolicyzmuФранцішак БагушэвічТворы на knihi.comТворы Францішка Багушэвіча на bellib.byСодаль Уладзімір. Францішак Багушэвіч на Лідчыне;Луцкевіч Антон. Жыцьцё і творчасьць Фр. Багушэвіча ў успамінах ягоных сучасьнікаў // Запісы Беларускага Навуковага таварыства. Вільня, 1938. Сшытак 1. С. 16-34.Большая российская1188761710000 0000 5537 633Xn9209310021619551927869394п

          Беларусь Змест Назва Гісторыя Геаграфія Сімволіка Дзяржаўны лад Палітычныя партыі Міжнароднае становішча і знешняя палітыка Адміністрацыйны падзел Насельніцтва Эканоміка Культура і грамадства Сацыяльная сфера Узброеныя сілы Заўвагі Літаратура Спасылкі НавігацыяHGЯOiТоп-2011 г. (па версіі ej.by)Топ-2013 г. (па версіі ej.by)Топ-2016 г. (па версіі ej.by)Топ-2017 г. (па версіі ej.by)Нацыянальны статыстычны камітэт Рэспублікі БеларусьШчыльнасць насельніцтва па краінахhttp://naviny.by/rubrics/society/2011/09/16/ic_articles_116_175144/А. Калечыц, У. Ксяндзоў. Спробы засялення краю неандэртальскім чалавекам.І ў Менску былі мамантыА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіГ. Штыхаў. Балты і славяне ў VI—VIII стст.М. Клімаў. Полацкае княства ў IX—XI стст.Г. Штыхаў, В. Ляўко. Палітычная гісторыя Полацкай зямліГ. Штыхаў. Дзяржаўны лад у землях-княствахГ. Штыхаў. Дзяржаўны лад у землях-княствахБеларускія землі ў складзе Вялікага Княства ЛітоўскагаЛюблінская унія 1569 г."The Early Stages of Independence"Zapomniane prawdy25 гадоў таму было аб'яўлена, што Язэп Пілсудскі — беларус (фота)Наша вадаДакументы ЧАЭС: Забруджванне тэрыторыі Беларусі « ЧАЭС Зона адчужэнняСведения о политических партиях, зарегистрированных в Республике Беларусь // Министерство юстиции Республики БеларусьСтатыстычны бюлетэнь „Полаўзроставая структура насельніцтва Рэспублікі Беларусь на 1 студзеня 2012 года і сярэднегадовая колькасць насельніцтва за 2011 год“Индекс человеческого развития Беларуси — не было бы нижеБеларусь занимает первое место в СНГ по индексу развития с учетом гендерного факцёраНацыянальны статыстычны камітэт Рэспублікі БеларусьКанстытуцыя РБ. Артыкул 17Трансфармацыйныя задачы БеларусіВыйсце з крызісу — далейшае рэфармаванне Беларускі рубель — сусветны лідар па дэвальвацыяхПра змену коштаў у кастрычніку 2011 г.Бядней за беларусаў у СНД толькі таджыкіСярэдні заробак у верасні дасягнуў 2,26 мільёна рублёўЭканомікаГаласуем за ТОП-100 беларускай прозыСучасныя беларускія мастакіАрхитектура Беларуси BELARUS.BYА. Каханоўскі. Культура Беларусі ўсярэдзіне XVII—XVIII ст.Анталогія беларускай народнай песні, гуказапісы спеваўБеларускія Музычныя IнструментыБеларускі рок, які мы страцілі. Топ-10 гуртоў«Мясцовы час» — нязгаслая легенда беларускай рок-музыкіСЯРГЕЙ БУДКІН. МЫ НЯ ЗНАЕМ СВАЁЙ МУЗЫКІМ. А. Каладзінскі. НАРОДНЫ ТЭАТРМагнацкія культурныя цэнтрыПублічная дыскусія «Беларуская новая пьеса: без беларускай мовы ці беларуская?»Беларускія драматургі па-ранейшаму лепш ставяцца за мяжой, чым на радзіме«Працэс незалежнага кіно пайшоў, і дзяржаву турбуе яго непадкантрольнасць»Беларускія філосафы ў пошуках прасторыВсе идём в библиотекуАрхіваванаАб Нацыянальнай праграме даследавання і выкарыстання касмічнай прасторы ў мірных мэтах на 2008—2012 гадыУ космас — разам.У суседнім з Барысаўскім раёне пабудуюць Камандна-вымяральны пунктСвяты і абрады беларусаў«Мірныя бульбашы з малой краіны» — 5 непраўдзівых стэрэатыпаў пра БеларусьМ. Раманюк. Беларускае народнае адзеннеУ Беларусі скарачаецца колькасць злачынстваўЛукашэнка незадаволены мінскімі ўладамі Крадзяжы складаюць у Мінску каля 70% злачынстваў Узровень злачыннасці ў Мінскай вобласці — адзін з самых высокіх у краіне Генпракуратура аналізуе стан са злачыннасцю ў Беларусі па каэфіцыенце злачыннасці У Беларусі стабілізавалася крымінагеннае становішча, лічыць генпракурорЗамежнікі сталі здзяйсняць у Беларусі больш злачынстваўМУС Беларусі турбуе рост рэцыдыўнай злачыннасціЯ з ЖЭСа. Дазволіце вас абкрасці! Рэйтынг усіх службаў і падраздзяленняў ГУУС Мінгарвыканкама вырасАб КДБ РБГісторыя Аператыўна-аналітычнага цэнтра РБГісторыя ДКФРТаможняagentura.ruБеларусьBelarus.by — Афіцыйны сайт Рэспублікі БеларусьСайт урада БеларусіRadzima.org — Збор архітэктурных помнікаў, гісторыя Беларусі«Глобус Беларуси»Гербы и флаги БеларусиАсаблівасці каменнага веку на БеларусіА. Калечыц, У. Ксяндзоў. Старажытны каменны век (палеаліт). Першапачатковае засяленне тэрыторыіУ. Ксяндзоў. Сярэдні каменны век (мезаліт). Засяленне краю плямёнамі паляўнічых, рыбакоў і збіральнікаўА. Калечыц, М. Чарняўскі. Плямёны на тэрыторыі Беларусі ў новым каменным веку (неаліце)А. Калечыц, У. Ксяндзоў, М. Чарняўскі. Гаспадарчыя заняткі ў каменным векуЭ. Зайкоўскі. Духоўная культура ў каменным векуАсаблівасці бронзавага веку на БеларусіФарміраванне супольнасцей ранняга перыяду бронзавага векуФотографии БеларусиРоля беларускіх зямель ва ўтварэнні і ўмацаванні ВКЛВ. Фадзеева. З гісторыі развіцця беларускай народнай вышыўкіDMOZGran catalanaБольшая российскаяBritannica (анлайн)Швейцарскі гістарычны15325917611952699xDA123282154079143-90000 0001 2171 2080n9112870100577502ge128882171858027501086026362074122714179пппппп

          ValueError: Expected n_neighbors <= n_samples, but n_samples = 1, n_neighbors = 6 (SMOTE) The 2019 Stack Overflow Developer Survey Results Are InCan SMOTE be applied over sequence of words (sentences)?ValueError when doing validation with random forestsSMOTE and multi class oversamplingLogic behind SMOTE-NC?ValueError: Error when checking target: expected dense_1 to have shape (7,) but got array with shape (1,)SmoteBoost: Should SMOTE be ran individually for each iteration/tree in the boosting?solving multi-class imbalance classification using smote and OSSUsing SMOTE for Synthetic Data generation to improve performance on unbalanced dataproblem of entry format for a simple model in KerasSVM SMOTE fit_resample() function runs forever with no result