修正方法: 「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
次の例は、このエラーを実際に解決する方法を示しています。
エラーを再現する方法
sklearnのtrain_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 に変換できません