Error in predicting Float values in kNN in python - python

I am new to this KNN I want to ask a simple question I have written a code in python of KNN. when I used fingerprints.csv that contains decimals number my code gives me an error. I assume that it doesn't predict float values. so I used another CSV that has similar data but no decimal value my code worked well.
what changes I should make so my code will be able to predict floats.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
import pickle
import glob
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score
from sklearn.multioutput import MultiOutputClassifier
# training/validation set
train_set = pd.read_csv("1.csv")
# test set
test_set = pd.read_csv("testing data.csv")
X = train_set.iloc[:,0:3].values #RSSI
Y = train_set.iloc[:,3:5].values #X,Y (OUTCOME)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)
#print(X_train.shape)
#print(X_test)
#print(Y_train.shape)
#print(Y_test)
sc = StandardScaler() #feature scalin
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
#print(Y_train)
aa =(X_train[:,0]+X_train[:,1]+X_train[:,2])/3
print(aa)
#import math
#print(math.sqrt(len(Y_test)))
knn = KNeighborsClassifier(n_neighbors=1, metric='euclidean')
classifier = MultiOutputClassifier(knn, n_jobs=-2)
classifier.fit(X_train, Y_train)
# Save the trained model as a pickle string.
saved_model = pickle.dumps (classifier)
# Load the pickled model
classifier_from_pickle = pickle.loads(saved_model)
# Use the loaded pickled model to make predictions
classifier_from_pickle.predict(X_test)
Y_pred = classifier.predict(X_test)
print(Y_pred)
a = Y_test[:,0] # actual labels
b = Y_pred[:,0] # predicted labels
acc = len([a[i] for i in range(0, len(a)) if a[i] == b[i]]) / len(a)
a = Y_test[:,1] # actual labels
b = Y_pred[:,1] # predicted labels
accu = len([a[i] for i in range(0, len(a)) if a[i] == b[i]]) / len(a)
accuracy=acc+accu
print("Accuracy: ",accuracy)
#Model Validation on Validation.csv
X = test_set.iloc[:,0:3].values #RSSI
#print(X)
X_test = sc.transform(X)
#print(X_test)
aa =(X_test[:,0]+X_test[:,1]+X_test[:,2])/3
print(aa)
# Use the loaded pickled model to make predictions on Validate Dataset
classifier_from_pickle.predict(X_test)
Y_pred = classifier.predict(X_test)
print(Y_pred)
the error
Traceback (most recent call last):
File "d:/knnn code/knn2.py", line 53, in <module>
classifier.fit(X_train, Y_train)
File "C:\Users\92316\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\multioutput.py", line 359, in fit
super().fit(X, Y, sample_weight)
File "C:\Users\92316\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\multioutput.py", line 156, in fit
check_classification_targets(y)
File "C:\Users\92316\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\utils\multiclass.py", line 169, in check_classification_targets
raise ValueError("Unknown label type: %r" % y_type)
ValueError: Unknown label type: 'continuous-multioutput'
thanks in advance for your time and help.

Related

Make a function that loads the model, takes a vector of data, and makes a prediction

I'm trying to train a regression model on the Boston Housing dataset and save the model to disk and then make the Title function.
Below code's is working
import pandas as pd
import numpy as np
import os
import pickle
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from joblib import dump, load
boston = load_boston()
boston_df = pd.DataFrame(boston.data, columns = boston.feature_names)
y = pd.DataFrame(boston.target)
x_train, x_test, y_train, y_test = train_test_split(boston_df, y, test_size = 0.2, random_state=17)
model = LinearRegression()
model.fit(x_train, y_train)
y_predict = model.predict(x_test)
mse = mean_squared_error(y_test, y_predict)
with open('model.pkl', 'wb') as file:
pickle.dump(model, file)
del model
with open('model.pkl', 'rb') as file:
lin_model = pickle.load(file)
But when I add it's supossed to work
def predicting(x):
x = pd.DataFrame(x)
with open('model.pkl', 'rb') as file:
lin_model = pickle.load(file)
pred = lin_model.predict(x)
print(pred)
But I don't know what structure does 'x' need for this function to work!
x = [1,2,4,5,6,3,5,6,7,3,5,6,4]
predicting(x)
Like above it says ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 13 is different from 1)
Please help?
import pandas as pd
import numpy as np
import os
import pickle
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from joblib import dump, load
from sklearn.datasets import make_blobs
boston = load_boston()
boston_df = pd.DataFrame(boston.data, columns = boston.feature_names)
y = pd.DataFrame(boston.target)
x_train, x_test, y_train, y_test = train_test_split(boston_df, y, test_size = 0.2, random_state=17)
model = LinearRegression()
model.fit(x_train, y_train)
y_predict = model.predict(x_test)
mse = mean_squared_error(y_test, y_predict)
with open('model.pkl', 'wb') as file:
pickle.dump(model, file)
del model
x, _ = make_blobs(n_samples=3, centers=2, n_features=13, random_state=1)
def preficting(x):
with open('model.pkl', 'rb') as file:
lin_model = pickle.load(file)
ynew = lin_model.predict(x)
for i in range(len(x)):
print("X=%s, Predicted=%s" % (x[i], ynew[i]))
preficting(x)
Without the final print but I saw it and thought that was pretty, but here's what I needed! :)

