Classification metrics can't handle a mix of continuous and multiclass targets

报错情景

今天笔者在使用sklearn的metrics.accuracy_score时遇到
“Classification metrics can’t handle a mix of continuous and multiclass targets”报错,

当时怎么也想不明白哪里错了,label是int型,pred也已经赋值为int型,为什么会有这样的continuous and multiclass targets报错

源码如下

#Evaluate model
def evaluate_model(lin_reg,feature,real_label):
    '''
    This function calculate the accuracy and MSE Error
    If the (pred year - real year), we suppose it is right.
    
    Variables Describe:
    lin_reg:linear regression model
    feature: training feature
    real_lable:ture labels
    '''
    y_pred=list(lin_reg.predict(feature))
    y_real=list(real_label)
    #To avoid "Classification metrics can't handle a mix of continuous and multiclass targets" Error
    for i in range(len(y_pred)-1):
        #If the (pred year - real year), we suppose it is right.
        y_pred[i]=(y_real[i] if abs(y_pred[i]-y_real[i])<=5 else y_pred[i]) 

    acc_score=sklearn.metrics.accuracy_score(y_pred,y_real)
    mse_err=sklearn.metrics.mean_squared_error(y_pred,fy_real)
    return acc_score, mse_err

既然目标数据类型没有错,那可能是输入的时候输入了一些“别的东西”。笔者的项目中就是多输入了index,导致accuracy_score不知道怎么办。

解决方法

使用新建的list,单独储存想比较正确率的项.

#Evaluate model
def evaluate_model(lin_reg,feature,real_label):
    '''
    This function calculate the accuracy and MSE Error
    If the (pred year - real year), we suppose it is right.
    
    Variables Describe:
    lin_reg:linear regression model
    feature: training feature
    real_lable:ture labels
    '''
    y_pred=list(lin_reg.predict(feature))
    y_real=list(real_label)
    #To avoid "Classification metrics can't handle a mix of continuous and multiclass targets" Error
    for_class_pred=list()
    for_class_real=list()
    for i in range(len(y_pred)-1):
        #If the (pred year - real year), we suppose it is right.
        y_pred[i]=(y_real[i] if abs(y_pred[i]-y_real[i])<=5 else y_pred[i]) 
        for_class_pred.append(int(y_pred[i]))
        for_class_real.append(int(y_real[i]))
    acc_score=sklearn.metrics.accuracy_score(for_class_pred,for_class_real)
    mse_err=sklearn.metrics.mean_squared_error(for_class_pred,for_class_real)
    return acc_score, mse_err

在稀奇古怪的地方上浪费了好多时间…sklearn的源码又不是那么好读,特此记录。

你可能感兴趣的:(经典机器学习模型,python,bug,算法)