Machine Learning Python

Asked

Viewed 583 times

0

I started in the course of Machine Learning and in exercise I’m having difficulty because it is returning me a silly error that I can not find the solution.

from sklearn.model_selection import train_test_split #função de dividir dados de treino e teste
from sklearn.neighbors import KNeighborsClassifier
import numpy as np

knn = KNeighborsClassifier(n_neighbors = 1)

X_train, X_test, y_train, y_test = train_test_split(X1, Y1, random_state = 1)

knn.fit(X_train, y_train)

inserir a descrição da imagem aqui

3 answers

4

You need to have the data before you separate it into the training and test data.

You are passing X1 and Y1 data as function parameter but the data has not been defined yet.

See the example below:

>>> import numpy as np
>>> from sklearn.model_selection import train_test_split
>>> X1, Y1 = np.arange(10).reshape((5, 2)), range(5)
>>> X1
array([[0, 1],
       [2, 3],
       [4, 5],
       [6, 7],
       [8, 9]])
>>> list(Y1)
[0, 1, 2, 3, 4]

>>> X_train, X_test, y_train, y_test = train_test_split(X1, Y1, test_size=0.33, random_state=42)

1

You need to import the data by separating the training and test data.

EX:

df = pd.read_csv('Data/seuarquivo.csv')

previsores = df.iloc[:,0:10].values

classe = df.iloc[:,4].values

0

#Acho que faltou voce importar os dados, vamos lembrar abaixo usando o pandas:

import pandas as pd

In place of the one in quotes you place your dataframe with the path where it is

df = pd.read_csv('Data/your.csv file')

Separating here what will be used to predict and what will be used as a class or the teacher

previsors = df.iloc[:,0:4]. values

class = df.iloc[:,4]. values

Now yes I will separate here the test data and training data

from sklearn.model_selection import train_test_split

X_train,X_test,y_train,y_test = train_test_split(predictors,classes, test_size = 0.25, random_state=0)

Now I’m going to import the Knn algorithm you’re using

from sklearn.Neighbors import Kneighborsclassifier

I define here some hyperparameters

classifier = Kneighborsclassifier(n_neighbors=5, Metric='Minkowski', p=2)

I train the model

classifier.fit(X_train, y_train)

I test the model with my test base, to see if the model is good

predictions = classifier.Predict(X_test)

And now I’m gonna check to see if you’re okay with some metrics

from sklearn.Metrics import confusion_matrix, accuracy_score accuracy_score(X_test, y_test) matrix = confusion_matrix(X_test, y_test)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.