R_Python

R与Python中的向量化三元运算符

向量化三元运算符能够使代码书写变得更为简洁,以下分别展示R语言与python语言中向量化三元运算符的实现方式:

背景:以logistics regression 回归为背景,sigmod函数的输出结果为[0, 1]区间中的任意实数.为了将该结果转化为二元结果即0或1,需要对sigmod函数输出结果做进一步处理,当sigmod函数输出小于0.5时,二元结果对应为0,当sigmod函数输出大于0.5时,二元结果对应为1,当等于0.5时,可随意给定1或0.

R语言实现方式

R语言中可直接通过ifelse()基础函数实习

sigmod_result <- c(0.5, 0.6, 0.8, 0.4)
binary_result <- ifelse(sigmod_result >= 0.5, 1, 0)
print(binary_result)
## [1] 1 1 1 0

python语言实现方式

python中需要借助numpy库中的where()函数

import numpy as np
sigmod_result = np.array([0.5, 0.6, 0.8, 0.4])
binary_result = np.where(sigmod_result >= 0.5, 1, 0)
print(binary_result)
## [1 1 1 0]

猜你喜欢

转载自blog.csdn.net/zhangxiaojiakele/article/details/80144468
今日推荐