해결 방법: "sklearn.cross_validation"이라는 모듈이 없습니다.


Python을 사용할 때 발생할 수 있는 오류는 다음과 같습니다.

 ModuleNotFoundError : No module named 'sklearn.cross_validation'

이 오류는 일반적으로 다음 줄을 사용하여 sklearn 에서 train_test_split 함수를 가져오려고 할 때 발생합니다.

 from sklearn. cross_validation import train_test_split

그러나 cross_validation 하위 모듈은 model_selection 하위 모듈로 대체되었으므로 다음 줄을 사용해야 합니다.

 from sklearn. model_selection import train_test_split

다음 예에서는 실제로 이 오류를 해결하는 방법을 보여줍니다.

오류를 재현하는 방법

sklearntrain_test_split 함수를 사용하여 pandas DataFrame을 훈련 세트와 테스트 세트로 분할한다고 가정해 보겠습니다.

train_test_split 함수를 가져오기 위해 다음 코드를 사용한다고 가정해 보겠습니다.

 from sklearn. cross_validation import train_test_split

ModuleNotFoundError : No module named 'sklearn.cross_validation'

train_test_split 함수를 가져오려고 할 때 잘못된 하위 모듈 이름을 사용했기 때문에 오류가 발생합니다.

오류를 수정하는 방법

이 오류를 수정하려면 대신 model_selection 하위 모듈을 사용해야 합니다.

 from sklearn. model_selection import train_test_split

이번에는 어떤 오류도 수신되지 않습니다.

그런 다음 train_test_split 함수를 사용하여 pandas DataFrame을 훈련 및 테스트 세트로 분할할 수 있습니다.

 from sklearn. model_selection import train_test_split
import pandas as pd
import numpy as np

#make this example reproducible
n.p. random . seeds (1)

#create DataFrame with 1000 rows and 3 columns
df = pd. DataFrame ({' x1 ': np.random.randint(30, size=1000),
                   ' x2 ': np.random.randint(12, size=1000),
                   ' y ': np.random.randint(2, size=1000)})

#split original DataFrame into training and testing sets
train, test = train_test_split(df, test_size=0.2, random_state=0)

#view first few rows of each set
print ( train.head ())

     x1 x2 y
687 16 2 0
500 18 2 1
332 4 10 1
979 2 8 1
817 11 1 0

print ( test.head ())

     x1 x2 y
993 22 1 1
859 27 6 0
298 27 8 1
553 20 6 0
672 9 2 1

우리는 오류 없이 train_test_split 함수를 성공적으로 사용했습니다.

추가 리소스

다음 튜토리얼에서는 Python의 다른 일반적인 오류를 수정하는 방법을 설명합니다.

수정방법: 열이 겹치는데 접미사가 지정되지 않음
수정 방법: ‘numpy.ndarray’ 개체에 ‘append’ 속성이 없습니다.
해결 방법: 모든 스칼라 값을 사용하는 경우 인덱스를 전달해야 합니다.
해결 방법: ValueError: float NaN을 int로 변환할 수 없습니다.

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다