TypeError:在Tensorflow中使用自定义指标时,“ Tensor”类型的对象没有len()

时间:2019-02-10 18:40:36

标签: python tensorflow machine-learning keras scikit-learn

我正在使用带有Tensorflow后端的Keras开发用于多类别分类问题(4类)的模型。 y_test的值具有2D格式:

0 1 0 0
0 0 1 0
0 0 1 0

这是我用来计算平衡精度的函数:

def my_metric(targ, predict):
    val_predict = predict
    val_targ = tf.math.argmax(targ, axis=1)
    return metrics.balanced_accuracy_score(val_targ, val_predict)

这是模型:

hidden_neurons = 50
timestamps = 20
nb_features = 18

model = Sequential()

model.add(LSTM(
                units=hidden_neurons,
                return_sequences=True, 
                input_shape=(timestamps,nb_features),
                dropout=0.15
                #recurrent_dropout=0.2
              )
         )

model.add(TimeDistributed(Dense(units=round(timestamps/2),activation='sigmoid')))

model.add(Dense(units=hidden_neurons,
               activation='sigmoid'))


model.add(Flatten())

model.add(Dense(units=nb_classes,
               activation='softmax'))

model.compile(loss="categorical_crossentropy",
              metrics = [my_metric],
              optimizer='adadelta')

运行此代码时,出现此错误:

  

-------------------------------------------------- ---------------------------- TypeError跟踪(最近的呼叫   最后)在()        30 model.compile(loss =“ categorical_crossentropy”,        31个指标= [my_metric],#'accuracy',   ---> 32 Optimizer ='adadelta')

     

〜/ anaconda3 / lib / python3.6 / site-packages / keras / engine / training.py在   编译(自我,优化程序,损失,指标,loss_weights,   sample_weight_mode,weighted_metrics,target_tensors,** kwargs)       449 output_metrics = nested_metrics [i]       450 output_weighted_metrics = nested_weighted_metrics [i]   -> 451 handle_metrics(输出指标)       452 handle_metrics(output_weighted_metrics,weights = weights)       453

     

〜/ anaconda3 / lib / python3.6 / site-packages / keras / engine / training.py在   handle_metrics(指标,权重)       418 metric_result = weighted_metric_fn(y_true,y_pred,       419重量=重量,   -> 420 mask = masks [i])       421       422#追加到self.metrics_names,self.metric_tensors,

     

〜/ anaconda3 / lib / python3.6 / site-packages / keras / engine / training_utils.py   加权(y_true,y_pred,权重,掩码)       402“”“       403#score_array的ndim> = 2   -> 404 score_array = fn(y_true,y_pred)       405如果mask不是None:       406#将蒙版投射到floatX以避免在Theano中进行float64向上投射

     

在my_metric中(目标,预测)        22 val_predict =预测        23 val_targ = tf.math.argmax(targ,axis = 1)   ---> 24个返回指标.balanced_accuracy_score(val_targ,val_predict)        25#返回5        26

     

〜/ anaconda3 / lib / python3.6 / site-packages / sklearn / metrics / classification.py   以balance_accuracy_score(y_true,y_pred,sample_weight,已调整)
  1431 1432“”“   -> 1433 C = confusion_matrix(y_true,y_pred,sample_weight = sample_weight)1434具有   np.errstate(divide ='ignore',invalid ='ignore'):1435
  per_class = np.diag(C)/ C.sum(axis = 1)

     

〜/ anaconda3 / lib / python3.6 / site-packages / sklearn / metrics / classification.py   在confusion_matrix中(y_true,y_pred,标签,sample_weight)       251       252“”“   -> 253 y_type,y_true,y_pred = _check_targets(y_true,y_pred)       254如果y_type不在(“ binary”,“ multiclass”)中:       255提高ValueError(“不支持%s”%y_type)

     

〜/ anaconda3 / lib / python3.6 / site-packages / sklearn / metrics / classification.py   在_check_targets(y_true,y_pred)中        69 y_pred:数组或指标矩阵        70“”“   ---> 71 check_consistent_length(y_true,y_pred)        72 type_true = type_of_target(y_true)        73 type_pred = type_of_target(y_pred)

     

〜/ anaconda3 / lib / python3.6 / site-packages / sklearn / utils / validation.py在   check_consistent_length(* arrays)       229“”“       230   -> 231个长度= [如果X不为None,则为数组中X的_num_samples(X)]       232个唯一性= np.unique(长度)       233如果len(uniques)> 1:

     

〜/ anaconda3 / lib / python3.6 / site-packages / sklearn / utils / validation.py在   (.0)       229“”“       230   -> 231个长度= [如果X不为None,则为数组中X的_num_samples(X)]       232个唯一性= np.unique(长度)       233如果len(uniques)> 1:

     

〜/ anaconda3 / lib / python3.6 / site-packages / sklearn / utils / validation.py在   _num_samples(x)       146返回x.shape [0]       其他147条:   -> 148返回len(x)       149其他:       150 return len(x)

     

TypeError:类型“ Tensor”的对象没有len()

2 个答案:

答案 0 :(得分:2)

您不能在Keras张量上调用sklearn函数。您需要使用Keras的后端函数自己实现该功能,如果使用TF后端,则需要TensorFlow函数。

在各列中获得的as the average of the recall定义为balanced_accuracy_score。检查this link以了解精确度和召回率的实现。对于balanced_accuracy_score,您可以按以下方式实现它:

import keras.backend as K

def balanced_recall(y_true, y_pred):
    """
    Computes the average per-column recall metric
    for a multi-class classification problem
    """ 
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)), axis=0)  
    possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)), axis=0)   
    recall = true_positives / (possible_positives + K.epsilon())    
    balanced_recall = K.mean(recall)
    return balanced_recall

答案 1 :(得分:-1)

尝试:

let res = JSON.parse('[' + "['Date', 'Call (minutes)'],['Date1', 100],['Date2', 1370],['Date3', 660],['Date4', 1030],['Date5', 1000],['Date6', 1170],['Date7', 660]".replaceAll("'", '"') + ']') console.log(res)