TPOT分析水文數(shù)據(jù)

1. 水文數(shù)據(jù)集

https://data.edmonton.ca/dataset/Water-Levels-and-Flows/cnsu-iagr

###該數(shù)據(jù)集一共9個(gè)屬性:
1.Raw ID 
2.Station Number => 水文站編號  --26 --離散值
3.Station Description => 水文站描述 --26 --文本信息
4.Latitude => 緯度 --28 --離散值
5.Longitude => 經(jīng)度 --28 --離散值
6.Station Location => 水文站位置乐疆,由經(jīng)緯度組合而成  --28 --離散值
7.Date and Time => 時(shí)間
8.Water Level (m) => 水位 -- --連續(xù)值
9.Water Flow (cu meter per sec) => 流速 -- --連續(xù)值

因?yàn)門POT只能處理數(shù)值類型焰望,在我們的數(shù)據(jù)集中蛋勺,有4個(gè)變量不是數(shù)值類型:
Station Number, Station Description, Station Location, Date and Time
所以侦讨,下面重點(diǎn)是處理這幾個(gè)變量摧找;

###數(shù)據(jù)預(yù)處理:
1.Station Number
離散值养交,有26個(gè)可選抓狭,使用one-hot編碼

2.Station Description, Station Location, Raw ID
無用信息粱挡,刪除

3.Date and Time
分析數(shù)據(jù)赠幕,從2016年到2019年,所以年份不敏感询筏;
拆分為月榕堰,日和小時(shí)

4.Latitude和Longitude可能缺失
總的記錄數(shù):
(3910803, 9)

非空記錄數(shù):
(1975617, 9)

5.經(jīng)緯度缺失的數(shù)據(jù)量很大,所以不能直接舍棄嫌套;
首先計(jì)算水文站經(jīng)緯度的平均值逆屡,用這個(gè)來代替

6.Water Flow (cu meter per sec)可能非法,例如-1, 刪除這些記錄

2. 代碼

from tpot import TPOTRegressor
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
import os
from tensorflow.python.client import device_lib

os.environ["CUDA_VISIBLE_DEVICES"] = "1"
print(device_lib.list_local_devices())

df = pd.read_csv('Water_Levels_and_Flows.csv.1w', header=0,error_bad_lines=False)
print(df.head(5))
print(df.shape)
print(pd.isnull(df).any())

#刪除Water_Flow為負(fù)的行
print('刪除Water_Flow無效行')
df=df[~(df['Water_Flow']<0)]
print(df.shape)

mean_longitude = df.groupby('Station Number').Longitude.mean()
mean_latitude = df.groupby('Station Number').Latitude.mean()
null_longitude = df[df.Longitude.isnull()]

for cat in ['Station Number', 'Station Description', 'Latitude', 'Longitude' ]:
    print("Number of levels in category '{0}': \b {1:2.2f} ".format(cat, df[cat].unique().size))

for cat in ['Latitude', 'Longitude']:
    print("Levels for catgeory '{0}': {1}".format(cat, df[cat].unique()))

#刪掉無關(guān)因素
df = df.drop(['id', 'Station Description','Station Location', 'Latitude', 'Longitude'],axis=1) # axis=0 刪除行踱讨,=1 刪除列

#將Station用啞變量表示
dumm = pd.get_dummies(df[['Station Number']]) # '啞變量'矩陣
df = df.join(dumm)
del df['Station Number'] # 刪除

#添加month,day,hour三個(gè)鍵和值
temp=pd.DatetimeIndex(df['Date and Time'])
df['date']=temp.date
df['time']=temp.time
df['hour']=pd.to_datetime(df.time,format="%H:%M:%S")#變換格式
df['hour']=pd.Index(df["hour"]).hour
df['month']=pd.to_datetime(df.date,format="%Y-%m-%d")#變換格式
df['month']=pd.Index(df["month"]).month
df['day']=pd.to_datetime(df.date,format="%Y-%m-%d")#變換格式
df['day']=pd.Index(df["day"]).day
df = df.drop(['Date and Time', 'date', 'time'],axis=1) # axis=0 刪除行魏蔗,=1 刪除列
print(df.head(5))
print(df.shape)

X = np.array(df.drop(['Water_Level'], 1))
Y = np.array(df['Water_Level'])
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)

tpot = TPOTRegressor(generations=20, verbosity=2) #迭代20次
tpot.fit(X_train, y_train)
print(tpot.score(X_test, y_test))
tpot.export('pipeline.py')

3. 運(yùn)行TPOT

因?yàn)閳?zhí)行時(shí)間過長,所以使用后臺運(yùn)行方式:

nohup python -u water_tpot.py > nohup.out 2>&1 &

輸出如下:

Generation 1 - Current best internal CV score: -0.10354635942452688
Generation 2 - Current best internal CV score: -0.07407627082459693
Generation 3 - Current best internal CV score: -0.07407627082459693
Generation 4 - Current best internal CV score: -0.07407627082459693
Generation 5 - Current best internal CV score: -0.07261441673202419
Generation 6 - Current best internal CV score: -0.07261441673202419
Generation 7 - Current best internal CV score: -0.07261441673202419
Generation 8 - Current best internal CV score: -0.06272878450716013
Generation 9 - Current best internal CV score: -0.06150379726583473
Generation 10 - Current best internal CV score: -0.06150379726583473
Generation 11 - Current best internal CV score: -0.06150379726583473
Generation 12 - Current best internal CV score: -0.05930206668688394
Generation 13 - Current best internal CV score: -0.054799951152979184
Generation 14 - Current best internal CV score: -0.054799951152979184
Generation 15 - Current best internal CV score: -0.052015877476651276
Generation 16 - Current best internal CV score: -0.052015877476651276
Generation 17 - Current best internal CV score: -0.05173009225925466
Generation 18 - Current best internal CV score: -0.043718068024817355
Generation 19 - Current best internal CV score: -0.043718068024817355
Generation 20 - Current best internal CV score: -0.043718068024817355
Best pipeline: ExtraTreesRegressor(SelectPercentile(DecisionTreeRegressor(ElasticNetCV(input_matrix, l1_ratio=0.7000000000000001, tol=1e-05), max_depth=1, min_samples_leaf=2, min_samples_split=15), percentile=94), bootstrap=False, max_features=1.0, min_samples_leaf=2, min_samples_split=2, n_estimators=100)
-0.027241579610884296

TPOT認(rèn)為ExtraTreesRegressor是最好的模型痹筛,并導(dǎo)出pipeline.py莺治。

4. 運(yùn)行pipeline

導(dǎo)出的pipeline.py文件需要根據(jù)實(shí)際情況修改如下:

import numpy as np
import pandas as pd
from sklearn.ensemble import ExtraTreesRegressor
from sklearn.feature_selection import SelectPercentile, f_regression
from sklearn.linear_model import ElasticNetCV
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline, make_union
from sklearn.tree import DecisionTreeRegressor
from tpot.builtins import StackingEstimator

# NOTE: Make sure that the class is labeled 'target' in the data file
df = pd.read_csv('Water_Levels_and_Flows.csv.1w', sep=',', header=0,error_bad_lines=False)
#刪除Water_Flow為負(fù)的行
print('刪除Water_Flow無效行')
df=df[~(df['Water_Flow']<0)]
print(df.shape)

mean_longitude = df.groupby('Station Number').Longitude.mean()
mean_latitude = df.groupby('Station Number').Latitude.mean()
null_longitude = df[df.Longitude.isnull()]

for cat in ['Station Number', 'Station Description', 'Latitude', 'Longitude' ]:
    print("Number of levels in category '{0}': \b {1:2.2f} ".format(cat, df[cat].unique().size))

for cat in ['Latitude', 'Longitude']:
    print("Levels for catgeory '{0}': {1}".format(cat, df[cat].unique()))

#刪掉無關(guān)因素
df = df.drop(['id', 'Station Description','Station Location', 'Latitude', 'Longitude'],axis=1) # axis=0 刪除行,=1 刪除列

#將Station用啞變量表示
dumm = pd.get_dummies(df[['Station Number']]) # '啞變量'矩陣
df = df.join(dumm)
del df['Station Number'] # 刪除

#添加month,day,hour三個(gè)鍵和值
temp=pd.DatetimeIndex(df['Date and Time'])
df['date']=temp.date
df['time']=temp.time
df['hour']=pd.to_datetime(df.time,format="%H:%M:%S")#變換格式
df['hour']=pd.Index(df["hour"]).hour
df['month']=pd.to_datetime(df.date,format="%Y-%m-%d")#變換格式
df['month']=pd.Index(df["month"]).month
df['day']=pd.to_datetime(df.date,format="%Y-%m-%d")#變換格式
df['day']=pd.Index(df["day"]).day
df = df.drop(['Date and Time', 'date', 'time'],axis=1) # axis=0 刪除行帚稠,=1 刪除列
print(df.head(5))
print(df.shape)


X = np.array(df.drop(['Water_Level'], 1))
Y = np.array(df['Water_Level'])
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2)

training_features, testing_features, training_target, testing_target = \
            train_test_split(X, Y, random_state=None)

