sklearn 을 사용 하여 다 중 분류의 각 유형 에 대해 지표 평가 작업 을 진행 합 니 다.
이 수요 에 대해 우 리 는 sklearn 으로 해결 할 수 있 습 니 다.방법 은 어렵 지 않 습 니 다.필 자 는 여기 서 기록 만 하고 자신 과 독자 가 참고 하도록 제공 합 니 다.
우리 가 모 의 한 데 이 터 는 다음 과 같다.
y_true=['베 이 징','상하 이','청 두','청 두','상하 이','베 이 징','상하 이','청 두','베 이 징','상하 이']
y_pred=['베 이 징','상하 이','청 두','상하 이','청 두','청 두','상하 이','청 두','베 이 징','상하 이']
그 중 ytrue 는 실제 데이터,ypred 는 다 중 분류 후의 아 날로 그 데이터 입 니 다.sklearn.metrics 의 classification 사용 하기report 는 다 분류의 각 유형 에 대해 지표 평 가 를 실현 할 수 있다.
예제 의 Python 코드 는 다음 과 같 습 니 다.
# -*- coding: utf-8 -*-
from sklearn.metrics import classification_report
y_true = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
y_pred = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
t = classification_report(y_true, y_pred, target_names=[' ', ' ', ' '])
print(t)
출력 결 과 는 다음 과 같 습 니 다.
precision recall f1-score support
0.75 0.75 0.75 4
1.00 0.67 0.80 3
0.50 0.67 0.57 3
accuracy 0.70 10
macro avg 0.75 0.69 0.71 10
weighted avg 0.75 0.70 0.71 10
주의해 야 할 것 은 출력 결과 데이터 형식 이 str 이 고 이 출력 결 과 를 사용 하려 면 이 방법 중의 outputdict 매개 변 수 는 True 로 설정 되 어 있 습 니 다.이 출력 결 과 는 다음 과 같 습 니 다.
{‘ ': {‘precision': 0.75, ‘recall': 0.75, ‘f1-score': 0.75, ‘support': 4},
‘ ': {‘precision': 1.0, ‘recall': 0.6666666666666666, ‘f1-score': 0.8, ‘support': 3},
‘ ': {‘precision': 0.5, ‘recall': 0.6666666666666666, ‘f1-score': 0.5714285714285715, ‘support': 3},
‘accuracy': 0.7,
‘macro avg': {‘precision': 0.75, ‘recall': 0.6944444444444443, ‘f1-score': 0.7071428571428572, ‘support': 10},
‘weighted avg': {‘precision': 0.75, ‘recall': 0.7, ‘f1-score': 0.7114285714285715, ‘support': 10}}
confusion 사용matrix 방법 은 이 여러 분류 문제 의 혼동 행렬 을 출력 할 수 있 습 니 다.코드 는 다음 과 같 습 니 다.
from sklearn.metrics import confusion_matrix
y_true = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
y_pred = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
print(confusion_matrix(y_true, y_pred, labels = [' ', ' ', ' ']))
출력 결 과 는 다음 과 같 습 니 다.
[[2 0 1]
[0 3 1]
[0 1 2]]
이 혼 란 스 러 운 행렬 을 그림 으로 그리 기 위해 서 는 다음 과 같은 Python 코드 를 사용 할 수 있 습 니 다.
# -*- coding: utf-8 -*-
# author: Jclian91
# place: Daxing Beijing
# time: 2019-11-14 21:52
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import matplotlib as mpl
# , Mac
zhfont=mpl.font_manager.FontProperties(fname="/Library/Fonts/Songti.ttc")
y_true = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
y_pred = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
classes = [' ', ' ', ' ']
confusion = confusion_matrix(y_true, y_pred)
#
plt.imshow(confusion, cmap=plt.cm.Greens)
indices = range(len(confusion))
plt.xticks(indices, classes, fontproperties=zhfont)
plt.yticks(indices, classes, fontproperties=zhfont)
plt.colorbar()
plt.xlabel('y_pred')
plt.ylabel('y_true')
#
for first_index in range(len(confusion)):
for second_index in range(len(confusion[first_index])):
plt.text(first_index, second_index, confusion[first_index][second_index])
#
plt.show()
생 성 된 혼동 행렬 그림 은 다음 과 같 습 니 다.보충 지식:python Sklearn xgboost 의 2 분류 와 다 분류 실현
2 분류:
train 2.txt 의 형식 은 다음 과 같 습 니 다.
import numpy as np
import pandas as pd
import sklearn
from sklearn.cross_validation import train_test_split,cross_val_score
from xgboost.sklearn import XGBClassifier
from sklearn.metrics import precision_score,roc_auc_score
min_max_scaler = sklearn.preprocessing.MinMaxScaler(feature_range=(-1,1))
resultX = []
resultY = []
with open("./train_data/train2.txt",'r') as rf:
train_lines = rf.readlines()
for train_line in train_lines:
train_line_temp = train_line.split(",")
train_line_temp = map(float, train_line_temp)
line_x = train_line_temp[1:-1]
line_y = train_line_temp[-1]
resultX.append(line_x)
resultY.append(line_y)
X = np.array(resultX)
Y = np.array(resultY)
X = min_max_scaler.fit_transform(X)
X_train,X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.3)
xgbc = XGBClassifier()
xgbc.fit(X_train,Y_train)
pre_test = xgbc.predict(X_test)
auc_score = roc_auc_score(Y_test,pre_test)
pre_score = precision_score(Y_test,pre_test)
print("xgb_auc_score:",auc_score)
print("xgb_pre_score:",pre_score)
다 분류:19 가지 분류 중 정상 0,이상 1~18 가지 가 있다.데이터 형식 은 다음 과 같 습 니 다.
# -*- coding:utf-8 -*-
from sklearn import datasets
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import LinearSVC
from sklearn.cross_validation import train_test_split,cross_val_score
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from xgboost.sklearn import XGBClassifier
import sklearn
import numpy as np
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import precision_score,roc_auc_score
min_max_scaler = sklearn.preprocessing.MinMaxScaler(feature_range=(-1,1))
resultX = []
resultY = []
with open("../train_data/train_multi_class.txt",'r') as rf:
train_lines = rf.readlines()
for train_line in train_lines:
train_line_temp = train_line.split(",")
train_line_temp = map(float, train_line_temp) #
line_x = train_line_temp[1:-1]
line_y = train_line_temp[-1]
resultX.append(line_x)
resultY.append(line_y)
X = np.array(resultX)
Y = np.array(resultY)
#fit_transform(partData) fit, part , 、 、 ( ), partData transform, 、 。。
X = min_max_scaler.fit_transform(X)
# OneHotEncoder Y 19 , 3 000000・・・100
Y = OneHotEncoder(sparse = False).fit_transform(Y.reshape(-1,1))
X_train,X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.2)
model = OneVsRestClassifier(XGBClassifier(),n_jobs=2)
clf = model.fit(X_train, Y_train)
pre_Y = clf.predict(X_test)
test_auc2 = roc_auc_score(Y_test,pre_Y)# auc
print ("xgb_muliclass_auc:",test_auc2)
이상 의 이 편 은 sklearn 을 사용 하여 여러 분류의 각 유형 에 대해 지표 평가 작업 을 하 는 것 이 바로 편집장 이 여러분 에 게 공유 한 모든 내용 입 니 다.여러분 께 참고 가 되 고 저희 도 많이 응원 해 주시 기 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
쓰쿠바 대학의 기계 학습 강좌 : 과제의 파이썬 스크립트 부분을 만들면서 sklearn 공부 (10)지난번 이번에는 이상치가 있는 경우 Youtube의 해설은 제6회(1)55분 30초당 프로그램은 2행 더 강좌에서는 최초의 값을 바꾸고 있는 것 같지만, 하나 추가해도 거기까지 변화는 없을 것 같다. 이것은 실행 결...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.