Ich bin neu im maschinellen Lernen und im Scikit-Learn.
Mein Problem:
(Bitte korrigieren Sie jegliche Art von Missverständnis.)
Ich habe einen Datensatz, der ein GROSSER JSON ist. Ich rufe ihn ab und speichere ihn in einer Variable trainList
.
Ich bereite es vor, um damit arbeiten zu können.
Sobald ich das getan habe, beginne ich mit der Klassifizierung:
Code:
Die Variablen, die ich im Moment habe:
trainList #It is a list with all the data of my dataset in JSON form
labelList #It is a list with all the labels of my data
Der größte Teil der Methode:
#I transform the data from JSON form to a numerical one
X=vec.fit_transform(trainList)
#I scale the matrix (don't know why but without it, it makes an error)
X=preprocessing.scale(X.toarray())
#I generate a KFold in order to make cross validation
kf = KFold(len(X), n_folds=10, indices=True, shuffle=True, random_state=1)
#I start the cross validation
for train_indices, test_indices in kf:
X_train=[X[ii] for ii in train_indices]
X_test=[X[ii] for ii in test_indices]
y_train=[listaLabels[ii] for ii in train_indices]
y_test=[listaLabels[ii] for ii in test_indices]
#I train the classifier
trained=qda.fit(X_train,y_train)
#I make the predictions
predicted=qda.predict(X_test)
#I obtain the accuracy of this fold
ac=accuracy_score(predicted,y_test)
#I obtain the confusion matrix
cm=confusion_matrix(y_test, predicted)
#I should calculate the TP,TN, FP and FN
#I don't know how to continue
Wenn Sie zwei Listen mit den vorhergesagten und tatsächlichen Werten haben; Wie es scheint, können Sie sie an eine Funktion übergeben, die TP, FP, TN, FN mit einem der folgenden Werte berechnet:
def perf_measure(y_actual, y_hat):
TP = 0
FP = 0
TN = 0
FN = 0
for i in range(len(y_hat)):
if y_actual[i]==y_hat[i]==1:
TP += 1
if y_hat[i]==1 and y_actual[i]!=y_hat[i]:
FP += 1
if y_actual[i]==y_hat[i]==0:
TN += 1
if y_hat[i]==0 and y_actual[i]!=y_hat[i]:
FN += 1
return(TP, FP, TN, FN)
Ich denke, von hier aus können Sie die Zinssätze für Sie berechnen und andere Kennzahlen wie Spezifität und Sensitivität berechnen.
Für den Fall mit mehreren Klassen finden Sie alles, was Sie brauchen, aus der Verwirrungsmatrix. Wenn Ihre Verwirrungsmatrix beispielsweise so aussieht:
Dann können Sie finden, wonach Sie pro Klasse suchen:
Mit Pandas/Numpy können Sie dies für alle Klassen gleichzeitig tun:
FP = confusion_matrix.sum(axis=0) - np.diag(confusion_matrix)
FN = confusion_matrix.sum(axis=1) - np.diag(confusion_matrix)
TP = np.diag(confusion_matrix)
TN = confusion_matrix.values.sum() - (FP + FN + TP)
# Sensitivity, hit rate, recall, or true positive rate
TPR = TP/(TP+FN)
# Specificity or true negative rate
TNR = TN/(TN+FP)
# Precision or positive predictive value
PPV = TP/(TP+FP)
# Negative predictive value
NPV = TN/(TN+FN)
# Fall out or false positive rate
FPR = FP/(FP+TN)
# False negative rate
FNR = FN/(TP+FN)
# False discovery rate
FDR = FP/(TP+FP)
# Overall accuracy
ACC = (TP+TN)/(TP+FP+FN+TN)
Sie können alle Parameter aus der Verwirrungsmatrix erhalten. Die Struktur der Konfusionsmatrix (die 2X2-Matrix ist) ist wie folgt
TP|FP
FN|TN
So
TP = cm[0][0]
FP = cm[0][1]
FN = cm[1][0]
TN = cm[1][1]
Weitere Details unter https://en.wikipedia.org/wiki/Confusion_matrix
Laut Scikit-Learn-Dokumentation
Per Definition ist eine Verwirrungsmatrix C so, dass C [i, j] gleich der Anzahl von Beobachtungen ist, von denen bekannt ist, dass sie sich in Gruppe i befinden, aber vorhergesagt wurde, dass sie in Gruppe j liegt.
In der binären Klassifizierung ist der Zählwert der wahren Negative also C [0,0], die False Negative ist C [1,0].
CM = confusion_matrix(y_true, y_pred)
TN = CM[0][0]
FN = CM[1][0]
TP = CM[1][1]
FP = CM[0][1]
In der 'metrics'-Bibliothek von scikit-learn gibt es eine confusion_matrix-Methode, die Ihnen die gewünschte Ausgabe gibt.
Sie können jeden gewünschten Klassifizierer verwenden. Hier habe ich die KNighbors als Beispiel verwendet.
from sklearn import metrics, neighbors
clf = neighbors.KNeighborsClassifier()
X_test = ...
y_test = ...
expected = y_test
predicted = clf.predict(X_test)
conf_matrix = metrics.confusion_matrix(expected, predicted)
>>> print conf_matrix
>>> [[1403 87]
[ 56 3159]]
Die Dokumente: http://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html#sklearn.metrics.confusion_matrix
Ich habe eine Version geschrieben, die nur mit numpy funktioniert. Ich hoffe, es hilft Ihnen.
import numpy as np
def perf_metrics_2X2(yobs, yhat):
"""
Returns the specificity, sensitivity, positive predictive value, and
negative predictive value
of a 2X2 table.
where:
0 = negative case
1 = positive case
Parameters
----------
yobs : array of positive and negative ``observed`` cases
yhat : array of positive and negative ``predicted`` cases
Returns
-------
sensitivity = TP / (TP+FN)
specificity = TN / (TN+FP)
pos_pred_val = TP/ (TP+FP)
neg_pred_val = TN/ (TN+FN)
Author: Julio Cardenas-Rodriguez
"""
TP = np.sum( yobs[yobs==1] == yhat[yobs==1] )
TN = np.sum( yobs[yobs==0] == yhat[yobs==0] )
FP = np.sum( yobs[yobs==1] == yhat[yobs==0] )
FN = np.sum( yobs[yobs==0] == yhat[yobs==1] )
sensitivity = TP / (TP+FN)
specificity = TN / (TN+FP)
pos_pred_val = TP/ (TP+FP)
neg_pred_val = TN/ (TN+FN)
return sensitivity, specificity, pos_pred_val, neg_pred_val
Der eine Liner, um echte Positive usw. aus der Verwirrungsmatrix zu bekommen, ist travel it:
from sklearn.metrics import confusion_matrix
y_true = [1, 1, 0, 0]
y_pred = [1, 0, 1, 0]
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
print(tn, fp, fn, tp) # 1 1 1 1
sie können sklearn.metrics.classification_report
wie folgt versuchen:
import sklearn
y_true = [1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0]
y_pred = [1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0]
print sklearn.metrics.classification_report(y_true, y_pred)
ausgabe:
precision recall f1-score support
0 0.80 0.57 0.67 7
1 0.50 0.75 0.60 4
avg / total 0.69 0.64 0.64 11
wenn Sie mehr als eine Klasse in Ihrem Klassifizierer haben, möchten Sie vielleicht pandas-ml in diesem Teil verwenden. Verwirrungsmatrix von Pandas-ml geben detailliertere Informationen. prüfe das
Ich denke, dass beide Antworten nicht völlig richtig sind. Nehmen wir beispielsweise an, wir haben die folgenden Arrays:
y_istual = [1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0]
y_predic = [1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0]
Wenn Sie die Werte für FP, FN, TP und TN manuell berechnen, sollten diese wie folgt aussehen:
FP: 3 FN: 1TP: 3TN: 4
Wenn wir jedoch die erste Antwort verwenden, werden die Ergebnisse wie folgt angegeben:
FP: 1 FN: 3TP: 3TN: 4
Sie sind nicht korrekt, da in der ersten Antwort False Positive dort sein sollte, wo der Istwert 0 ist, der Vorhersagewert jedoch 1 ist, nicht das Gegenteil. Gleiches gilt für False Negative.
Wenn wir die zweite Antwort verwenden, werden die Ergebnisse wie folgt berechnet:
FP: 3 FN: 1TP: 4TN: 3
Echte Positive und Echte Negative Zahlen sind nicht korrekt, sie sollten entgegengesetzt sein.
Bin ich mit meinen Berechnungen richtig? Bitte lassen Sie mich wissen, wenn mir etwas fehlt.
Ich habe einige der Antworten ausprobiert und festgestellt, dass sie nicht funktionieren.
Das funktioniert bei mir:
from sklearn.metrics import classification_report
print(classification_report(y_test, predicted))