Scipy库里的众数函数不严谨,我把它重构了。

关于这个众数函数

python 复制代码
from scipy import stats
result2 = stats.mode(Tensor)

我重构后没有那个心情去和numpy原生库函数互怼,不过可以在用numpy计算众数的时候,调用我重构的这个函数。我在阅读编程书时,书上说numpy没有众数函数,观察scipy的众数函数发现的问题,我还以为是自己逻辑错误了,然后经过验证,我的数学逻辑没有问题,那就是scipy的函数出问题了,我就选择把它重构了成了一个Mode_Calculation.py文件【模块】。Codes:

python 复制代码
from collections import Counter
def Find_Mode(Array):
    vector_translate = Array.ravel()
    counts = Counter(vector_translate)
    if max(counts.values()) == 1 or len(set(vector_translate)) == 1:return None
    else:
        mode_ls = [k for k,v in counts.items() if v == max(counts.values())]
        return mode_ls

From the above Codes,Find_Mode(Array), it's one parameter about np.array(x,y,z,c,v,b,n,,,,,,,) of the function. It could solve mode number calculation questions in 1-N Dimension Array. It also solve array = \[2,2,2,2,2,2,2,2,2,2,2,2,2,2,2] hasn't mode number question. It also solve array = np.array(i for i in range(1,100000000)) hasn't mode number question. But I couldn't find a way to add the function to numpy. Thus, you need create one Mode_Calculation.py. And you must add these codes to the file. When you use numpy to calculate mode number, you will like my below codes to achieve it:

python 复制代码
import Mode_Calculation as MC
import numpy as np
from scipy import stats

array = np.random.randint(1,10,10)
array2 = np.array([i for i in range(1,10)])
array3 = np.random.random(10)
array4 = np.random.randint(1,100,100000000)
Tensor = np.reshape(array4,(200,500,10,100))

Matrix = np.reshape(array,(2,5))
mode_result = MC.Find_Mode(Matrix)
sp_result = stats.mode(Matrix)
mode_result2 = MC.Find_Mode(array2)
sp_result2 = stats.mode(array2)
mode_result3 = MC.Find_Mode(array3)
sp_result3 = stats.mode(array3)
mode_result4 = MC.Find_Mode(Tensor)
sp_result4 = stats.mode(Tensor)
print("The Array Mode is:{}".format(mode_result))
print("sp_result:\n{}".format(sp_result))
print("mode_result2:\n{}".format(mode_result2))
print("sp_result2:\n{}".format(sp_result2))
print("mode_result3:\n{}".format(mode_result3))
print("sp_result3:\n{}".format(sp_result3))
print("mode_result4:\n{}".format(mode_result4))
print("sp_result4:\n{}".format(sp_result4))

The result:

根据scipy的原有众数函数,继续升级,既能获得众数,也能获得众数在Array数组中的总量,change the Codes like the below Codes:

python 复制代码
from collections import Counter
def Find_Mode(Array):
    vector_translate = Array.ravel()
    counts = Counter(vector_translate)
    if max(counts.values()) == 1 or len(set(vector_translate)) == 1:return None
    else:
        mode_ls = [(k,v) for k,v in counts.items() if v == max(counts.values())]
        return mode_ls

再次升级【get progress】,Mode_Calculation.py Codes:

python 复制代码
from collections import Counter
def Find_Mode(Array):
    vector_translate = Array.ravel()
    counts = Counter(vector_translate)
    if len(set(vector_translate))==1:
        return None
    max_value = max(counts.values())
    if max_value==1:
        return None
    else:
        mode_ls = [(k,v) for k,v in counts.items() if v == max_value]
        return mode_ls

Again, let it become high-level better than before.

python 复制代码
from collections import Counter
import numpy as np
def Find_Mode(Array):
    try:
        vector_translate = Array.ravel()
        counts = Counter(vector_translate)
        if len(set(vector_translate))==1:
            return np.nan
        max_value = max(counts.values())
        if max_value==1:
            return np.nan
        else:
            mode_ls = [(k,v) for k,v in counts.items() if v == max_value]
            return mode_ls
    except Exception:
        return Array

Test Codes:

python 复制代码
import Mode_Calculation as MC
import numpy as np
import time

def Test():
    m = 10
    array4 = np.random.randint(11,23,30)
    array8 = np.array([m for n in range(0,10000000)])
    array6 = np.random.randint(1,50000,10000000)
    array5 = np.reshape(array4,(2,5,3))
    array9 = np.reshape(array6,(20,500,10,100))
    array7 = np.reshape(array8,(100,50,10,10,20))
    AY1 = np.array([])
    # print("array3:\n{}".format(array5))
    mode_result = MC.Find_Mode(array5)
    mode_result2 = MC.Find_Mode(array7)
    start_time = time.time()
    mode_result3 = MC.Find_Mode(array9)
    end_time = time.time()
    print("mode_result:{}".format(mode_result))
    print("mode_result2:{}".format(mode_result2))
    test = MC.Find_Mode(AY1)
    print("mode_result3:{}".format(mode_result3))
    print("time:%.4f秒"%(end_time-start_time))
    print("test:{}".format(test))

if __name__ == "__main__":
    Test()

Result:

结论

数据要科学,不能不科学。去菜市场买菜,和菜农说"你这菜要多少阶乘的钱一斤?",菜农说"4!块钱"。这很有趣不是吗?

相关推荐
宿州派大星1 小时前
Python 音视频处理流水线:视频分离音频 + 讯飞转写 + 星火大模型解析(附完整代码与踩坑指南)
开发语言·python·音视频
I Am a robert girl1 小时前
DiffRAC:当视频“呼吸”有了节拍器——重复动作计数的新范式
python·深度学习·计算机视觉·视频分析·视频扩散模型·重复动作计数
郝学胜-神的一滴2 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
有个傻瓜2 小时前
容器里时间凭空差 8 小时:naive 与 aware 时区混用排错复盘与四种方案实测
python·docker·springboot·时区排错·naive/aware
心流剑2 小时前
从零打造带降级路由的 Agentic RAG 校园智能体(附前端终端UI实战)
python·ai·rag
天远数科3 小时前
零信任架构实战:基于天远车辆过户详版查询构建自动化抵押车权属合规审查网关
人工智能·python·架构·自动化
badhope4 小时前
3 个 Agent 并行发文章:我用 SQLite 任务表止住重复
后端·python·ai编程
战6174 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
databook4 小时前
马尔可夫链入门:状态、转移概率与无记忆性
python·机器学习·数据分析
郝学胜-神的一滴5 小时前
量化交易从入门到精通 05:策略从哪来
开发语言·python·numpy·pandas·scikit-learn·matplotlib·scipy