【问题标题】:Multi-target having dependent variables as both classification and regression?具有因变量作为分类和回归的多目标?
【发布时间】:2018-03-27 22:40:13
【问题描述】:

我有两个输入作为自变量,我想根据它预测 3 个因变量。

我的 3 个因变量属于 2 个多类别类别,1 个属于连续值。下面是我的目标变量。

typeid_encodedreporttype_encodedlog_count

typeid_encodedreporttype_encoded 属于分类类型,其中每个变量至少有 5 个不同的类别。

log_count 是连续变量。

我用谷歌搜索了很多,我发现只是使用两种不同的模型。但我找不到任何这样做的例子。请发布一些示例以便对我有所帮助?

或者有没有其他方法可以在一个模型中使用神经网络?

我需要一个使用 sci-kit learn 的示例。提前致谢!

【问题讨论】:

    标签: python scikit-learn regression multilabel-classification multitargeting


    【解决方案1】:

    sklearn 中没有为此设计的任何内容,但是您可以使用一些小技巧来制作这样的分类器。

    请注意,这些不一定适合您的问题,很难猜测什么对您的数据有效。

    我首先想到的两个是 Knn 和随机森林,但您基本上可以调整任何多输出回归算法来做这些事情。

    import numpy as np
    from sklearn.ensemble import RandomForestRegressor
    from sklearn.neighbors import NearestNeighbors
    
    # Create some data to look like yours
    n_samples = 100
    n_features = 5
    
    X = np.random.random((n_samples, n_features))
    y_classifcation = np.random.random((n_samples, 2)).round()
    y_regression = np.random.random((n_samples))
    
    y = np.hstack((y_classifcation, y_regression[:, np.newaxis]))
    

    现在我有一个包含两个二进制变量和一个连续变量的数据集

    从 Knn 开始,您也可以使用 KNeighborsRegressor 来执行此操作,但我觉得这更好地说明了解决方案

    # use an odd number to prevent tie-breaks
    nn = NearestNeighbors(n_neighbors=5)
    nn.fit(X, y)
    
    idxs = nn.kneighbors(X, return_distance=False)
    # take the average of the nearest neighbours to get the predictions
    y_pred = y[idxs].mean(axis=1)
    # all predictions will be continous so just round the continous ones
    y_pred[:, 2] = y_pred[:, 2].round()
    

    现在我们的y_pred 是分类和回归的预测向量。所以现在让我们看一个随机森林。

    # use an odd number of trees to prevent predictions of 0.5
    rf = RandomForestRegressor(n_estimators=11)
    rf.fit(X, y)
    y_pred = rf.predict(X)
    
    # all predictions will be continous so just round the continous ones
    y_pred[:, 2] = y_pred[:, 2].round()
    

    我会说这些“黑客”是相当合理的,因为它们与这些算法的分类设置的工作方式相差不远。

    如果你有一个热编码的多类问题,那么不要像我上面所做的那样将概率四舍五入到二进制类,你需要选择概率最高的类。你可以很简单地使用这样的东西来做到这一点

    n_classes_class1 = 3
    n_classes_class2 = 4
    y_pred_class1 = np.argmax(y_pred[:, :n_classes_class1], axis=1)
    y_pred_class2 = np.argmax(y_pred[:, n_classes_class1:-1], axis=1)
    

    【讨论】:

    • 其实我的两个分类变量,我已经转换成labelencoders了。根据您上面的示例,我了解所有预测值都是连续的。它怎么能给出两个分类和一个连续的。有什么解决方法吗?我尝试过使用神经网络,它给了我所有 3 个连续的预测,这是我不想要的
    • 在许多分类算法中,输出最初是连续的,然后将其转换为分类,类似于我上面所做的。对于神经网络,这是使用 softmax 函数进行转换的,但是在这里我只是选择概率最高的类。我现在将在答案的末尾添加一些内容,以帮助解决多类问题。
    • 当然。谢谢!另外,如果可能的话,您能否用一些输入和输出值解释上面的代码。我明白了一点,但不完全:)
    • 我的代码中有示例数据(随机生成),如果您复制并粘贴代码并运行它,您将能够自己查看它。我建议您使用自己的数据来更好地理解它。
    猜你喜欢
    • 2018-07-13
    • 2018-02-06
    • 2018-07-19
    • 1970-01-01
    • 2020-05-20
    • 2020-11-22
    • 2011-02-09
    • 2021-07-29
    • 2021-05-14
    相关资源
    最近更新 更多