5 C& e1 N9 R9 x. C8 r 此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设3 `0 h4 z( Y! ?1 U
数据分析的目的: * D& n' ]4 U8 e$ N8 t1 d
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 + F5 X0 y) W% ]
2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布
6 L0 a7 ]( G( Y6 q- F' r9 S& | 三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd
6 g) Q$ q, D' j P( L import geopandas as gpd * U0 Y, N+ r+ m# g
from pyproj import Proj 5 o: u+ @7 J/ }* _ m
from keplergl import KeplerGl
% j0 R& A/ i2 G8 r5 b from tqdm import tqdm 6 W- v1 O' ~" l; K5 `
import os / d6 B) v+ `8 x0 `4 G1 b1 m$ p
import matplotlib.pyplot as plt % n& Q4 W5 l9 o8 S: o
import shapely , O1 f. Y; I; F) |( a: c% g
import numpy as np
* ^0 p9 d% [, ]0 v3 ? from datetime import datetime $ W: K* y( ^3 u; s1 S" ?6 O$ F
import warnings
4 y; }( P* H* X: D warnings.filterwarnings(ignore) & @3 a7 j3 j6 {# N& b1 z
plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。 I H5 y) Q( N& b: I
plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。
, b5 z) ^5 h* K! {' ~' O #获取文件夹中的数据 + g1 V7 s1 M7 b3 `% I
def get_data(file_path,model):
' w: r+ c! ^5 X, H0 A! q3 [ assert model in [train, test], {} Not Support this type of file.format(model)
- g5 ^& ?: m, a y paths = os.listdir(file_path) ) {% ~; ?7 `4 l- ^5 J4 o
# print(len(paths)) " F- j9 K% H8 c' C
tmp = []
# i: G8 k+ ?9 S _- X. T for t in tqdm(range(len(paths))): 0 l/ H- y( I, h$ g/ n
p = paths[t]
7 L; t# U$ Q4 v4 M5 E1 [- s( a with open({}/{}.format(file_path, p), encoding=utf-8) as f: ) Q$ j9 a2 g0 [4 N' ^1 d, `
next(f)
! o' D# [& a' f; S for line in f.readlines(): - W/ \1 T0 F6 j C
tmp.append(line.strip().split(,))
+ }1 V" u7 M2 z& U1 s tmp_df = pd.DataFrame(tmp)
& _( a3 `: `5 h# n if model == train:
) u! j5 R( _( g8 E' ?) x tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
: N* e1 t) [, v' n, R6 M; ~" a else:
6 a; T& R- n- _! V# r# T6 K. @ tmp_df[type] = unknown
7 ~5 {4 \+ S4 @/ I5 h tmp_df.columns = [ID, lat, lon, speed, direction, time, type] : x' r* L5 g: y X( ~ s
tmp_df[lat] = tmp_df[lat].astype(float) * ?7 ? T" O! Y
tmp_df[lon] = tmp_df[lon].astype(float) , G- h" v( V% H/ p, z* E
tmp_df[speed] = tmp_df[speed].astype(float)
' h9 e- H* @6 T3 i/ x tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本 # z7 H9 y0 N! c# Y7 W" v; I
return tmp_df
: Q6 |- O6 o* A # 平面坐标转经纬度,供初赛数据使用 & Y6 b5 k( s/ I2 [: V# h
# 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud
9 R; {6 `" P" h5 ?5 s6 \: h def transform_xy2lonlat(df):
0 L n' z1 c" F8 {, R x = df[lat].values
$ L* ^7 y" ^& D# L1 o1 r/ s y = df[lon].values : y2 t; L& `7 ?: X0 _
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 )
& F2 d% e+ m0 o; l+ u8 c8 U# B/ I: }: k* ` df[lon], df[lat] = p(y, x, inverse=True) / H# f2 @" b% T5 X0 k, S8 a
return df
5 {" j+ y/ D% k/ d" o9 T4 [7 P" h6 [ #修改数据的时间格式
7 F. n- e5 r/ [; y def reformat_strtime(time_str=None, START_YEAR="2019"): 8 c- j2 P" T8 I. F
"""Reformat the strtime with the form 08 14 to START_YEAR-08-14 """
6 @+ l! b4 M' \# O( h, I time_str_split = time_str.split(" ")
& W5 S& l3 n8 R" U! z2 z time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] : w9 r% J' N+ s I& _
time_str_reformat = time_str_reformat + " " + time_str_split[1]
: ~6 w1 B$ N; {8 O" P* O # time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S) . M: ?5 k2 ^ f" a
return time_str_reformat 4 R1 Y) V f) C
#计算两个点的距离
9 w$ x1 M7 g$ ~ def haversine_np(lon1, lat1, lon2, lat2): % ]% p8 K' n5 P) O$ b/ o/ O/ S
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) / Q; Q. s8 @+ c! i [; o
dlon = lon2 - lon1
, q- l" @ D R dlat = lat2 - lat1
6 \% Q0 [' i9 ^- k0 u4 O* J- n# v a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
8 U7 s- W/ D/ E# N ] c = 2 * np.arcsin(np.sqrt(a)) 6 W' B0 P' T: e7 E$ w
km = 6367 * c
1 E( S+ {/ \0 Z/ _- X' b, D- y$ ? return km * 1000 ' C% e p/ f1 H/ N6 p! t/ y
def compute_traj_diff_time_distance(traj=None): 5 C0 Q+ `# k2 [3 j2 l2 c
"""Compute the sampling time and the coordinate distance.""" , x1 I* b5 _% V- N" h
# 计算时间的差值
+ Q0 J l- m& i9 P3 \+ C+ u time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[ " F" R4 E& o$ ]. Z1 p8 [3 \+ J
"time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60 + A8 j6 A: f; u1 l8 Q }. p, F$ z
# 计算坐标之间的距离
9 J: j0 n' ]! m: `. ]$ j dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0 3 _$ r5 F) v' v# U# r
traj["lat"].values[1:], # lat_0 $ W6 ~; P. f: i! ^$ V4 v' t1 N- E
traj["lon"].values[:-1], # lon_1 0 ^) g$ _; ?2 ~8 K# C
traj["lat"].values[:-1] # lat_1 8 t* l! G+ h, \# q
) 0 A6 }# G" p6 g0 j, _/ ?7 o+ |7 V
# 填充第一个值 5 X. ~4 {* T& `& Z/ A* M
time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist() ) r2 L& k% c) R2 i
dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
! a5 q& C0 j) ? traj.loc[list(traj.index),time_array] = time_diff_array
/ h, E: x6 ]/ n. h, W) h& g ?# w traj.loc[list(traj.index),dist_array] = dist_diff_array 8 t( b4 k- n+ y" G" a J6 E+ ]
return traj 6 C6 }) b! M$ p& j- X1 X
#对轨迹进行异常点的剔除 0 z4 V5 g& R( S) Q$ Y4 c, s; S, u& y! u
def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23, ) f9 i- E5 O0 H+ s1 x
time_interval_maximum=200,
. Z9 o8 p; q I$ z- _2 U) K* K coord_speed_maximum=700):
+ B0 t' B. t# l/ B4 U, u """Assign the anomaly points in traj to np.nan."""
6 g0 o- a: |3 n' J6 y- q def thigma_data(data_y,n):
2 ~7 i0 r0 C0 }5 E/ K data_x =[i for i in range(len(data_y))] % e M7 U4 W9 {, |5 L" _! O/ V' c
ymean = np.mean(data_y) - `( x/ ~% I& w5 a/ V
ystd = np.std(data_y)
+ D! G5 U' Q, e( R threshold1 = ymean - n * ystd 3 [1 y- A9 A% ]9 A: x& ]
threshold2 = ymean + n * ystd
- \2 @- ?& W! p: C judge=[]
$ l. N {3 a1 o" o' x, B( F j) n+ G for data in data_y:
. S$ Q& |" o5 J, W! _8 i: R if (data < threshold1)|(data> threshold2):
0 J6 v, Y0 B! A* o) C' _. a( U judge.append(True) + w& d0 [8 [1 F% w& x
else: ( _3 l) _+ M- o' c% X" Y
judge.append(False)
9 c0 g% ?, Y5 u: f7 \3 G return judge
0 ^$ z' o5 O3 b: U2 R) i# Y # Step 1: The speed anomaly repairing
: D2 B8 V* p6 ~6 f8 v4 s. | is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) # l/ S6 _* u6 L4 ?! n
traj["speed"][is_speed_anomaly] = np.nan
0 C, w: a# x) h # Step 2: 根据距离和时间计算速度
! }1 ^' {) ^4 w5 f W is_anomaly = np.array([False] * len(traj))
' X6 K! \1 G; Q p0 C0 x' G traj["coord_speed"] = traj["dist_array"] / traj["time_array"] ! R8 p+ L& ?6 U
# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点
% D) D/ k1 l C" h% d is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3))
$ V# F: O6 U2 l2 n( S is_anomaly = is_anomaly | is_anomaly_tmp # w: `- x! H. n0 ]
is_anomaly.index=traj.index }0 N3 _- a9 e4 ?; l1 ?
# Condition 2: 轨迹点的3-sigma异常处理
( `1 t3 P$ W8 ^$ q! X0 w1 ` traj = traj[~is_anomaly].reset_index(drop=True)
m1 M. G P5 y% @# [( [8 t is_anomaly = np.array([False] * len(traj)) 0 C, g4 K: Q* v# W! U. M1 N
if len(traj) != 0: * V/ F/ ? _# u$ f
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
) X( v/ j2 o; k# ?* Y2 m lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean()
6 w' V% ^9 K0 O! L4 | lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std . W, s2 z( f" a4 [" d1 O) X
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std
" h7 j8 ?1 N/ W3 M8 k9 W is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) - H6 Y6 P8 S4 F( D
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
' D# o7 I& X/ s/ u* I traj = traj[~is_anomaly].reset_index(drop=True)
3 j; K c1 H |: h: w+ m return traj, [len(is_speed_anomaly) - len(traj)] A$ W& w' c' r5 s( b+ L
df=get_data(rC:\Users\admin\hy_round1_train_20200102,train) ; u! @: D( U- j
#对轨迹进行异常点剔除,对nan值进行线性插值 3 W- F8 c3 H7 W {9 _5 j* g) |) n6 @! S
ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
1 C% R B" Z1 E' L% r DF_NEW=[]
0 C& b& [5 ~4 h+ j Anomaly_count=[] 0 X L; h, N' J% `9 `
for ID in tqdm(ID_list):
9 W/ P7 ~# E) u4 `) _ df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
. a6 ]0 i% t. n* V; T7 f df_new,count=assign_traj_anomaly_points_nan(df_id)
a- W0 K$ y% Q8 n4 p. H. [ df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) ) ~7 X9 x5 H J6 B. t4 b
df_new = df_new.fillna(method="bfill")
! G' }& e Z7 K7 R' U# s, l df_new = df_new.fillna(method="ffill") & Y1 a% d7 B- Y' }* D, }5 N+ y
df_new["speed"] = df_new["speed"].clip(0, 23) ) Q8 H% T: W0 `7 {5 O7 i
Anomaly_count.append(count)#统计每个id异常点的数量有多少 - O2 O1 l" [* ]. L, ]; O
DF_NEW.append(df_new) 1 Z" v( b; S- S u; r6 I$ h
#将数据写入到pkl格式 . X! _6 X. X' |, H( D. B
load_save = Load_Save_Data() 7 ?" ]% i; z$ O% i: | Y
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl") 8 g' m7 X, \ M% s+ j( ~1 ^
#### 三类渔船速度和方向可视化 , G) M! b' l! V2 N5 t/ d8 {- _. H0 W
# 把训练集的所有数据,根据类别存放到不同的数据文件中 ; o* I) I% l& k, h
def get_diff_data(): 3 W: e+ f( [6 \: L2 V' u
Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
1 s) w& b3 ]" w6 b% r with open(Path,"rb") as f: : c9 N5 M( z. \9 p
total_data = pickle.load(f)
2 d* r$ m, r# }& @ load_save = Load_Save_Data()
0 K1 y8 r f. W% { m kind_data = ["刺网","围网","拖网"] , k5 W! l0 p& ]3 p S
file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"] 1 Z6 Z+ Y9 ]( g5 }( K& _2 V5 F
for i,datax in enumerate(kind_data): 5 M% w5 I! y) U" G3 q4 @& I8 x
data_type = [data for data in total_data if data["type"].unique()[0] == datax] / u i7 P4 l( ~
load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i]) ! ^! r7 y& N* o
get_diff_data() " l9 J+ [8 t" f" l
#对轨迹进行异常点剔除,对nan值进行线性插值
) j7 L. E% X2 d" h ID_list=list(pd.DataFrame(df[ID].value_counts()).index) 8 L( ~& g4 E/ x
DF_NEW=[] 3 ^0 \$ i, j" S3 p6 }" e% v0 u
Anomaly_count=[] ! o8 i9 F" U- k( b: w4 h1 ]
for ID in tqdm(ID_list):
6 ~6 S. p A; |, p df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
; o$ m/ N- q& `% m" c df_new,count=assign_traj_anomaly_points_nan(df_id)
2 X* x0 F% |' n( M9 q df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) * R4 E+ N, W+ D# u5 u6 J5 x
df_new = df_new.fillna(method="bfill")
1 ?, X/ x4 \. \2 S* [. M1 P4 w df_new = df_new.fillna(method="ffill")
" q0 a% G Z3 t5 ?, g df_new["speed"] = df_new["speed"].clip(0, 23)
: k3 i5 q/ I4 O6 C: T5 Q Anomaly_count.append(count)#统计每个id异常点的数量有多少 + M2 d3 u' R" w' c4 u
DF_NEW.append(df_new)
0 P/ N8 N9 z& O% o # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列
" p9 m6 i! ?& \3 ]- S9 V1 R0 Q def visualize_three_traj_speed_direction():
" t: s8 Q5 U& F- X! H fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15)) 5 c7 U/ M: b( [6 m) G$ `
plt.subplots_adjust(wspace=0.3,hspace=0.3)
) W" h. J( r+ p/ `2 | # 随机选出刺网的三条轨迹进行可视化 3 M0 [- V! x! Y3 W% t
file_types = ["ciwang_data","weiwang_data","tuowang_data"]
- J( m" R3 S( Q" _% v9 t speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] $ k' h7 P9 B, m6 `2 l. h N
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"]
: T+ Q, A( M { colors = [pink, lightblue, lightgreen]
$ S6 C4 [( c: D. T for i,file_name in tqdm(enumerate(file_types)): w/ }4 U5 P5 J6 U
datax = get_random_one_traj(type=file_name)
% _( Z1 K, J6 h( ? x_data = datax["速度"].loc[-1:].values " R& b+ M. W' T+ Y& O J% t
y_data = datax["方向"].loc[-1:].values . {, ?7 `! ^. c: \
axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) % ~# S: }* ~; G, e
axes[i][0].grid(alpha=2) ! \3 Q" `/ C E! i1 q
axes[i][0].legend(loc="best")
6 e7 v* ?: J$ J9 g4 n' a axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) 6 g/ n. A2 W, g, ? \! m
axes[i][1].grid(alpha=2)
) M2 e* a9 C$ a3 I4 y0 }# [5 F) h4 D axes[i][1].legend(loc="best")
; t+ v* a4 |- K1 l" S" v plt.show() |4 r$ J0 V! @5 p
visualize_three_traj_speed_direction() ' X% k5 i& f, R( G! q4 \
( L# X( w! P) x- e* A$ _: s, j, D9 R) X
作业二:相关性分析。 : _% I. W+ F" m$ g- c* H) d
data_train.loc[data_train[type]==刺网,type_id]=1 , Y2 l4 f' [/ U$ ?
data_train.loc[data_train[type]==围网,type_id]=2 3 y7 m, o7 [# Z% e3 i# i
data_train.loc[data_train[type]==拖网,type_id]=3
. ]" F4 X1 }: `1 \ f, ax = plt.subplots(figsize=(9, 6)) % x( W( u; _- u( d% J
ax = sns.heatmap(np.abs(df.corr()),annot=True) % A0 M. i+ m V. a; v( C& M# w( q" N
plt.show()
# s" J$ `: a; Y8 p
: E* B: h& u: B# C( H1 e 从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
" w9 W) H; f& X* T& N ^
7 r5 ^$ ?( e5 D" f' z8 k) `% _
; c5 K! u: X( e0 n6 h) D4 M5 W9 c3 j4 @! F- Y9 M
" R# k1 q8 D4 O; V2 f7 N$ D2 u
|