|
9 h: }1 {+ w( j$ e
此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设
9 n4 N* K& ]& ^4 w+ g) F& b, d& T6 V1 F 数据分析的目的:
" Q) W' ?, t T5 ^! G& V2 u EDA的主要价值在于熟悉整个数据集的基本情况(缺失值、异常值),来确定所获得数据集可以用于接下来的机器学习或者深度学习使用。了解特征之间的相关性、分布,以及特征与预测值之间的关系。为进行特征工程提供理论依据。项目地址:https://github.com/datawhalechina/team-learning-data-mining/tree/master/wisdomOcean比赛地址:https://tianchi.aliyun.com/competition/entrance/231768/introduction?spm=5176.12281957.1004.8.4ac63eafE1rwsY
+ D* S# H% z, e, ? 2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布 " A' h: i; `* B. V. A; C6 ~8 f1 K
三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd
. O# e. }& x/ P( G. n( d import geopandas as gpd 0 E: g8 @# V5 o
from pyproj import Proj
( j' Z4 \& N4 Q* d3 d, r' p0 A) F from keplergl import KeplerGl
- D p, Q- a- |: @6 h B0 m( I# G from tqdm import tqdm 3 c: k% U6 g. j4 r6 U' ~
import os
w* |; V4 ?5 K% h' g2 j import matplotlib.pyplot as plt * q( h1 s9 T( F
import shapely
, L. ^/ D! i/ J7 m- T6 X6 v1 `8 o import numpy as np
$ M L' Y# L# N/ S+ i! {; Z from datetime import datetime 0 }3 E* m4 q0 O7 [0 ]
import warnings
* n, @! M k. ~( k' ~ warnings.filterwarnings(ignore) % L8 P. Y) h, r, u
plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。 / k8 N, E9 V9 ?& l- _/ l% Z
plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。
9 K9 s: i) ^& q* s #获取文件夹中的数据 " @/ H3 J K S( |: _& r# H7 k; ~: ` h
def get_data(file_path,model): - p1 S6 S; b+ k' L, R, V
assert model in [train, test], {} Not Support this type of file.format(model)
; J7 U4 c# p5 \" P# b* W paths = os.listdir(file_path)
* r! E4 r$ p M5 m( w1 r # print(len(paths)) - ] b) q; m% K! H, k8 H& X
tmp = []
/ v( D1 V: v/ E5 `& j; t' h for t in tqdm(range(len(paths))): & D4 Z) W5 U' g1 E7 G
p = paths[t] 4 l: e- D* R3 L, f: u
with open({}/{}.format(file_path, p), encoding=utf-8) as f: * M! N& I8 D7 F9 e% @
next(f) * C' `) b, G& Y$ i
for line in f.readlines(): " S0 S9 J" G$ e$ P
tmp.append(line.strip().split(,))
6 p: Z, c$ {& o5 Z tmp_df = pd.DataFrame(tmp) ( P7 j9 w. @: m8 e
if model == train:
: ^- E4 z. r* S$ L2 b: r tmp_df.columns = [ID, lat, lon, speed, direction, time, type] 9 ?4 O; e" R- _6 @; Q9 Y
else:
6 n1 V8 N% C4 u9 v6 r7 _ tmp_df[type] = unknown + H9 V5 X& B+ y. w9 E& Q; I
tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
9 {6 E5 M {8 v2 t5 M0 V& {5 h' i3 l- ` tmp_df[lat] = tmp_df[lat].astype(float) 0 _% B6 ^8 }/ p7 Q9 ^9 ?2 H
tmp_df[lon] = tmp_df[lon].astype(float)
5 c4 z# u; O/ M ]% W7 R. E tmp_df[speed] = tmp_df[speed].astype(float)
6 _5 A- `/ b1 f/ z5 H4 z tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本
) f9 |! ?" [' Q3 M! W; F& i return tmp_df
5 n1 j) @6 G! E) b # 平面坐标转经纬度,供初赛数据使用 5 ^% Z3 n* c7 t+ P2 ^
# 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud / X7 n+ G2 \% {7 p R0 H. g$ C: @. Q' M. Q
def transform_xy2lonlat(df):
! I" B1 x' K, F, m4 E0 v* y1 A x = df[lat].values
. `! ~8 f& z7 s, p5 b$ I y = df[lon].values
4 v3 t" P9 a, k1 o9 t3 D5 m4 J1 U2 Q: B; g p=Proj(+proj=lcc +lat_1=33.88333333333333 +lat_2=32.78333333333333 +lat_0=32.16666666666666 +lon_0=-116.25 +x_0=2000000.0001016 +y_0=500000.0001016001 +datum=NAD83 +units=us-ft +no_defs )
7 v$ I: q E; e df[lon], df[lat] = p(y, x, inverse=True) ! b( X. h+ [7 H: W' N7 I+ T
return df
0 Q) ?3 B5 p! K% R* Q #修改数据的时间格式
4 j+ f8 B9 ^. A( k: D$ u' I def reformat_strtime(time_str=None, START_YEAR="2019"):
4 F* p4 ^% z( H) s6 j """Reformat the strtime with the form 08 14 to START_YEAR-08-14 """
# x9 {( M, F6 x( d time_str_split = time_str.split(" ")
8 H7 C/ f1 \1 ] M# y8 D0 R time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4]
+ V- n2 W' d! d, P time_str_reformat = time_str_reformat + " " + time_str_split[1] " k3 W! \* {! s) N5 ~3 L* W$ c
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S)
& ^/ N4 x2 O& j }! r4 F; w return time_str_reformat 9 ~. o2 n; D* V6 E* e
#计算两个点的距离
( \2 n. k+ S/ E6 d def haversine_np(lon1, lat1, lon2, lat2):
% V8 Q+ R) q/ g/ E0 `0 ?& ~ w lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
; _" a+ j# `& `' W/ ~+ |& e dlon = lon2 - lon1 . m+ b* p4 N- D9 e7 }3 X
dlat = lat2 - lat1 3 I0 A. ]# k" f1 u
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 $ r4 u% N; y; A
c = 2 * np.arcsin(np.sqrt(a)) . }3 o* [/ j+ Y g5 Y& |
km = 6367 * c , T/ u- K# i/ O, m* W0 f \) _* W
return km * 1000 9 H5 o1 b5 O& S* A& {3 E/ r
def compute_traj_diff_time_distance(traj=None):
: Y1 T' `( `5 `; t0 ? """Compute the sampling time and the coordinate distance.""" % c- V* }4 H9 ]
# 计算时间的差值 . b, r" Q/ a0 h3 H/ \$ U
time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[
* b: F$ [: N3 F* ~ D# x "time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60
$ ?& C2 b2 c J/ y4 y8 [ # 计算坐标之间的距离
% n$ T# n& X+ w6 K5 B dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0
3 o1 p2 ? ~' ^5 x traj["lat"].values[1:], # lat_0 8 t$ M( n- \7 y) G# [# l
traj["lon"].values[:-1], # lon_1 1 |6 ^" s z" V% J4 n/ D$ q
traj["lat"].values[:-1] # lat_1 7 }! c' @8 E0 m8 E+ \2 {4 A4 C, ~
)
) I& T& {; A: R2 l) H5 U # 填充第一个值 5 h; f6 v/ l* N" I* Q3 Q5 k" t( w
time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist() 1 h8 H0 I/ K P: b7 `
dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist() 4 j; N& K7 j+ ^1 Y2 ^# L
traj.loc[list(traj.index),time_array] = time_diff_array 7 d( {, {/ ^7 v, }4 j
traj.loc[list(traj.index),dist_array] = dist_diff_array
6 \; _; l; d% o return traj 1 z! ?: \* {! ]9 s# z
#对轨迹进行异常点的剔除
" k+ c5 ]/ Y/ ]( M9 t" I O def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,
& k: }7 ^& t9 ^# D time_interval_maximum=200, 9 o. }& X( b5 N# F: W
coord_speed_maximum=700):
3 O: e3 o2 }8 w# I0 E """Assign the anomaly points in traj to np.nan."""
! g% @/ u5 Q% J; O# i- j- ^ def thigma_data(data_y,n):
1 T4 B% Q* q& d' Q% a data_x =[i for i in range(len(data_y))] 0 D+ y1 X) Z6 T" M) x9 K! x
ymean = np.mean(data_y)
- p# P" J* m: Z$ [ ystd = np.std(data_y) 6 C/ _( R0 T( v9 U2 O- i' a0 u1 S
threshold1 = ymean - n * ystd
s, ^3 Z3 T g( i6 b" h threshold2 = ymean + n * ystd * k# d& m# z# \
judge=[]
# J' Z0 T2 x, Z9 y for data in data_y: 1 s4 o2 U: x3 [* A* O- E
if (data < threshold1)|(data> threshold2):
0 [3 L+ _ C1 Z' F judge.append(True)
, l3 Z: [ X& m& m else: , F- o0 b2 Q6 |5 X j3 m8 s3 t
judge.append(False) : Z3 ] w2 P& P; N- @
return judge ; _0 r! R( l! X7 v7 H& _
# Step 1: The speed anomaly repairing
3 |* Q9 w# }5 ~# x) M is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) , N8 [9 {- X1 j6 ~" g
traj["speed"][is_speed_anomaly] = np.nan
. i- A9 |) h2 E Z # Step 2: 根据距离和时间计算速度
: O( h+ C4 \) q$ y is_anomaly = np.array([False] * len(traj)) ; X" d1 A) ^% A! K& x
traj["coord_speed"] = traj["dist_array"] / traj["time_array"] 7 o- n0 e- G/ Y ^- m. A
# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点 - U4 M: i/ F, R, J# U( Q; x
is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) , a- f3 k. O+ v4 d! N
is_anomaly = is_anomaly | is_anomaly_tmp . H2 @* U* u2 V- |9 s
is_anomaly.index=traj.index . n* c2 ]2 n7 C5 P' e( H
# Condition 2: 轨迹点的3-sigma异常处理 + P0 ]) X# N7 A0 G
traj = traj[~is_anomaly].reset_index(drop=True)
; ^2 o7 ~6 k6 _# U5 y is_anomaly = np.array([False] * len(traj))
7 G+ L, v% `9 u# A- G2 C( h if len(traj) != 0: 7 H9 e2 f& ~6 F4 J, N; N* Z- e, \
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
# A0 ?- _1 B3 |+ p" l F4 k/ S lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean() - K4 m$ l: }* O1 z- K
lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std * W! l7 _# G5 [& ?5 j6 x; D9 L% \
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std 7 ]$ @# e$ E+ O8 G$ Y u% G1 M& F
is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) & m" X' j5 v g8 f/ C$ Z2 O
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
. J' n, e- p" \; o3 m0 T traj = traj[~is_anomaly].reset_index(drop=True) 0 H: z" x9 l2 v, @; e$ l, S8 O+ W" |
return traj, [len(is_speed_anomaly) - len(traj)] 3 t, \/ j6 R+ v+ I
df=get_data(rC:\Users\admin\hy_round1_train_20200102,train)
4 M5 y" R/ H. N' i #对轨迹进行异常点剔除,对nan值进行线性插值 4 [0 h; Y1 E' R0 R. j$ Q% }# W
ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
. c; O; f3 h. o0 t% `3 c DF_NEW=[]
7 I1 C' P" |4 w- }6 J Anomaly_count=[] % w9 y* ]+ T% c( s
for ID in tqdm(ID_list):
& u- J w$ Z8 |, ~$ ?1 t df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
5 V+ g$ A2 L! ? j6 w" q df_new,count=assign_traj_anomaly_points_nan(df_id)
6 `8 U$ m1 c( I/ j1 U3 y df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
, C8 h' R% C8 @% d8 ^- n G df_new = df_new.fillna(method="bfill")
7 ?% D; C. X) ]/ k- K df_new = df_new.fillna(method="ffill")
9 v' c$ U4 N8 U7 }; ~: m df_new["speed"] = df_new["speed"].clip(0, 23)
1 A; B3 }) A# Y1 y6 q Anomaly_count.append(count)#统计每个id异常点的数量有多少
2 s4 h3 x; c6 A4 \# V DF_NEW.append(df_new)
0 X+ }3 g, h& i5 e #将数据写入到pkl格式
& w8 M) W; e; Y6 g# H load_save = Load_Save_Data() : j1 j! W1 w5 s. ?; P. g
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl") $ I1 j* `0 `9 q/ ]1 T/ K- A5 {
#### 三类渔船速度和方向可视化
' I# g: @& p- H4 y K6 [& D # 把训练集的所有数据,根据类别存放到不同的数据文件中
' h0 o' j# f0 q: C# c* H% a def get_diff_data():
' F' e9 Y4 U- }& P% f Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl" 5 c9 b! z, M; \1 c
with open(Path,"rb") as f:
5 }9 e. |5 @, _1 ^/ b @ total_data = pickle.load(f) ' s' ^& Y3 _( x2 J; v0 v5 X
load_save = Load_Save_Data() 7 H2 }4 n6 v0 `* [& {0 z) g3 k
kind_data = ["刺网","围网","拖网"] 1 O8 A, b) I$ @2 N$ B0 a! q
file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"] - M3 i; P- D2 Q# D0 O4 X/ C7 w' w
for i,datax in enumerate(kind_data):
7 {3 Q t/ J2 o0 W data_type = [data for data in total_data if data["type"].unique()[0] == datax] % S- F1 K7 ]. z, z5 @- p
load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
K& m9 p1 `0 ^1 A. _; U get_diff_data() ( s' g7 E6 K" i5 n* j) f' H- [; X
#对轨迹进行异常点剔除,对nan值进行线性插值 4 R. O' D3 h- k% C( I
ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
& k i, e6 H. w7 [2 `; L2 ` DF_NEW=[] $ A! I$ {9 Q! M* S
Anomaly_count=[] 1 p4 T9 a4 i+ R; N
for ID in tqdm(ID_list):
- h' Q' C% r1 l8 F& v( y) y df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) 2 X" j, E0 a) r4 e1 ^
df_new,count=assign_traj_anomaly_points_nan(df_id) / B* j- S: S! p' o
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
" F J- R f n- Q) f {% m df_new = df_new.fillna(method="bfill")
/ o" V. k1 `7 i3 t. u6 ?6 a2 D7 J df_new = df_new.fillna(method="ffill")
! C: C5 m/ h2 _ df_new["speed"] = df_new["speed"].clip(0, 23)
" x" R. b4 P8 Z5 M" m. v/ l/ p Anomaly_count.append(count)#统计每个id异常点的数量有多少 ( |, O% B- f e4 J9 g
DF_NEW.append(df_new)
& V( N5 v& I$ { # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列 , y+ l0 J: n7 E2 K; N' q( h( u
def visualize_three_traj_speed_direction():
8 E7 r1 b. p/ ^) V. N fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15))
0 ~7 j. U5 q# E3 G8 i& C. z" c4 l plt.subplots_adjust(wspace=0.3,hspace=0.3) 1 E. u& O; z9 E9 ]! h: i4 j
# 随机选出刺网的三条轨迹进行可视化 2 ~# d& G" v& [" z- l5 _" k
file_types = ["ciwang_data","weiwang_data","tuowang_data"] z7 B% w% }( P$ W3 U U2 ^% l! e9 H
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] ( d6 _- H" w; k5 P. C5 v& p
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"] ' L6 _7 S; [0 E2 B9 g
colors = [pink, lightblue, lightgreen] ; \: e2 j& [7 G& v6 g% Q
for i,file_name in tqdm(enumerate(file_types)): / p% @" h8 B Y
datax = get_random_one_traj(type=file_name)
5 g" p" o, [' y x_data = datax["速度"].loc[-1:].values 5 E0 m7 J7 `: S
y_data = datax["方向"].loc[-1:].values 4 f; g5 H, q6 J4 f
axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) Y9 t( f Z; ` n* t1 e4 ?
axes[i][0].grid(alpha=2) ( A- P) r& t7 k/ m/ k1 W' ? w
axes[i][0].legend(loc="best") 7 m1 J1 ?' E m: a
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) 9 ~/ b3 m- `3 S6 A3 V9 b9 X6 I; R, \
axes[i][1].grid(alpha=2)
& H' ^: z5 u- A \9 G axes[i][1].legend(loc="best")
( @! u0 Y" |! {& d; j3 G plt.show() ( Z1 ?. c: p5 Z$ a6 m- y+ h/ p1 x K
visualize_three_traj_speed_direction()
0 B7 y9 S1 ~3 N- z5 t $ J' f. `) z% m6 B# k9 R2 _
作业二:相关性分析。 5 R( q# @ Z% y V) N
data_train.loc[data_train[type]==刺网,type_id]=1
( N% ^: Z" G ?* Q t data_train.loc[data_train[type]==围网,type_id]=2
* I c, Q l; O4 t1 G data_train.loc[data_train[type]==拖网,type_id]=3
1 g3 r6 i7 J6 x" @' k; f8 W f, ax = plt.subplots(figsize=(9, 6)) 0 W1 z$ S. x4 U- b+ v+ `2 @
ax = sns.heatmap(np.abs(df.corr()),annot=True)
7 S7 J* D. G$ x3 p9 n9 e# y4 T plt.show()
8 F' d) k" R' X/ q) ]% a, b" \
$ }) t. L2 K& F I8 f2 P; Z4 e 从图中可以清楚看到,经纬度和速度跟类型相关性比较大。 1 v% L/ p1 {4 ~2 x: i8 i
& y/ ^2 F; L: w; O8 d5 M3 r2 Y- w
' v2 p% k1 k/ \# _2 m9 V6 Q+ l
1 ^* ^9 I5 p: N a2 s
$ ]& C% m# u6 Y, N$ [+ S
|