日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

数据分析问题(异常值识别)中数据预处理部分流程(含2022年全国服务外包大赛实例)

發(fā)布時(shí)間:2024/3/24 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据分析问题(异常值识别)中数据预处理部分流程(含2022年全国服务外包大赛实例) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

??博主個(gè)人理解的數(shù)據(jù)預(yù)處理主要包括 個(gè)方面:讀取文件 => 數(shù)據(jù)概覽 => 缺失值填補(bǔ) => 數(shù)據(jù)分布預(yù)覽 => 衍生特征設(shè)計(jì)。這套流程在完成異常值識(shí)別時(shí)作為數(shù)據(jù)預(yù)處理時(shí)沒有什么問題的。
??我們以2022年全國服務(wù)外包大賽的A03題目作為示例代碼實(shí)現(xiàn)整個(gè)預(yù)處理過程。問題的主要任務(wù)時(shí)找出商品的銷量異常和價(jià)格異常,提供4個(gè)月的商品信息數(shù)據(jù),共1700萬余條,4個(gè)月的店鋪信息數(shù)據(jù),共60萬余條,強(qiáng)調(diào)時(shí)間復(fù)雜度空間復(fù)雜度、異常值識(shí)別率和準(zhǔn)確率。
??部分?jǐn)?shù)據(jù)鏈接:https://pan.baidu.com/s/1KatV_6ozYHjPkNjfVGBPmw 提取碼:ee8i
??整體思路如下:

讀取文件

??嚴(yán)格來說讀取文件不算是預(yù)處理的步驟的。但對(duì)于初學(xué)者而言,代碼在這塊多多少少總有些問題,主要是在文件編碼方面的和內(nèi)存炸了的問題。

def change_utf_1(): # 打開文檔,以u(píng)tf-8的csv保存for i in range(6, 7, 1): # 為了批量打開文檔們file = "data_20210" + str(i) + ".tsv"result = []# 相較于pd.read_csv(),這個(gè)內(nèi)存不會(huì)炸with codecs.open(file, "rb", 'gb18030', errors='ignore') as csvfile:# 如果'gb18030'打開有問題,可以嘗試下遍歷這五個(gè)編碼方式,基本上都能解決問題# ['gbk', 'utf-8', 'utf-8-sig', 'GB2312', 'gb18030']for line in csvfile:line = line.replace("\r", "")line = line.replace("\n", "")temp1 = line.split("\t")result.append(temp1)# print(result)data = pd.DataFrame(result)new_file = "data_20210" + str(i) + "_new.tsv"data.to_csv(new_file, index=0, encoding="utf-8", header=None, sep="\t")f = pd.read_csv(new_file, sep="\t", encoding="utf-8")# 因?yàn)樵瓉淼臄?shù)據(jù)太大了,不方便實(shí)驗(yàn),所以取個(gè)頭保存new_head = "data_20210" + str(i) + "_head.tsv"f.head(50).to_csv(new_head, sep="\t", encoding="utf-8", index=0)

數(shù)據(jù)概覽

??這一部分一般都是直接跟在讀取文件后面的,實(shí)際上就是為了查看缺失值和每個(gè)數(shù)據(jù)的大概情況。

import pandas as pd file = pd.read_csv("data_202106.csv", encoding = "utf-8") # 看缺失值 print(file.info()) # 這里可以只選LV變量,不一定要全部的 for i in file.columns:print(file[i].values_count()) # 更直觀一點(diǎn),直接看餅圖,查看銷售額總量 plt.figure.figsize = (20,20) for i in range(5):sub_cat_val = df.groupby('CATE_NAME_LV'+str(i+1))['ITEM_SALES_AMOUNT'].sum()sub_cat_val.plot(kind = 'pie', autopct='%1.1f%%', label = 'sub_cat_val.index' )

??餅圖結(jié)果如下:


缺失值填補(bǔ)

??這部分是方法非常重要的部分,注意不要死死盯著準(zhǔn)確率,可能準(zhǔn)確率上去了,但是過擬合,一定要親眼掃一掃被填補(bǔ)的缺失值長(zhǎng)什么樣。就比如我現(xiàn)在展示的隨機(jī)森林方法就不太適合這個(gè)問題。其他解決辦法見博主的另一篇博客:https://blog.csdn.net/Hjh1906008151/article/details/124338450

