반응형

UserWarning: X does not have valid feature names, but StandardScaler was fitted with feature names 발생시 해결 방법 입니다.




2024. 3. 20  최초작성




DataFrame으로 StandardScaler 학습한 후, 적용시에는 Numpy 배열을 사용해서 발생한 문제입니다. 

Numpy 배열로 학습시키면 해결됩니다.

 



테스트해봅니다. 데이터프레임을 사용하여 학습한 스케일러를 적용할때 NumPy 배열을 사용해봅니다. 

 

# 학습된 스케일러로 학습 데이터를 스케일링합니다. 

train_scaled = scaler.transform(df_train.values)

 

# 같은 스케일러를 사용하여 테스트 데이터를 스케일링합니다. 

test_scaled = scaler.transform(df_test.values)

 

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler



# 임의의 데이터 생성 (10개 데이터 포인트)
data = {
    'feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'feature2': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
    'feature3': [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]
}

# 데이터를 pandas DataFrame으로 변환
df = pd.DataFrame(data)

# 학습 데이터와 테스트 데이터로 분할
df_train, df_test = train_test_split(df, test_size=0.2, random_state=42)

# StandardScaler 인스턴스 생성
scaler = StandardScaler()

# 학습 데이터에 대해 StandardScaler 학습을 시켜서 평균과 표준편차를 계산합니다.
scaler.fit(df_train)


# 테스트 삼아 Dataframe을 Numpy 배열로 바꾸어 사용해봅니다.

# 학습된 스케일러로 학습 데이터를 스케일링합니다.
train_scaled = scaler.transform(df_train.values)

# 같은 스케일러를 사용하여 테스트 데이터를 스케일링합니다.
test_scaled = scaler.transform(df_test.values)



실행해보면 다음처럼 경고 메시지가 transform 메소드를 사용할때 마다 출력됩니다.

 

/Users/webnautes/miniforge3/envs/tensorflow-dev/lib/python3.10/site-packages/sklearn/base.py:493: UserWarning: X does not have valid feature names, but StandardScaler was fitted with feature names

  warnings.warn(

 

/Users/webnautes/miniforge3/envs/tensorflow-dev/lib/python3.10/site-packages/sklearn/base.py:493: UserWarning: X does not have valid feature names, but StandardScaler was fitted with feature names

  warnings.warn(




NumPy 배열로 바꾸었던 것을 데이터프레임으로 바꾼 다음 코드를 실행하면 경고메시지가 보이지 않게 됩니다.

 

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler



# 임의의 데이터 생성 (10개 데이터 포인트)
data = {
    'feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'feature2': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
    'feature3': [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]
}

# 데이터를 pandas DataFrame으로 변환
df = pd.DataFrame(data)

# 학습 데이터와 테스트 데이터로 분할
df_train, df_test = train_test_split(df, test_size=0.2, random_state=42)

# StandardScaler 인스턴스 생성
scaler = StandardScaler()

# 학습 데이터에 대해 StandardScaler 학습을 시켜서 평균과 표준편차를 계산합니다.
scaler.fit(df_train)


# 학습된 스케일러로 학습 데이터를 스케일링합니다.
train_scaled = scaler.transform(df_train)

# 같은 스케일러를 사용하여 테스트 데이터를 스케일링합니다.
test_scaled = scaler.transform(df_test)





반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts