noo*_*ert 2 python classification deep-learning keras
我在SO中有与此问题相同的问题。但是,当我尝试使用probas_to_classes()实用程序功能时,**它在当前代码中已经丢失:
"""Numpy-related utilities."""
from __future__ import absolute_import
import numpy as np
def to_categorical(y, num_classes=None):
"""Converts a class vector (integers) to binary class matrix.
E.g. for use with categorical_crossentropy.
# Arguments
y: class vector to be converted into a matrix
(integers from 0 to num_classes).
num_classes: total number of classes.
# Returns
A binary matrix representation of the input.
"""
y = np.array(y, dtype='int').ravel()
if not num_classes:
num_classes = np.max(y) + 1
n = y.shape[0]
categorical = np.zeros((n, num_classes))
categorical[np.arange(n), y] = 1
return categorical
def normalize(x, axis=-1, order=2):
"""Normalizes a Numpy array.
# Arguments
x: Numpy array to normalize.
axis: axis along which to normalize.
order: Normalization order (e.g. 2 for L2 norm).
# Returns
A normalized copy of the array.
"""
l2 = np.atleast_1d(np.linalg.norm(x, order, axis))
l2[l2 == 0] = 1
return x / np.expand_dims(l2, axis)
Run Code Online (Sandbox Code Playgroud)
为了获取与模型输出关联的类,您还有其他选择吗?
小智 5
根据Matias的正确介绍,您应该使用np.argmax函数
但是,由于您通常分批处理输入,因此预测输出很可能是矩阵。您可以通过将argmax分别应用于每个参数来处理它,但是我认为最好使用axis参数。
简而言之:
predictions = model.predict(Input)
classes = np.argmax(predictions, axis=1)
Run Code Online (Sandbox Code Playgroud)
很快,您就可以测试可运行的代码:
from __future__ import print_function
import keras
import numpy as np
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
num_classes = 10
y_test_cat = keras.utils.to_categorical(y_test, num_classes)
print(y_test)
print(np.argmax(y_test_cat,axis=1))
error = y_test-np.argmax(y_test_cat,axis=1)
all_zero = not np.any(error)
print (all_zero)
Run Code Online (Sandbox Code Playgroud)
说明:
首先,所有这些keras和numpy导入和打印功能(因为为什么不这样做)
from __future__ import print_function
import keras
import numpy as np
from keras.datasets import mnist
Run Code Online (Sandbox Code Playgroud)
然后加载mnist数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
Run Code Online (Sandbox Code Playgroud)
之后,使用to_categorical将您的目标类别更改为一种热门编码
y_test_cat = keras.utils.to_categorical(y_test, num_classes)
Run Code Online (Sandbox Code Playgroud)
然后回到您需要的课程:
print(np.argmax(y_test_cat,axis=1))
Run Code Online (Sandbox Code Playgroud)
在此示例中,y_test_cat将是model.predict()函数的输出,因此这就是将其传递给argmax以便从最高概率预测中恢复类的方式。
现在,仅要确保我们的类“预测”与原始类完全相同(因为“预测”已经是正确的类,所以它们应该是原始类),就可以计算出错误。并打印
error = y_test-np.argmax(y_test_cat,axis=1)
all_zero = not np.any(error)
print (all_zero)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9732 次 |
最近记录: |