# coding:utf-8 import pandas as pd import numpy as np from sklearn.ensemble import RandomForestRegressor import matplotlib.pyplot as plt import matplotlib as mpl from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定中文字體 mpl.rcParams['axes.unicode_minus'] = False # 解決保存圖像是負(fù)號(hào)'-'顯示為方塊的問題 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 正常顯示負(fù)號(hào)def check_data_and_process(need_fill_col, need_fill_file):f = pd.read_csv(need_fill_file, sep="\t", encoding="utf-8")col = f.columnsnull_col = [] # 有缺失值的列no_need_col = ["DATA_MONTH"] # 確定對(duì)訓(xùn)練無用的字段for c in col:if len(f[f[c].isnull()][c]) != 0:null_col.append(c)print("字段:", c, "缺失數(shù):", len(f[f[c].isnull()][c]))need_fill_col = need_fill_coldrop_col = [] # 填補(bǔ)數(shù)據(jù)時(shí)需要先刪除缺失的數(shù)據(jù),一個(gè)一個(gè)補(bǔ)drop_col.extend(no_need_col)for c in null_col:if c != need_fill_col:drop_col.append(c)data_all = f.drop(columns=drop_col) # 需要缺失值預(yù)測(cè)字段的缺失和非缺失都在一起# data_need_to_pre = data_all[data_all[need_fill_col].isnull()] # 需要填補(bǔ)此字段的數(shù)據(jù)data_need_to_train = data_all[~data_all[need_fill_col].isnull()] # 無缺失數(shù)據(jù)作為訓(xùn)練數(shù)據(jù)data = data_need_to_train.drop(columns=[need_fill_col])label = data_need_to_train[need_fill_col]return data, label, need_fill_col, f, data_alldef train_and_chose_model(model, data, label):data = np.array(data)label = np.array(label)scaler_1 = MinMaxScaler(feature_range=(0, 1))scaler_2 = MinMaxScaler(feature_range=(0, 1))data = scaler_1.fit_transform(data) # 歸一化處理,構(gòu)造兩個(gè)因?yàn)橹筮€需要反歸一化label = scaler_2.fit_transform(label.reshape(-1, 1))data_tr, data_te, labels_tr, labels_te = train_test_split(data, label, test_size=0.2, random_state=10)model.fit(data_tr, labels_tr) # 訓(xùn)練模型score_test = model.score(data_te, labels_te)score_train = model.score(data_tr, labels_tr)print(str(model) + "訓(xùn)練集準(zhǔn)確率為:" + str(score_train))print(str(model) + "測(cè)試集準(zhǔn)確率為:" + str(score_test)) # 出現(xiàn)負(fù)數(shù)不是很理解y_test_pre = model.predict(data_te) # 預(yù)測(cè)測(cè)試集y_train_pre = model.predict(data_tr) # 預(yù)測(cè)訓(xùn)練集print("訓(xùn)練集均方誤差:", mean_squared_error(labels_tr, y_train_pre))print("測(cè)試集均方誤差:", mean_squared_error(labels_te, y_test_pre))data_test_pre = scaler_2.inverse_transform(y_test_pre.reshape(-1, 1))data_train_pre = scaler_2.inverse_transform(y_train_pre.reshape(-1, 1)) # 測(cè)試集的預(yù)測(cè)值print(data_train_pre)def fill_data(model, data, label, need_fill_col, f, data_all):data_need_to_pre = data_all[data_all[need_fill_col].isnull()].drop(columns=[need_fill_col]) # 含缺失的去除缺失標(biāo)簽的數(shù)據(jù)data = np.array(data)label = np.array(label)scaler_1 = MinMaxScaler(feature_range=(0, 1))scaler_2 = MinMaxScaler(feature_range=(0, 1))scaler_1.fit_transform(data_all.drop(columns=[need_fill_col]))data_to_pre = scaler_1.fit_transform(data_need_to_pre)data = scaler_1.fit_transform(data) # 歸一化處理,構(gòu)造兩個(gè)因?yàn)橹筮€需要反歸一化label = scaler_2.fit_transform(label.reshape(-1, 1))data_tr, data_te, labels_tr, labels_te = train_test_split(data, label, test_size=0.2, random_state=10)model.fit(data_tr, labels_tr) # 訓(xùn)練模型score_test = model.score(data_te, labels_te)score_train = model.score(data_tr, labels_tr)print(str(model) + "訓(xùn)練集準(zhǔn)確率為:" + str(score_train))print(str(model) + "測(cè)試集準(zhǔn)確率為:" + str(score_test)) # 出現(xiàn)負(fù)數(shù)不是很理解y_test_pre = model.predict(data_te) # 預(yù)測(cè)測(cè)試集y_train_pre = model.predict(data_tr) # 預(yù)測(cè)訓(xùn)練集y_need_pred = model.predict(data_to_pre) # 填補(bǔ)缺失值print("訓(xùn)練集均方誤差:", mean_squared_error(labels_tr, y_train_pre))print("測(cè)試集均方誤差:", mean_squared_error(labels_te, y_test_pre))data_need_pred = scaler_2.inverse_transform(y_need_pred.reshape(-1, 1))for i, x in zip(f[f[need_fill_col].isnull()][need_fill_col].index, data_need_pred): # 遍歷索引和預(yù)測(cè)值,一個(gè)一個(gè)補(bǔ)進(jìn)去f.loc[i, need_fill_col] = xf.to_csv(need_fill_col+"已補(bǔ)"+"202106_10000_drop.tsv", sep="\t", index=0)# print(f[f[need_fill_col].isnull()][need_fill_col]) # 檢測(cè)是否補(bǔ)完def check(file):f = pd.read_csv(file, sep="\t", encoding="utf-8")col = f.columnsnull_col = [] # 有缺失值的列no_need_col = ["DATA_MONTH"] # 確定對(duì)訓(xùn)練無用的字段for c in col:if len(f[f[c].isnull()][c]) != 0:null_col.append(c)print("字段:", c, "缺失數(shù):", len(f[f[c].isnull()][c]))def main():need_fill_file = "TOTAL_EVAL_NUM已補(bǔ)202106_10000_drop.tsv" # 需要補(bǔ)的文件need_fill_col = "ITEM_STOCK" # 需要補(bǔ)的字段check("ITEM_STOCK已補(bǔ)202106_10000_drop.tsv")data, label, need_fill_col, f, data_all = check_data_and_process(need_fill_col, need_fill_file) # 用于數(shù)據(jù)分析以及數(shù)據(jù)預(yù)處理train_and_chose_model(RandomForestRegressor(), data, label) # 選擇最優(yōu)模型fill_data(RandomForestRegressor(), data, label, need_fill_col, f, data_all) # 填補(bǔ)數(shù)據(jù)if __name__ == '__main__':main()

