I have to work on an AI project the name is 'Create Text Classification Model'. From now on, I will explain the project you have to do.
The data is divided into two parts. 1. Training data: train.csv 2. Test data: test.csv the train.csv file consists of 3 columns of id, text and label, and the test.csv file consists of 2 columns of id and text.
The ‘label’ consists of a total of 8 category. ‘0’ is Science and Technology. ‘1’ is Sports. ‘2’ is Business And Company. ‘3’ is World topic and Global topic. ‘4’ is Politics and Government. ‘5’ is ‘ESG’(Environmetal, Social and Governance). ‘6’ is Health and Fitness. ‘7’ is Entertainment or enjoyment. The text column consists of news article text data and the text columns are all in English. So in this project, we should do multiple classifications. And goal of this project is creating ‘Submission.csv’ file from learing above train data and predicting test data. ‘Submission.csv’ file is consist of id and label columns.
The first thing you need to do is preprocess the train data. At this stage, please make the News article text data better to make it easier for the model to learn using LSTM.
Secondly, bring the best model for this project and learn the news article data and its label. At this time, adjust the parameters well so that overfitting does not occur.
Third, use the learned model to predict test data and create a submission file. And let me check the F1 Score to know the performance of the model.
Now write the code based on the information I provided.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is a Python code implementation for your "Create Text Classification Model" project using LSTM (Long Short-Term Memory) for text classification. This example leverages the Keras library with TensorFlow backend for building the LSTM model, and pandas for data manipulation, numpy for numerical computations, re for text preprocessing, and sklearn for evaluating the model's performance (F1 Score). Ensure you have these libraries installed (pip install pandas numpy tensorflow keras scikit-learn).
Code:
python
import pandas as pd
import numpy as np
import re
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense, Dropout
from sklearn.metrics import f1_score, classification_report, accuracy_score
from sklearn.model_selection import train_test_split
# **Step 1: Load and Preprocess Data**
### Load Data
train_df = pd.read_csv('train.csv')
test_df = pd.read_csv('test.csv')
### Define Label Mapping
label_map = {0: 'Science and Technology', 1: 'Sports', 2: 'Business And Company',
3: 'World topic and Global topic', 4: 'Politics and Government',
5: 'ESG (Environmental, Social and Governance)',
6: 'Health and Fitness', 7: 'Entertainment or enjoyment'}
### Preprocess Text Data
def preprocess_text(text):
text = text.lower() # Convert to lowercase
text = re.sub(r'[^a-zA-Z\s]', '', text) # Remove non-letter and non-space characters
return text
train_df['text'] = train_df['text'].apply(preprocess_text)
test_df['text'] = test_df['text'].apply(preprocess_text)
### Tokenize and Pad Sequences
tokenizer = Tokenizer()
tokenizer.fit_on_texts(train_df['text'])
train_sequences = tokenizer.texts_to_sequences(train_df['text'])
test_sequences = tokenizer.texts_to_sequences(test_df['text'])
max_length = 200 # Maximum length of text (adjust based on dataset)
padded_train = pad_sequences(train_sequences, maxlen=max_length, padding='post')
padded_test = pad_sequences(test_sequences, maxlen=max_length, padding='post')
### One-Hot Encode Labels
num_classes = 8
train_labels_onehot = to_categorical(train_df['label'], num_classes)
### Split Data for Validation
X_train, X_val, y_train, y_val = train_test_split(padded_train, train_labels_onehot, test_size=0.2, random_state=42)
# **Step 2: Build and Train LSTM Model**
### Define LSTM Model Architecture
model = Sequential()
model.add(Embedding(len(tokenizer.word_index) + 1, 64, input_length=max_length))
model.add(LSTM(64, dropout=0.2, recurrent_dropout=0.2))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
### Train the Model
batch_size = 32
epochs = 5 # Adjust epochs based on performance and overfitting
model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=epochs, batch_size=batch_size)
# **Step 3: Predict Test Data and Evaluate**
### Predict on Test Data
predictions = model.predict(padded_test)
predicted_labels = np.argmax(predictions, axis=1)
### Create Submission File
submission_df = pd.DataFrame({'id': test_df['id'], 'label': predicted_labels})
submission_df.to_csv('submission.csv', index=False)
### Evaluate Model Performance on Validation Set
val_pred = np.argmax(model.predict(X_val), axis=1)
val_true = np.argmax(y_val, axis=1)
print("F1 Score on Validation Set:", f1_score(val_true, val_pred, average='macro'))
print("Classification Report:\n", classification_report(val_true, val_pred))
print("Accuracy on Validation Set:", accuracy_score(val_true, val_pred))
Important Notes:
Hyperparameter Tuning: You may need to adjust max_length, batch_size, epochs, LSTM units, dropout rates, and the embedding dimension to optimize performance for your specific dataset. Techniques like Grid Search, Random Search, or Bayesian Optimization can be used to systematically find better hyperparameters.
Overfitting: Monitor validation accuracy and loss during training. If overfitting occurs, consider increasing dropout rates, adding more dropout layers, or collecting more data. Other strategies include early stopping, weight regularization, or using pre-trained embeddings like GloVe.
F1 Score Calculation: This example calculates the F1 score on the validation set. For the actual model performance evaluation, you might want to use a separate test set not used during training or tuning. Additionally, the classification_report from Scikit-learn provides a detailed breakdown of precision, recall, and F1 scores for each class, which is helpful for imbalanced datasets.
Submission File: Ensure the 'submission.csv' file format matches the expected format for your project submission.
Class Imbalance: If the dataset is imbalanced, consider using class weights, oversampling the minority class, undersampling the majority class, or using metrics like F1 score that are more robust to class imbalance.