2022-03-09:內(nèi)存優(yōu)化

在進(jìn)行內(nèi)存優(yōu)化之前寞宫,可以使用如下函數(shù)對進(jìn)行使用的內(nèi)存進(jìn)行統(tǒng)計。

import psutil
impot os
def cpu_stats():
    pid = os.getpid()
    py = psutil.Process(pid)
    memory_use = py.memory_info()[0] / 2. ** 30
    return 'memory GB:' + str(np.round(memory_use, 2))


# 整體內(nèi)存使用
df.info(memory_usage="deep")
# 每列內(nèi)存使用
df.memory_usage()

對于應(yīng)用程序崇摄,可以使用filprofiler函數(shù)查看內(nèi)存峰值擎值。
https://pythonspeed.com/fil/docs/


Pandas內(nèi)存優(yōu)化
分批讀取
如果數(shù)據(jù)文件非常大,可以在讀取時分批次讀取逐抑,通過設(shè)置chunksize來控制批大小鸠儿。
df = pd.read_csv(path, chunksize=1000000)
for chunk in df:  
    # 分批次處理數(shù)據(jù)
    pass
選擇讀取部分列
df = pd.read_csv(path, usecols=["a"])
提前設(shè)置列類型
df = pd.read_csv(path, dtype={"a":"int8"})
將類別列設(shè)為category類型
df['a'] = df['a'].astype('category')
自動識別類型并進(jìn)行轉(zhuǎn)換
def reduce_mem_usage(props):
    start_mem_usg = props.memory_usage().sum() / 1024**2 
    print("Memory usage of properties dataframe is :",start_mem_usg," MB")
    NAlist = [] # Keeps track of columns that have missing values filled in. 
    for col in props.columns:
        if props[col].dtype != object:  # Exclude strings
            
            # Print current column type
            print("******************************")
            print("Column: ",col)
            print("dtype before: ",props[col].dtype)
            
            # make variables for Int, max and min
            IsInt = False
            mx = props[col].max()
            mn = props[col].min()
            
            # Integer does not support NA, therefore, NA needs to be filled
            if not np.isfinite(props[col]).all(): 
                NAlist.append(col)
                props[col].fillna(mn-1,inplace=True)  
                   
            # test if column can be converted to an integer
            asint = props[col].fillna(0).astype(np.int64)
            result = (props[col] - asint)
            result = result.sum()
            if result > -0.01 and result < 0.01:
                IsInt = True

            
            # Make Integer/unsigned Integer datatypes
            if IsInt:
                if mn >= 0:
                    if mx < 255:
                        props[col] = props[col].astype(np.uint8)
                    elif mx < 65535:
                        props[col] = props[col].astype(np.uint16)
                    elif mx < 4294967295:
                        props[col] = props[col].astype(np.uint32)
                    else:
                        props[col] = props[col].astype(np.uint64)
                else:
                    if mn > np.iinfo(np.int8).min and mx < np.iinfo(np.int8).max:
                        props[col] = props[col].astype(np.int8)
                    elif mn > np.iinfo(np.int16).min and mx < np.iinfo(np.int16).max:
                        props[col] = props[col].astype(np.int16)
                    elif mn > np.iinfo(np.int32).min and mx < np.iinfo(np.int32).max:
                        props[col] = props[col].astype(np.int32)
                    elif mn > np.iinfo(np.int64).min and mx < np.iinfo(np.int64).max:
                        props[col] = props[col].astype(np.int64)    
            
            # Make float datatypes 32 bit
            else:
                props[col] = props[col].astype(np.float32)
            
            # Print new column type
            print("dtype after: ",props[col].dtype)
            print("******************************")
    
    # Print final result
    print("___MEMORY USAGE AFTER COMPLETION:___")
    mem_usg = props.memory_usage().sum() / 1024**2 
    print("Memory usage is: ",mem_usg," MB")
    print("This is ",100*mem_usg/start_mem_usg,"% of the initial size")
    return props, NAlist
props = pd.read_csv(r"../input/properties_2016.csv")  #The properties dataset
props, NAlist = reduce_mem_usage(props)
print("_________________")
print("")
print("Warning: the following columns have missing values filled with 'df['column_name'].min() -1': ")
print("_________________")
print("")
print(NAlist)

模型內(nèi)存優(yōu)化

https://zhuanlan.zhihu.com/p/90302494

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌陈醒,老刑警劉巖朴恳,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件舍杜,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進(jìn)店門贤徒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人汇四,你說我怎么就攤上這事接奈。” “怎么了通孽?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵序宦,是天一觀的道長。 經(jīng)常有香客問我背苦,道長挨厚,這世上最難降的妖魔是什么堡僻? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任糠惫,我火速辦了婚禮疫剃,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘硼讽。我一直安慰自己巢价,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布固阁。 她就那樣靜靜地躺著壤躲,像睡著了一般。 火紅的嫁衣襯著肌膚如雪备燃。 梳的紋絲不亂的頭發(fā)上碉克,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天,我揣著相機與錄音并齐,去河邊找鬼漏麦。 笑死,一個胖子當(dāng)著我的面吹牛况褪,可吹牛的內(nèi)容都是我干的撕贞。 我是一名探鬼主播,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼测垛,長吁一口氣:“原來是場噩夢啊……” “哼捏膨!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起食侮,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤号涯,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后锯七,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體链快,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年起胰,在試婚紗的時候發(fā)現(xiàn)自己被綠了久又。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡效五,死狀恐怖地消,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情畏妖,我是刑警寧澤脉执,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站戒劫,受9級特大地震影響半夷,放射性物質(zhì)發(fā)生泄漏婆廊。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一巫橄、第九天 我趴在偏房一處隱蔽的房頂上張望淘邻。 院中可真熱鬧,春花似錦湘换、人聲如沸宾舅。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽筹我。三九已至,卻和暖如春帆离,著一層夾襖步出監(jiān)牢的瞬間蔬蕊,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工哥谷, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留岸夯,地道東北人。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓呼巷,卻偏偏與公主長得像囱修,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子王悍,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,044評論 2 355

推薦閱讀更多精彩內(nèi)容