我执行下面的代码,我希望第二个图中的数字是百分比格式,具有两位数的精度(0.3333 - > 33.33%)。我已经尝试了大量不同的版本,我在数组上的lambda函数中使用' {%,。2%}' .format(),但我并没有完全得到它。所有输入都是适用的!
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn import datasets
%matplotlib inline
iris = datasets.load_iris()
x = iris['data']
y = iris['target']
x = iris_x[:, :2]
clf_tree = DecisionTreeClassifier(random_state = 1)
fit_clf = clf_tree.fit(x, y)
y_pred_proba = fit_clf.predict_proba(x)
y_pred = fit_clf.predict(x)
conf_mat = confusion_matrix(y_true = y, y_pred = y_pred)
fig, ax = plt.subplots(figsize = (15, 9))
ax.matshow(conf_mat, cmap = plt.cm.Blues, alpha = 0.3)
for i in range(conf_mat.shape[0]):
for j in range(conf_mat.shape[1]):
ax.text(x = j, y = i,
s = conf_mat[i, j],
va = 'center',
ha = 'center')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.show()
conf_mat_prc = conf_mat/len(y)
fig, ax = plt.subplots(figsize = (15, 9))
ax.matshow(conf_mat_prc, cmap = plt.cm.Blues, alpha = 0.3)
for i in range(conf_mat_prc.shape[0]):
for j in range(conf_mat_prc.shape[1]):
ax.text(x = j, y = i,
s = conf_mat_prc[i, j],
va = 'center',
ha = 'center')
plt.xlabel('Predicted % dist')
plt.ylabel('Actual % dist')
plt.show()
非常感谢,
- swepab
答案 0 :(得分:0)
您的代码中至少存在两个问题:
line 14
中的x[:, :2]
是什么?我认为您的意思是iris_x[:, :2]
而不是conf_mat_prc
conf_mat_prc = conf_mat/float(len(y))
应该定义为conf_mat_prc = conf_mat/len(y)
而不是str(round(conf_mat_prc[i, j]*100,precision)) + "%"
来获取浮点而不是0(int)。
最后,对于第二个图(第48行),使用import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn import datasets
from sklearn.metrics import confusion_matrix
# %matplotlib inline
iris = datasets.load_iris()
x = iris['data']
y = iris['target']
x = x[:, :2]
clf_tree = DecisionTreeClassifier(random_state = 1)
fit_clf = clf_tree.fit(x, y)
y_pred_proba = fit_clf.predict_proba(x)
y_pred = fit_clf.predict(x)
conf_mat = confusion_matrix(y_true = y, y_pred = y_pred)
fig, ax = plt.subplots(figsize = (15, 9))
ax.matshow(conf_mat, cmap = plt.cm.Blues, alpha = 0.3)
for i in range(conf_mat.shape[0]):
for j in range(conf_mat.shape[1]):
ax.text(x = j, y = i,
s = conf_mat[i, j],
va = 'center',
ha = 'center')
plt.xlabel('Predicted')
plt.ylabel('Actual')
plt.show()
conf_mat_prc = conf_mat/float(len(y))
fig, ax = plt.subplots(figsize = (15, 9))
ax.matshow(conf_mat_prc, cmap = plt.cm.Blues, alpha = 0.3)
precision = 2
for i in range(conf_mat_prc.shape[0]):
for j in range(conf_mat_prc.shape[1]):
ax.text(x = j, y = i,
s = str(round(conf_mat_prc[i, j]*100,precision)) + "%",
va = 'center',
ha = 'center')
plt.xlabel('Predicted % dist')
plt.ylabel('Actual % dist')
plt.show()
,其中precision定义浮点数。
这是新代码:
{{1}}
这是新的第二张图: