Low Validation and Test Accuracy with Random Forest on ECG Data

I’m working on a project involving ECG data classification using a Random Forest model. Unfortunately, my model’s performance is significantly lower than expected, and I’m struggling to understand why.

Here are the details:
my data organisation:

each folder for classes contains csv file ( 13 columns)
Validation Accuracy: 0.22705314009661837

Test Accuracy: 0.1746987951807229
As you can see, the performance metrics are quite poor. Here is the code I used to train and evaluate the model:

import os
import numpy as np
import pandas as pd

def load_data(folder):
    X = []
    Y = []
    classes = [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]
    
    for class_name in classes:
        class_path = os.path.join(folder, class_name)
        for file_name in os.listdir(class_path):
            if file_name.endswith('.csv'):
                file_path = os.path.join(class_path, file_name)
                try:
                    data = pd.read_csv(file_path)
                    X.append(data.values)  # Ajouter les données du fichier
                    Y.append(class_name)   # Ajouter le nom de la classe pour ce fichier
                except Exception as e:
                    print(f"Error reading {file_path}: {e}")
    
    return X, Y
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.preprocessing import OneHotEncoder
"""
def load_data(folder, samples_per_class=250):
    X = []
    Y = []
    classes = [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]
    
    for class_name in classes:
        class_path = os.path.join(folder, class_name)
        files = [f for f in os.listdir(class_path) if f.endswith('.csv')]
        files_to_load = min(samples_per_class, len(files))
        selected_files = np.random.choice(files, size=files_to_load, replace=False)
        for file_name in selected_files:
            file_path = os.path.join(class_path, file_name)
            try:
                data = pd.read_csv(file_path)
                X.append(data.iloc[:, 1:].values)  # Ajouter les données du fichier
                Y.append(class_name)   # Ajouter le nom de la classe pour ce fichier
            except Exception as e:
                print(f"Error reading {file_path}: {e}")
    
    return X, Y
    """
# y encoder
def encode_labels(y_train, y_valid, y_test):
    ohe = OneHotEncoder(sparse=False)
    y_train = np.array(y_train).reshape(-1, 1)
    y_valid = np.array(y_valid).reshape(-1, 1)
    y_test = np.array(y_test).reshape(-1, 1)
    y_train_enc = ohe.fit_transform(y_train)
    y_valid_enc = ohe.transform(y_valid)
    y_test_enc = ohe.transform(y_test)
    return y_train_enc, y_valid_enc, y_test_enc, ohe

print("loading data")
# Charger les données
X_train, y_train = load_data(trainFolder)
X_valid, y_valid = load_data(validFolder)
X_test, y_test = load_data(testFolder)

print("encoding labels")
# Encoder les étiquettes de classe
y_train, y_valid, y_test, ohe = encode_labels(y_train, y_valid, y_test)

# Convertir les listes en arrays NumPy si nécessaire
X_train = np.array(X_train)
X_valid = np.array(X_valid)
X_test = np.array(X_test)

# Flatten the target labels if they are one-hot encoded
y_train_flat = y_train.argmax(axis=1)
y_valid_flat = y_valid.argmax(axis=1)
y_test_flat = y_test.argmax(axis=1)



save_args = {
    'X_train': X_train.astype('float32'),
    'X_valid': X_valid.astype('float32'),
    'X_test':  X_test.astype('float32'),
    'y_train': y_train_flat.astype('float32'), 
    'y_valid': y_valid_flat.astype('float32'),
    'y_test':  y_test_flat.astype('float32')
}


print("training")
# Flatten the feature data
X_train_2d = X_train.reshape(X_train.shape[0], -1)
X_valid_2d = X_valid.reshape(X_valid.shape[0], -1)
X_test_2d = X_test.reshape(X_test.shape[0], -1)

# Initialize and train the Random Forest classifier
rf_classifier = RandomForestClassifier(n_estimators=100, criterion="gini",random_state=42)
rf_classifier.fit(X_train_2d, y_train_flat)

# Make predictions on the validation set
valid_predictions = rf_classifier.predict(X_valid_2d)

# Evaluate accuracy on the validation set
valid_accuracy = accuracy_score(y_valid_flat, valid_predictions)
print("Validation Accuracy:", valid_accuracy)

# Confusion matrix for validation set
valid_conf_matrix = confusion_matrix(y_valid_flat, valid_predictions)
print("Validation Confusion Matrix:n", valid_conf_matrix)

# Make predictions on the test set
test_predictions = rf_classifier.predict(X_test_2d)

# Evaluate accuracy on the test set
test_accuracy = accuracy_score(y_test_flat, test_predictions)
print("Test Accuracy:", test_accuracy)

# Confusion matrix for test set
test_conf_matrix = confusion_matrix(y_test_flat, test_predictions)
print("Test Confusion Matrix:n", test_conf_matrix)

Any advice on how to improve the performance of my Random Forest model on this ECG dataset would be greatly appreciated.
Thanks in advance for your help!
Best regards,

New contributor

MEJRI Rawaa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật