Sure, here's the code to train a model with TF-IDF and LSTM using the provided data:
```python
import pandas as pd
import numpy as np
from sklearn.utils import compute_class_weight
from sklearn.feature_extraction.text import TfidfVectorizer
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
from tensorflow.keras.callbacks import tqdm_callback

# Define constants
MAX_NUM_WORDS = 5000
MAX_SEQUENCE_LENGTH = 100
EMBEDDING_DIM = 50
NUM_EPOCHS = 10
BATCH_SIZE = 64

# Define function to compute class weights
def compute_class_weight_from_dataframe(df):
    class_weights = compute_class_weight(class_weight='balanced', classes=np.unique(df['label']), y=df['label'])
    return dict(enumerate(class_weights))

# Define the vectorizer and tokenizer
vectorizer = TfidfVectorizer()
tokenizer = Tokenizer(num_words=MAX_NUM_WORDS)

# Vectorize the text data
vectorizer.fit(train_set['text'])
X_train = vectorizer.transform(train_set['text'])
X_val = vectorizer.transform(val_set['text'])
X_test = vectorizer.transform(test_df['text'])

# Tokenize the text data
tokenizer.fit_on_texts(train_set['text'])
sequences_train = tokenizer.texts_to_sequences(train_set['text'])
sequences_val = tokenizer.texts_to_sequences(val_set['text'])
sequences_test = tokenizer.texts_to_sequences(test_df['text'])

# Pad the token sequences
X_train_seq = pad_sequences(sequences_train, maxlen=MAX_SEQUENCE_LENGTH)
X_val_seq = pad_sequences(sequences_val, maxlen=MAX_SEQUENCE_LENGTH)
X_test_seq = pad_sequences(sequences_test, maxlen=MAX_SEQUENCE_LENGTH)

# Convert the labels to one-hot encoding
y_train = to_categorical(train_set['label'])
y_val = to_categorical(val_set['label'])

# Compute the class weights
class_weights = compute_class_weight_from_dataframe(train_set)

# Define the model architecture
model = Sequential()
model.add(Embedding(input_dim=MAX_NUM_WORDS, output_dim=EMBEDDING_DIM, input_length=MAX_SEQUENCE_LENGTH))
model.add(LSTM(units=64, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(units=8, activation='softmax'))

# Compile the model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# Train the model
tqdm = tqdm_callback.TqdmCallback(verbose=1)
for epoch in range(NUM_EPOCHS):
    print(f"Epoch {epoch + 1}/{NUM_EPOCHS}")
    history = model.fit(X_train_seq, y_train, batch_size=BATCH_SIZE, epochs=1, validation_data=(X_val_seq, y_val), class_weight=class_weights, callbacks=[tqdm])
    print()
    print("Training Accuracy:", history.history['accuracy'][-1])
    print("Validation Accuracy:", history.history['val_accuracy'][-1])
    print()

# Predict the labels of the test data
y_pred = model.predict(X_test_seq)
y_pred_labels = np.argmax(y_pred, axis=1)

# Save the results to a CSV file
results_df = pd.DataFrame({'id': test_df['id'], 'label': y_pred_labels})
results_df.to_csv('./0317_test_v3.csv', index=False, columns=['id', 'label'])
```
Note that this code assumes that the `train_set`, `val_set`, and `test_df` dataframes are already defined and contain the preprocessed data. The `compute_class_weight_from_dataframe` function is defined to
제공된 데이터를 사용하여 TF-IDF 및 LSTM으로 모델을 훈련하는 코드는 다음과 같습니다.'''python임포트 팬더로 pdimport numpy as npsklearn.utils에서 compute_class_weight를 가져옵니다.sklearn.feature_extraction.text에서 TfidfVectorizer를 가져옵니다.tensorflow.keras.preprocessing.text에서 Tokenizer를 가져옵니다.tensorflow.keras.preprocessing.sequence에서 pad_sequences 가져오기tensorflow.keras.utils에서 to_categorical 가져오기tensorflow.keras.models에서 import Sequentialtensorflow.keras.layers에서 임베딩, LSTM, Dense를 가져옵니다.tensorflow.keras.callbacks에서 tqdm_callback을 가져옵니다.# 상수 정의max_num_words = 5000max_sequence_length = 100embedding_dim = 50num_epochs = 10batch_size = 64# 클래스 가중치를 계산하는 함수 정의def compute_class_weight_from_dataframe(df):    class_weights = compute_class_weight(class_weight='balanced', classes=np.unique(df['label']), y=df['label'])    반환 딕셔너리(열거(class_weights))# 벡터라이저와 토큰라이저 정의하기벡터라이저 = TfidfVectorizer()토큰라이저 = 토큰라이저(num_words=MAX_NUM_WORDS)# 텍스트 데이터 벡터화vectorizer.fit(train_set['text'])X_train = vectorizer.transform(train_set['text'])X_val = vectorizer.transform(val_set['text'])X_test = vectorizer.transform(test_df['text'])# 텍스트 데이터 토큰화tokenizer.fit_on_texts(train_set['text'])sequences_train = tokenizer.texts_to_sequences(train_set['text'])sequences_val = 토큰화기.텍스트_투_시퀀스(val_set['text'])sequences_test = tokenizer.texts_to_sequences(test_df['text'])# 토큰 시퀀스 채우기X_train_seq = pad_sequences(sequences_train, maxlen=MAX_SEQUENCE_LENGTH)X_val_seq = pad_sequences(sequences_val, maxlen=MAX_SEQUENCE_LENGTH)X_test_seq = pad_sequences(sequences_test, maxlen=MAX_SEQUENCE_LENGTH)# 라벨을 원핫 인코딩으로 변환하기y_train = to_categorical(train_set['label'])y_val = to_categorical(val_set['label'])# 클래스 가중치 계산class_weights = compute_class_weight_from_dataframe(train_set)# 모델 아키텍처 정의model = Sequential()model.add(Embedding(input_dim=MAX_NUM_WORDS, output_dim=EMBEDDING_DIM, input_length=MAX_SEQUENCE_LENGTH))model.add(LSTM(units=64, dropout=0.2, recurrent_dropout=0.2))model.add(Dense(units=8, activation='softmax'))# 모델 컴파일model.compile(loss='범주형_크로센트로피', optimizer='adam', metrics=['accuracy'])# 모델 훈련tqdm = tqdm_callback.TqdmCallback(verbose=1)for epoch in range(NUM_EPOCHS):    print(f"에포크 {에포크 + 1}/{NUM_EPOCHS}")    history = model.fit(X_train_seq, y_train, batch_size=BATCH_SIZE, epochs=1, validation_data=(X_val_seq, y_val), class_weight=class_weights, callbacks=[tqdm])    print()    print("훈련 정확도:", history.history['accuracy'][-1])    print("유효성 검사 정확도:", history.history['val_accuracy'][-1])    print()# 테스트 데이터의 레이블을 예측합니다.y_pred = model.predict(X_test_seq)y_pred_labels = np.argmax(y_pred, axis=1)# 결과를 CSV 파일에 저장results_df = pd.DataFrame({'id': test_df['id'], 'label': y_pred_labels})results_df.to_csv('./0317_test_v3.csv', index=False, columns=['id', 'label'])```이 코드는 `train_set`, `val_set`, `test_df` 데이터 프레임이 이미 정의되어 있고 전처리된 데이터를 포함하고 있다고 가정합니다. 데이터프레임에서 `compute_class_weight_from_dataframe` 함수는 다음과 같이 정의됩니다.