# Average CV score on the training set was:-0.043718068024817355
exported_pipeline = make_pipeline(
    StackingEstimator(estimator=ElasticNetCV(l1_ratio=0.7000000000000001, tol=1e-05)),
    StackingEstimator(estimator=DecisionTreeRegressor(max_depth=1, min_samples_leaf=2, min_samples_split=15)),
    SelectPercentile(score_func=f_regression, percentile=94),
    ExtraTreesRegressor(bootstrap=False, max_features=1.0, min_samples_leaf=2, min_samples_split=2, n_estimators=100)
)

exported_pipeline.fit(training_features, training_target)
results = exported_pipeline.predict(testing_features)
print("results: %s"%results)
score = exported_pipeline.score(testing_features, testing_target)
print("score: %s"%score)

同樣谣旁,在后臺運(yùn)行:

nohup python -u pipeline.py > nohup.out 2>&1 &

輸出如下:

results: [7.1012806  1.25462311 0.73743519 ... 2.12231535 4.22561277 1.27338528]
score: 0.9999991261258582

5. GPU

可惜的是,目前TPOT不支持GPU:
https://github.com/EpistasisLab/tpot/issues/680

不過滋早,實(shí)際應(yīng)用中我們發(fā)現(xiàn)榄审,只是GPU-Util為0, GPU Memory Usage仍然可以達(dá)到10440MiB


屏幕快照 2019-01-30 下午6.32.55.png

6. 速度

TPOT在處理小規(guī)模數(shù)據(jù)的時(shí)候非掣唆铮快搁进,結(jié)果很給力。但處理大規(guī)模的數(shù)據(jù)問題昔头,速度非常慢饼问。所以可以嘗試在數(shù)據(jù)清洗之后,抽樣小部分?jǐn)?shù)據(jù)跑一下TPOT揭斧,能得到一個(gè)還不錯(cuò)的算法匆瓜。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市未蝌,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌茧妒,老刑警劉巖萧吠,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異桐筏,居然都是意外死亡纸型,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來狰腌,“玉大人除破,你說我怎么就攤上這事∏砬唬” “怎么了瑰枫?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長丹莲。 經(jīng)常有香客問我光坝,道長,這世上最難降的妖魔是什么甥材? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任盯另,我火速辦了婚禮,結(jié)果婚禮上洲赵,老公的妹妹穿的比我還像新娘鸳惯。我一直安慰自己,他們只是感情好叠萍,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布芝发。 她就那樣靜靜地躺著,像睡著了一般俭令。 火紅的嫁衣襯著肌膚如雪后德。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天抄腔,我揣著相機(jī)與錄音瓢湃,去河邊找鬼。 笑死赫蛇,一個(gè)胖子當(dāng)著我的面吹牛绵患,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播悟耘,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼落蝙,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了暂幼?” 一聲冷哼從身側(cè)響起筏勒,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎旺嬉,沒想到半個(gè)月后管行,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡邪媳,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年捐顷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了荡陷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,727評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡迅涮,死狀恐怖废赞,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情叮姑,我是刑警寧澤唉地,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站戏溺,受9級特大地震影響渣蜗,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜旷祸,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一耕拷、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧托享,春花似錦骚烧、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至羡榴,卻和暖如春碧查,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背校仑。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工忠售, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人迄沫。 一個(gè)月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓稻扬,卻偏偏與公主長得像,于是被迫代替她去往敵國和親羊瘩。 傳聞我的和親對象是個(gè)殘疾皇子泰佳,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,619評論 2 354

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

  • 官網(wǎng) 中文版本 好的網(wǎng)站 Content-type: text/htmlBASH Section: User ...
    不排版閱讀 4,380評論 0 5
  • 一、Python簡介和環(huán)境搭建以及pip的安裝 4課時(shí)實(shí)驗(yàn)課主要內(nèi)容 【Python簡介】: Python 是一個(gè)...
    _小老虎_閱讀 5,744評論 0 10
  • 簡評:隨著自由職業(yè)者的增多尘吗,在家工作的人越來越多逝她。這種靈活性似乎是個(gè)好主意,但很多人卻發(fā)現(xiàn)這種模式很難管理時(shí)間睬捶。在...
    極小光閱讀 2,664評論 0 8
  • 寒秋黔宛,連天的雨,反復(fù)洗刷著我所住的小城侧戴,房前屋后的水泥路面宁昭,閃著粗糙的冷光。 父親酗宋,在我母親病逝后的五年积仗,就...
    東園一姝梅閱讀 286評論 0 0
  • 海闊憑魚躍寂曹,天高任鳥飛! 行動營回右,又讓我開闊了眼界隆圆,漲了新姿勢。認(rèn)識了一條在文山案海里隨意躍動的魚翔烁,他帶領(lǐng)我們遨游...
    歲月追逐者閱讀 938評論 18 12