| import pickle |
| import tensorflow as tf |
| import pandas as pd |
| import re |
|
|
|
|
| |
| def preprocess_text(text): |
| |
| text = text.lower() |
| |
| text = re.sub(r'[^a-zA-Z0-9\'+\-*/\s]', ' ', text) |
| |
| text = text.replace('plus', '+') |
| |
| text = text.replace('minus', '-') |
| |
| text = text.replace('times', '*') |
| |
| text = text.replace('divided by', '/') |
| |
| text = text.replace('*', ' * ').replace('/', ' / ').replace('-', ' - ').replace('+', ' + ').replace('.', ' . ') |
| |
| text = re.sub(r'\d+', '<num>', text) |
| |
| text = text.replace(r'oov', '<oov>') |
| |
| text = re.sub(r'\s+', ' ', text) |
| return text.strip() |
|
|
|
|
| epochs = int(input("epochs: ")) |
| batch_size = int(input("batch size: ")) |
|
|
| |
| data = pd.read_csv("data.csv") |
| input_data = data['input'].values |
| labels = data['class'].values |
|
|
| |
| input_data = [preprocess_text(text) for text in input_data] |
|
|
| |
| vocab = tf.keras.preprocessing.text.Tokenizer(filters='') |
| vocab.fit_on_texts(input_data) |
| encoded_input = vocab.texts_to_sequences(input_data) |
|
|
| |
| max_length = max([len(seq) for seq in encoded_input]) |
| padded_input = tf.keras.preprocessing.sequence.pad_sequences(encoded_input, maxlen=max_length, padding='post') |
|
|
| |
| model = tf.keras.Sequential([ |
| tf.keras.layers.Embedding(input_dim=len(vocab.word_index) + 1, output_dim=64, input_length=max_length), |
| tf.keras.layers.Conv1D(filters=64, kernel_size=3, activation='relu', padding='same'), |
| tf.keras.layers.GlobalMaxPooling1D(), |
| tf.keras.layers.Dense(128, activation='relu'), |
| tf.keras.layers.Dense(128, activation=tf.keras.layers.ELU(alpha=1.0)), |
| tf.keras.layers.Dense(3, activation='softmax') |
| ]) |
|
|
| |
| model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) |
|
|
| |
| model.fit(padded_input, labels, epochs=epochs, batch_size=batch_size) |
|
|
| |
| model.save('main.h5') |
|
|
| |
| with open('tokenizer.pkl', 'wb') as file: |
| pickle.dump(vocab, file) |
|
|
| token_to_word = {token: word for word, token in vocab.word_index.items()} |
| print(token_to_word) |
|
|
| model.summary() |
|
|
| |
|
|