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!块钱"。这很有趣不是吗?

相关推荐
协皓家具4 小时前
2026年广州岛台吧台椅厂家有啥新变化
大数据·运维·python·devops
yuniko-n5 小时前
【Java】字符串相关坑点
java·开发语言·python
用户019027581615 小时前
如何用 Python 统计 A 股连续涨停(几连板)?
python
外收内放5 小时前
Python基础语法练习题(拓展1)
python·游戏
H_unique5 小时前
Chat2Excel:接口自动化测试
python·测试工具·自动化
ss2735 小时前
AI全栈实战 | 3.3-02 Python 并发:有 GIL 为什么还用多线程,asyncio 和 JS 事件循环同源不同味
开发语言·javascript·python
空心木偶☜5 小时前
Langgraph操作时常见的错误
python·ai·ai编程·langgraph
cpolar技术支持5 小时前
外网测试机的异常传不回内网?自托管 Sentry,用 cpolar 打通错误上报链路
python·nginx·docker·cpolar·sentry
小小龙学IT6 小时前
Python SQLAlchemy 2.0 深度解析:从 Core 到 ORM 的数据访问双引擎
开发语言·数据库·python
2601_962885726 小时前
如何用 Python 计算 ROC 变动率指标做动量分析?
开发语言·python·算法