Advertisement
furas

Keras - data size for predict()

Jul 19th, 2018
276
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. #
  2. # Code to question on StackOverflow
  3. # https://stackoverflow.com/questions/51421885/expected-dense-to-have-shape-but-got-array-with-shape/51432523#51432523
  4. #
  5.  
  6. data = '''             query        tags
  7.               hi       intro
  8.      how are you       wellb
  9.            hello       intro
  10.        what's up       wellb
  11.       how's life       wellb
  12.              bye          gb
  13.    see you later          gb
  14.         good bye          gb
  15.           thanks   gratitude
  16.        thank you   gratitude
  17.  that's helpful   gratitude
  18.      I am great  revertfine
  19.            fine  revertfine
  20.       I am fine  revertfine
  21.            good  revertfine'''
  22.  
  23. import pandas as pd
  24. from io import StringIO
  25. import numpy as np
  26.  
  27. data = pd.read_table(StringIO(data), sep='\s{2,}')
  28.  
  29. print(df.columns)
  30. print(df)
  31.  
  32. #-------------------------------------------------------
  33.  
  34. from keras.preprocessing.text import Tokenizer
  35. from sklearn.preprocessing import LabelBinarizer
  36. from keras.models import Sequential
  37. import pandas as pd
  38. from keras.layers import Dense, Activation
  39.  
  40. #data = pd.read_csv('text_class.csv')
  41. train_text = data['query']
  42. train_labels = data['tags']
  43.  
  44. tokenize = Tokenizer(num_words=100)
  45. tokenize.fit_on_texts(train_text)
  46.  
  47. x_data = tokenize.texts_to_matrix(train_text)
  48.  
  49. encoder = LabelBinarizer()
  50. encoder.fit(train_labels)
  51. y_data = encoder.transform(train_labels)
  52.  
  53. model = Sequential()
  54. model.add(Dense(512, input_shape=(100,)))
  55. model.add(Activation('relu'))
  56. model.add(Dense(5))
  57. model.add(Activation('softmax'))
  58.  
  59. model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])
  60. model.fit(x_data, y_data, batch_size=8, epochs=10)
  61.  
  62. print('x_data     :', type(x_data), x_data.shape)
  63. print('x_data[0]  :', type(x_data[0]), x_data[0].shape)
  64. print('x_data[0:1]:', type(x_data[0:1]), x_data[0:1].shape)
  65.  
  66. predictions = model.predict(x_data[0:1]) # <-- need x_data[0:1] instead of x_data[0]
  67.  
  68. tag_labels = encoder.classes_
  69. predicted_tags = tag_labels[np.argmax(predictions)]
  70. print (predicted_tags)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement