Search code examples
pythonscikit-learntypeerrorknn

kNN classification using scikit-learn: TypeError: unsupported operand type(s) for /: 'str' and 'int'


I am trying to predict the name of attribute area which has object as its dtype using longitude and latitude having float as their dtype. I am using kNN algorithm but I am getting this error: TypeError: unsupported operand type(s) for /: 'str' and 'int'

I am confused about the data types in the use of kNN. Could I get any help with understanding what I am doing wrong here? Here's my code:

from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor

# read csv file

df = pd.read_csv("perfectData.csv")
X = np.array(df.ix[:, 13:])
y = np.array(df['area'])

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=90)
y_train=y_train.ravel()
y_test=y_test.ravel()

knn = KNeighborsRegressor(n_neighbors=3)

# fitting the model
knn.fit(X_train, y_train)

# predict the response
pred = knn.predict(X_test)

print(pred)

Solution

  • Just need to remove ravel():

    df = pd.read_csv("perfectData.csv")
    X = np.array(df.ix[:, 13:])
    y = np.array(df['area'])
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
    
    knn=KNeighborsClassifier(n_neighbors=3)
    knn.fit(X_train,y_train)
    prediction=knn.predict(X_test)