數(shù)據(jù)分布預(yù)覽

??查看下各個(gè)數(shù)據(jù)的分布,觀察各個(gè)數(shù)據(jù)的分布,這對(duì)之后設(shè)計(jì)衍生特征特別重要,也對(duì)后面的模型選擇有一定指導(dǎo)作用。所以需要對(duì)自己感興趣的數(shù)據(jù)組合預(yù)覽一下。我們?cè)谶@里對(duì)幾對(duì)特征可視化一下。

def draw_scatter(df):df.plot.scatter(x="ITEM_FAV_NUM", y="ITEM_SALES_VOLUME") # 銷售量與點(diǎn)贊的關(guān)系plt.show()df.plot.scatter(x="TOTAL_EVAL_NUM", y="ITEM_SALES_VOLUME") # 銷售量與收藏的關(guān)系plt.show()df.plot.scatter(x="ITEM_PRICE", y="ITEM_SALES_VOLUME") # 銷售量與單價(jià)之間的關(guān)系plt.show()df.plot.scatter(x="ITEM_STOCK", y="ITEM_SALES_VOLUME") # 銷售量與庫存之間的關(guān)系plt.show()# 此處的df_total數(shù)據(jù)是4個(gè)月總體的,是為了看月份之間的差距 def draw_bar(df_total):df.groupby('ITEM_NAME')['ITEM_SALES_VOLUME_6','ITEM_SALES_VOLUME_7','ITEM_SALES_VOLUME_8','ITEM_SALES_VOLUME_9'].sum().plot.bar()plt.show()

衍生特征設(shè)計(jì)

??此處的衍生特征設(shè)計(jì)主要是pandas的應(yīng)用,可以參考思路(以價(jià)格異常為例):

衍生特征計(jì)算方法
same-CATE_NAME_LV1-mean-ITEM_PRICE-rate商品價(jià)格/同月同一級(jí)類目均價(jià)
same-CATE_NAME_LV2-mean-ITEM_PRICE-rate商品價(jià)格/同月同二級(jí)類目均價(jià)
same-CATE_NAME_LV3-mean-ITEM_PRICE-rate商品價(jià)格/同月同三級(jí)類目均價(jià)
same-CATE_NAME_LV4-mean-ITEM_PRICE-rate商品價(jià)格/同月同四級(jí)類目均價(jià)
same-CATE_NAME_LV5-mean-ITEM_PRICE-rate商品價(jià)格/同月同五級(jí)類目均價(jià)
same-CATE_NAME_LV2-deliver商品價(jià)格/同月同二級(jí)類目&&同一發(fā)貨地均價(jià)
same-CATE_NAME_LV2_price商品價(jià)格/同月同二級(jí)類目&&同一產(chǎn)地均價(jià)
month_6_mean_rate商品價(jià)格/四個(gè)月商品價(jià)格的均價(jià)
same-USER_ID_ITEM_PRICE商品價(jià)格/同月同一店鋪商品均價(jià)
same-MAIN_BUSINESS_price商品價(jià)格/同月同一主營(yíng)類型店鋪的所有商品均價(jià)
same-BUSINESS_SCOPE_price商品價(jià)格/同月同一經(jīng)營(yíng)范圍店鋪的所有商品均價(jià)
same-CATE_NAME_LV2_city商品價(jià)格/同月同一發(fā)貨城市的店鋪所有同二級(jí)類目的商品的均價(jià)

??這里的重點(diǎn)并非如何計(jì)算這些變量,當(dāng)然也是可以計(jì)算的,類似的方法見博主的這些博客
??傳統(tǒng)方法可以參考這篇博客:https://blog.csdn.net/Hjh1906008151/article/details/124342492
??pyod方法可以參考這篇博客:https://blog.csdn.net/Hjh1906008151/article/details/124340047

總結(jié)

以上是生活随笔為你收集整理的数据分析问题(异常值识别)中数据预处理部分流程(含2022年全国服务外包大赛实例)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。