Inconsistent number of samples error in SVM accuracy calculation

I'm trying to calculate the accuracy score, of a SVM using Laplacian kernel (as a pre-computed kernel). However, I'm getting the error as below when I try to calculate the accuracy score.
My code :
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
from sklearn.metrics.pairwise import laplacian_kernel
#Load the iris data
iris_data = load_iris()
#Split the data and target
X = iris_data.data
y = iris_data.target
#Convert X and y to a numpy array
X = np.array(X)
y = np.array(y)
#Perform train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=42, shuffle=True)
#Using Laplacian kernel - https://scikit-learn.org/stable/modules/metrics.html#laplacian-kernel
K = np.array(laplacian_kernel(X_train, gamma=.5))
svm = SVC(kernel='precomputed').fit(K, np.ravel(y_train))
pred_y = svm.predict(K)
#Print accuracy score - here is where the error is happening.
print(accuracy_score(y_test, pred_y))
When I run this code, I'm getting error as shown below :
Traceback (most recent call last):
File "/Users/user/Desktop/Research/Src/Laplace.py", line 36, in <module>
print(accuracy_score(y_test, pred_y))
File "/Users/user/miniforge3/envs/user_venv/lib/python3.8/site-packages/sklearn/utils/validation.py", line 63, in inner_f
return f(*args, **kwargs)
File "/Users/user/miniforge3/envs/user/lib/python3.8/site-packages/sklearn/metrics/_classification.py", line 202, in accuracy_score
y_type, y_true, y_pred = _check_targets(y_true, y_pred)
File "/Users/user/miniforge3/envs/user/lib/python3.8/site-packages/sklearn/metrics/_classification.py", line 83, in _check_targets
check_consistent_length(y_true, y_pred)
File "/Users/user/miniforge3/envs/user/lib/python3.8/site-packages/sklearn/utils/validation.py", line 262, in check_consistent_length
raise ValueError("Found input variables with inconsistent numbers of"
ValueError: Found input variables with inconsistent numbers of samples: [45, 105]
So how can I resolve this error?
You calculated pred_y using your train inputs which has 105 elements and y_test has 45 elements.
You need to add a step:
#user3046211's code
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score
from sklearn.svm import SVC
from sklearn.metrics.pairwise import laplacian_kernel
#Load the iris data
iris_data = load_iris()
#Split the data and target
X = iris_data.data
y = iris_data.target
#Convert X and y to a numpy array
X = np.array(X)
y = np.array(y)
#Perform train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=42, shuffle=True)
#Using Laplacian kernel - https://scikit-learn.org/stable/modules/metrics.html#laplacian-kernel
K = np.array(laplacian_kernel(X_train, gamma=.5))
svm = SVC(kernel='precomputed').fit(K, np.ravel(y_train))
pred_y = svm.predict(K)
#Print accuracy score - here is where the error is happening.
print(accuracy_score(y_test, pred_y))
# NEW CODE STARTS HERE
K_test = np.array(laplacian_kernel(X=X_test,Y=X_train, gamma=.5))
pred_y_test = svm.predict(K_test)
print(accuracy_score(y_test, pred_y_test))

NameError: name 'fit_classifier' is not defined

I'm trying to make a text classifier
import pandas as pd
import pandas
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.multiclass import OneVsOneClassifier
from sklearn.svm import SVC
from sklearn import cross_validation
from sklearn.metrics import confusion_matrix
dataset = pd.read_csv('data.csv', encoding = 'utf-8')
data = dataset['text']
labels = dataset['label']
X_train, X_test, y_train, y_test = train_test_split (data, labels, test_size = 0.2, random_state = 0)
count_vector = CountVectorizer()
tfidf = TfidfTransformer()
classifier = OneVsOneClassifier(SVC(kernel = 'linear', random_state = 84))
train_counts = count_vector.fit_transform(X_train)
train_tfidf = tfidf.fit_transform(train_counts)
classifier.fit(train_tfidf, y_train)
test_counts = count_vector.transform(X_test)
test_tfidf = tfidf.transform(test_counts)
classifier.predict(test_tfidf)
fit_classifier(X_train, y_train)
predicted = predict(X_test)
print("confusion matrix")
print(confusion_matrix(X_test, predicted, labels = labels))
print("cross validation")
test_counts = count_vector.fit_transform(data)
test_tfidf = tfidf.fit_transform(test_counts)
scores = cross_validation.cross_val_score(classifier, test_tfidf, labels, cv = 10)
print(scores)
print("Accuracy: {} +/- {}".format(scores.mean(), scores.std() * 2))
But I have the following error and I can not understand.
Traceback (most recent call last):
File "classificacao.py", line 37, in
fit_classifier(X_train, y_train)
NameError: name 'fit_classifier' is not defined
But fit is not always defined by default?
you are calling a non existing function:
fit_classifier(X_train, y_train)
to fit your classifier you would use
classifier.fit(X_train, y_train)
instead.
You'll get the same error when trying to predict your test data.
You need to change
predicted = predict(X_test)
to
predicted = classifier.predict(X_test)
Your Confusionmatrix should get your labels, not your test data:
print(confusion_matrix(y_test, predicted, labels = labels))

ValueError: cannot use sparse input in 'SVC' trained on dense data

I'm trying to run my classifier but I get this error
import pandas
import numpy as np
import pandas as pd
from sklearn import svm
from sklearn.svm import SVC
from sklearn import cross_validation
from sklearn.metrics import confusion_matrix
from sklearn.multiclass import OneVsOneClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_fscore_support as score
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
dataset = pd.read_csv('all_topics_limpo.csv', encoding = 'utf-8')
data = pandas.get_dummies(dataset['verbatim_corrige'])
labels = dataset['label']
X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size = 0.2, random_state = 0)
count_vector = CountVectorizer()
tfidf = TfidfTransformer()
classifier = OneVsOneClassifier(SVC(kernel = 'linear', random_state = 100))
#classifier = LogisticRegression()
train_counts = count_vector.fit_transform(X_train)
train_tfidf = tfidf.fit_transform(train_counts)
classifier.fit(X_train, y_train)
test_counts = count_vector.transform(X_test)
test_tfidf = tfidf.transform(test_counts)
predicted = classifier.predict(test_tfidf)
predicted = classifier.predict(X_test)
print("confusion matrix")
print(confusion_matrix(y_test, predicted, labels = labels))
print("F-score")
print(f1_score(y_test, predicted))
print(precision_score(y_test, predicted))
print(recall_score(y_test, predicted))
print("cross validation")
test_counts = count_vector.fit_transform(data)
test_tfidf = tfidf.fit_transform(test_counts)
scores = cross_validation.cross_val_score(classifier, test_tfidf, labels, cv = 10)
print(scores)
print("Accuracy: {} +/- {}".format(scores.mean(), scores.std() * 2))
My output error:
ValueError: cannot use sparse input in 'SVC' trained on dense data
I can not execute my code because of this problem and I am not understanding anything of what is happening.
all output error
Traceback (most recent call last):
File "classification.py", line 42, in
predicted = classifier.predict(test_tfidf)
File "/usr/lib/python3/dist-packages/sklearn/multiclass.py", line 584, in predict
Y = self.decision_function(X)
File "/usr/lib/python3/dist-packages/sklearn/multiclass.py", line 614, in decision_function
for est, Xi in zip(self.estimators_, Xs)]).T
File "/usr/lib/python3/dist-packages/sklearn/multiclass.py", line 614, in
for est, Xi in zip(self.estimators_, Xs)]).T
File "/usr/lib/python3/dist-packages/sklearn/svm/base.py", line 548, in predict
y = super(BaseSVC, self).predict(X)
File "/usr/lib/python3/dist-packages/sklearn/svm/base.py", line 308, in predict
X = self._validate_for_predict(X)
File "/usr/lib/python3/dist-packages/sklearn/svm/base.py", line 448, in _validate_for_predict
% type(self).name)
ValueError: cannot use sparse input in 'SVC' trained on dense data
You get this error because your training & test data are not of the same kind: while you train in your initial X_train set:
classifier.fit(X_train, y_train)
you are trying to get predictions from a dataset which has undergone count vectorization & tf-idf transormations first:
predicted = classifier.predict(test_tfidf)
It is puzzling why you choose to do so, why you nevertheless compute train_counts and train_tfidf (you don't seem to actually use them anywhere), and why you are also trying to redefine predicted as classifier.predict(X_test) immediately afterwards. Normally, changing your training line to
classifier.fit(train_tfidf, y_train)
and getting rid of your second predicted definition should work OK...
you can use this code :
test_tfidf = tfidf.transform(test_counts).toarray()
befor you want to predict your model and after :
predicted = classifier.predict(test_tfidf)
just do this simple code
nice job

How to fix NameError: name 'X_train' is not defined?

I am running the [code] of multi-label classification1.how to fix the NameError that the "X_train" is not defined.the python code is given below.
import scipy
from scipy.io import arff
data, meta = scipy.io.arff.loadarff('./yeast/yeast-train.arff')
from sklearn.datasets import make_multilabel_classification
# this will generate a random multi-label dataset
X, y = make_multilabel_classification(sparse = True, n_labels = 20,
return_indicator = 'sparse', allow_unlabeled = False)
# using binary relevance
from skmultilearn.problem_transform import BinaryRelevance
from sklearn.naive_bayes import GaussianNB
# initialize binary relevance multi-label classifier
# with a gaussian naive bayes base classifier
classifier = BinaryRelevance(GaussianNB())
# train
classifier.fit(X_train, y_train)
# predict
predictions = classifier.predict(X_test)
from sklearn.metrics import accuracy_score
accuracy_score(y_test,predictions)
You forgot to split the dataset into train and test sets.
Import the library
from sklearn.model_selection import train_test_split
Add this line before classifier.fit()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
X_train does not exist, you have to split between train and test :
from sklearn.preprocessing import StandardScaler
s =StandardScaler()
X_train = s.fit_transform(X_train)
X_test = s.fit_transform(X_test)

Categories