我正在使用我的模型进行预测,输出形式为numpy ndarray。所有预测值都经过sigmoid函数处理。现在,我想将numpy数组中的每个值回填到数据框的相应行中,并且添加一个条件:如果值大于0.5,则设为1;否则,如果值小于0.5,则设为0。
到目前为止,我可以读取numpy数组,但似乎无法正确地逐个添加到数据框中。
employers = data_churn# employers = np.array([employers])predictions = model_churn.predict(employers)predictionsemployerPredictions = real_churnemployerPredictions = employerPredictions.rename(index=str, columns={"main_reason": "churned"})employerPredictions.drop(['biztype_knowledge','biztype_field','biztype_creative','PercentEmpChg','PercentChgRevenue','PercentChgPay','amountOfResignations','nb_months_active'], axis=1, inplace=True)if predictions.any() > .5: employerPredictions['predictedChurn'] = 1 employerPredictions['ConfidenceWillChurn %'] = round((predictions[0][0] * 100), 2)else: employerPredictions['predictedChurn'] = 0 employerPredictions['ConfidenceWillNotChurn %'] = round(((1 - predictions[0][0]) * 100), 2)employerPredictions
到目前为止,any方法只是返回第一个预测值,并将其设置为数据框中的所有值
回答:
如何将预测值四舍五入为1和0:
employerPredictions['predictedChurn'] = np.round(predictions).astype(np.int8)#或者你可以直接将其转换为整数employerPredictions['predictedChurn'] = predictions.astype(np.int8)#或者使用np.whereemployerPredictions['predictedChurn'] = np.where(predictions>=0.5,1,0)
至于ConfidenceWillChurn %或ConfidenceWillNotChurn %,我会尝试这样做,但我不确定这是你所问的。
employerPredictions['ConfidenceWillChurn %'] = np.where(predictions>=0.5,predictions*100,np.nan)employerPredictions['ConfidenceWillNotChurn %'] = np.where(predictions<0.5,(1-predictions)*100,np.nan)
我使用了np.nan,但你可以选择其他值来表示条件不满足的情况。我使用了来自numpy的where方法。Pandas也有where方法,但功能有所不同。