2017-05-11 15 views
2

먼저 모든 관련 질문을 살펴 보았습니다. 매우 비슷한 문제가 있습니다.
그래서 링크에서 제안을 따랐지만 그 중 누구도 나를 위해 일하지 않았습니다.
나는 또한 오류 메시지를 따르도록 노력 Data Conversion Error while applying a function to each row in pandas Python
Getting deprecation warning in Sklearn over 1d array, despite not having a 1D arraysklearn : sklearn.preprocessing 배열에 대한 DeprecationWarning

, 또한 작동하지 않았다.

코드는 다음과 같습니다

# Importing the libraries 
import numpy as np 
import pandas as pd 

# Importing the dataset 
dataset = pd.read_csv('Position_Salaries.csv') 
X = dataset.iloc[:, 1:2].values 
y = dataset.iloc[:, 2].values 

# avoid DataConversionError 
X = X.astype(float) 
y = y.astype(float) 


## Attempt to avoid DeprecationWarning for sklearn.preprocessing 
#X = X.reshape(-1,1)     # attempt 1 
#X = np.array(X).reshape((len(X), 1)) # attempt 2 
#X = np.array([X])     # attempt 3 


# Feature Scaling 
from sklearn.preprocessing import StandardScaler 
sc_X = StandardScaler() 
sc_y = StandardScaler() 
X = sc_X.fit_transform(X) 
y = sc_y.fit_transform(y) 

# Fitting SVR to the dataset 
from sklearn.svm import SVR 
regressor = SVR(kernel = 'rbf') 
regressor.fit(X, y) 

# Predicting a new result 
y_pred = regressor.predict(sc_X.transform(np.array([6.5]))) 
y_pred = sc_y.inverse_transform(y_pred) 

데이터는 다음과 같습니다

Position,Level,Salary 
Business Analyst,1,45000 
Junior Consultant,2,50000 
Senior Consultant,3,60000 
Manager,4,80000 
Country Manager,5,110000 
Region Manager,6,150000 
Partner,7,200000 
Senior Partner,8,300000 
C-level,9,500000 
CEO,10,1000000 

전체 오류 로그는 다음과 같이 진행됩니다

/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/preprocessing/data.py:586: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample. 
    warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning) 
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/preprocessing/data.py:649: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample. 
    warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning) 
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/preprocessing/data.py:649: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample. 
    warnings.warn(DEPRECATION_MSG_1D, DeprecationWarning) 
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/validation.py:395: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample. 
    DeprecationWarning) 

난 단지 두 번째 사용하고 및 세 번째 열이 있으므로 첫 번째 열에 대해 하나의 핫 인코딩이 필요하지 않습니다. 유일한 문제는 DeprecationWarning입니다.

나는 모든 제안을 시도했지만 그들 중 누구도 일하지 않았습니다.
그래서 도움을 진심으로 감사드립니다.

+1

스택 추적을 포함한 전체 오류 메시지를 게시 할 수 있습니까? –

+0

이렇게하면 알겠습니다. X (데이터 프레임의 레벨 열)에 단일 기능이 있습니까? –

+0

@VivekKumar 질문에 데이터를 게시했습니다. –

답변

3

이것은 이상한 것입니다. Deprecation 경고를 없애기 위해 사용한 코드는 아래에 나와 있으며 StandardScaler()에 맞춰 transform()을 호출하는 방법을 약간 수정했습니다. 이 솔루션은 경고 메시지에 따라 배열을 고쳐 만들고 짜증나게했습니다. 이것이 최선의 방법인지 확실하지 않지만 경고를 제거했습니다.

# Importing the libraries 
import numpy as np 
import pandas as pd 
from io import StringIO 
from sklearn.preprocessing import StandardScaler 

# Setting up data string to be read in as a .csv 
data = StringIO("""Position,Level,Salary 
Business Analyst,1,45000 
Junior Consultant,2,50000 
Senior Consultant,3,60000 
Manager,4,80000 
Country Manager,5,110000 
Region Manager,6,150000 
Partner,7,200000 
Senior Partner,8,300000 
C-level,9,500000 
CEO,10,1000000""") 

dataset = pd.read_csv(data) 

# Importing the dataset 
#dataset = pd.read_csv('Position_Salaries.csv') 

# Deprecation warnings call for reshaping of single feature arrays with reshape(-1,1) 
X = dataset.iloc[:, 1:2].values.reshape(-1,1) 
y = dataset.iloc[:, 2].values.reshape(-1,1) 

# avoid DataConversionError 
X = X.astype(float) 
y = y.astype(float) 

#sc_X = StandardScaler() 
#sc_y = StandardScaler() 
X_scaler = StandardScaler().fit(X) 
y_scaler = StandardScaler().fit(y) 

X_scaled = X_scaler.transform(X) 
y_scaled = y_scaler.transform(y) 

# Fitting SVR to the dataset 
from sklearn.svm import SVR 
regressor = SVR(kernel = 'rbf') 

# One of the warnings called for ravel() 
regressor.fit(X_scaled, y_scaled.ravel()) 

# Predicting a new result 
# The warnings called for single samples to reshaped with reshape(1,-1) 
X_new = np.array([6.5]).reshape(1,-1) 
X_new_scaled = X_scaler.transform(X_new) 
y_pred = regressor.predict(X_new_scaled) 
y_pred = y_scaler.inverse_transform(y_pred) 
+3

가장 좋은 방법입니다. 왜 경고가 존재하는지 알기 위해 [이 질문]을 볼 수 있습니다 (https://stackoverflow.com/questions/41972375/why-does-scikit-learn-demand-different-data-shapes-for-different-regressors/). 42063867 # 42063867) –

+0

감사합니다. 이러한 조작을 요구하는 철학에 대한 언급에 상당히 감사드립니다. –

+3

1 차원 어레이의 경우 이전 scikit-learn은 X와 y를 기반으로 자동 추론하는 데 사용된다는 것을 알 수 있습니다. 그러나 X 만 제공되는 경우 (StandardScaler), 제공된 배열이 n 개의 특징을 갖는 단 하나의 샘플 또는 각각 n 개의 특징을 갖는 n 개의 샘플 인 것으로 추측하는 것이 얼마나 문제가되는지. 그것은 여전히 ​​처리하지만, 다음 버전이 자동으로 유추하지 않으며 오류를 줄 것이므로 공급하기 전에 명시 적으로 변환하도록 경고합니다. –