|
6 Q' X# p6 F0 l6 H6 x: G$ U1 B. h
此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设% L4 s& H& [: J6 V. e
数据分析的目的: 4 f6 R5 | P1 x: N/ Q
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
& o$ i9 R; b% y) e% _3 h7 c2 t3 D 2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布 " [9 W9 a/ _# \7 F% y# E
三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd & Q" R. J+ T- w- [5 x" ]0 t
import geopandas as gpd
3 l/ W4 g" `7 k2 F1 R from pyproj import Proj
( R. S/ L* W! k1 W from keplergl import KeplerGl % L4 s% A: ^4 L/ O! F K
from tqdm import tqdm
( T, M7 Q' y0 S import os
# C* ]9 x' _3 Z( A# c: s import matplotlib.pyplot as plt 3 e8 c! k5 ~8 i$ M' R) b
import shapely
1 T' ?- f" a8 G( D3 c import numpy as np
5 B. s7 q; ~* H% Y/ L from datetime import datetime
/ a, S5 w: r+ g import warnings $ }3 r4 c. d+ a; h) [6 E. v
warnings.filterwarnings(ignore)
0 x/ z& D6 {# F Q4 d& |( @$ T plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。 % ?0 U% B' l' c' h/ s& V+ D; D
plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。 + P" R# I3 }; F
#获取文件夹中的数据 % s" Y$ x% d1 j6 Q3 }/ H
def get_data(file_path,model):
: u/ f5 X' |' Q; @/ u( J! x assert model in [train, test], {} Not Support this type of file.format(model) 3 v3 \. [. Q8 `0 Q" ^0 L8 B
paths = os.listdir(file_path) # n/ d/ b4 s1 c1 ~3 y9 K7 N( W- ^
# print(len(paths))
2 c; `! K0 e- K. M0 V8 t tmp = [] ) b- i, X, `* ^" T2 h, m$ q
for t in tqdm(range(len(paths))): 9 z' ~7 a& Q' b- Q" B- }
p = paths[t] t7 ^; ]. C3 Z3 W8 G! x; S
with open({}/{}.format(file_path, p), encoding=utf-8) as f:
6 l. y( I1 {5 v, D( T next(f) % ]6 F# u9 Z. U, h- z
for line in f.readlines():
+ o9 `8 K) ?& Z! R9 e tmp.append(line.strip().split(,)) * U- X+ O+ F7 p
tmp_df = pd.DataFrame(tmp)
/ N& q6 j( i+ f7 I( b3 ^5 A# I2 N if model == train:
1 x* }- S8 J4 k+ M tmp_df.columns = [ID, lat, lon, speed, direction, time, type] / W, k$ C6 G( {0 I9 r
else:
( p2 R0 u1 L8 l& p% l tmp_df[type] = unknown
9 Y7 J& v" |0 a! l U% O$ @4 Y tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
2 n( x" |9 v; v# A) N) c tmp_df[lat] = tmp_df[lat].astype(float)
6 [) s1 {3 A- ]7 Z5 a, J. V tmp_df[lon] = tmp_df[lon].astype(float) / l" [) P/ l A8 k
tmp_df[speed] = tmp_df[speed].astype(float)
8 V0 K+ r& l5 }! Z2 b/ V" Q/ S0 @ tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本 J1 O- p9 S; L/ l
return tmp_df / U; q0 r& D7 G! z
# 平面坐标转经纬度,供初赛数据使用 " r# c- {& L0 a! b0 W
# 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud
7 D6 e3 w9 l/ {* I def transform_xy2lonlat(df):
' [7 Z4 G5 F& V x = df[lat].values 2 a/ Y# T5 m- I& f' u# [2 [) x; N. d
y = df[lon].values 5 \/ m. Q2 l, J% N6 y
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 ) 9 z# {/ j% E3 o
df[lon], df[lat] = p(y, x, inverse=True) ; o% s( L. Y1 ~- I z( F4 a1 ?: U2 C
return df
9 G+ C( f# S# B$ y% Q. Y# L #修改数据的时间格式
! W5 w# {8 s0 v% T' X, R' r def reformat_strtime(time_str=None, START_YEAR="2019"):
- n" J, ^2 l" V: m( _ """Reformat the strtime with the form 08 14 to START_YEAR-08-14 """ 1 ~5 v! V P3 [7 u7 g$ `( o4 C1 f
time_str_split = time_str.split(" ") 5 K, A/ D v' d" q1 n
time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] 4 R, N8 `2 V5 J/ A- a; @( D" E! V6 M
time_str_reformat = time_str_reformat + " " + time_str_split[1] 4 k& r* Z0 f* U0 c' G6 P( B
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S)
) @+ h+ x7 t4 h9 t+ G8 C9 [ return time_str_reformat
) Z% B d2 `* {; J #计算两个点的距离
2 D5 n$ ^) A7 p' l) h; z def haversine_np(lon1, lat1, lon2, lat2): 2 C- c' J3 x$ c
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
! b1 j ]4 D& d6 ^8 U dlon = lon2 - lon1
3 g% R; X8 ^* v. ]! L1 ~$ v$ g dlat = lat2 - lat1 6 ]* j3 m( y- L( g% {; c
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
8 d2 v; t/ C; Z( [ c = 2 * np.arcsin(np.sqrt(a)) / e& a+ x6 g, F- v
km = 6367 * c
" ^) m3 t- S3 u# d2 ~ return km * 1000 ( _* ~, S8 Q4 b+ _# J
def compute_traj_diff_time_distance(traj=None): , p* w) j( b0 T3 G* O! [& }8 w
"""Compute the sampling time and the coordinate distance.""" 2 R# c5 G& x5 Z
# 计算时间的差值
: F$ t Y7 D9 p2 K# j1 A time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[ - P& ]( W1 M! x7 J+ J8 @
"time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60 0 z/ Z3 a9 m0 y2 W
# 计算坐标之间的距离 + g0 i1 ~, i: w q* F# e
dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0 0 U7 j2 F& n* _) t( g1 y' {
traj["lat"].values[1:], # lat_0
/ `) f0 c# E; a9 {7 ]4 C- _& i( m traj["lon"].values[:-1], # lon_1 4 L3 E) y; o L6 j) N
traj["lat"].values[:-1] # lat_1 * R0 x% x; P9 O' u1 D
)
- G$ z" M' {( B: L # 填充第一个值 ; _4 s# t9 B N
time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()
- s* x+ E) ^, [, [, B+ g5 o dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
2 J7 F5 W; B+ T6 d traj.loc[list(traj.index),time_array] = time_diff_array . Z" f0 Z: Y$ p" V4 f: e5 I* z' Z, u9 N
traj.loc[list(traj.index),dist_array] = dist_diff_array ! Y! r* c$ a: R% X# k
return traj 3 |7 q3 }( b7 P9 y
#对轨迹进行异常点的剔除
' x$ g: n3 g; O* c7 W8 `1 G% L def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23, + ]9 a0 g) b {! V, u. G: i6 P
time_interval_maximum=200, 1 Z% I3 Q8 |# j1 y! T
coord_speed_maximum=700): 7 O' p7 ?2 {; r" t& b0 P
"""Assign the anomaly points in traj to np.nan."""
. b2 L3 w. q) p7 p0 ? def thigma_data(data_y,n):
/ l) Z6 M' x4 I' H, V data_x =[i for i in range(len(data_y))]
2 b: w. M6 z* N/ Y ymean = np.mean(data_y)
* r. x: x5 v8 e' u% D ystd = np.std(data_y)
5 |! X1 W$ S$ U u2 {8 c9 \ threshold1 = ymean - n * ystd
. d( d. J# U& e1 T+ L2 { threshold2 = ymean + n * ystd
( x1 t) _2 n5 O judge=[] $ M7 ^3 E; \) y ?2 Y4 Q; L) ~; \
for data in data_y: $ s# K2 r) q4 { P. O5 N
if (data < threshold1)|(data> threshold2):
+ q% R t, ?2 k+ H& l judge.append(True) U8 V1 B% o' j5 [4 f+ Z# C
else:
7 R# o& |4 d; d, Z; @5 m# H1 d judge.append(False)
7 O0 u% q9 L+ @ return judge - r; ?1 {0 Q+ K; [2 f' z$ O" ?
# Step 1: The speed anomaly repairing
" J. q4 i: v& b6 G' ~ is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0)
/ m) j7 U! c7 ~# X% r7 Z traj["speed"][is_speed_anomaly] = np.nan
( l- A) N+ W* {5 X* K- r& T* @ # Step 2: 根据距离和时间计算速度
' b. _: X4 k, O2 p is_anomaly = np.array([False] * len(traj)) 3 C, U3 K6 ~0 J4 T: `8 g; b) V) K1 l6 }
traj["coord_speed"] = traj["dist_array"] / traj["time_array"] 9 n8 B1 |& t% z$ u1 q. h: t
# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点
0 Y& `0 C* S! I f S4 X* I is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) d+ u. p7 q0 K3 R b
is_anomaly = is_anomaly | is_anomaly_tmp
2 s! b' Z5 U! [& X) o is_anomaly.index=traj.index 0 z, g; |* R" [ O0 m/ A2 V
# Condition 2: 轨迹点的3-sigma异常处理
" O- Q! x6 h/ _; N# I. j- N$ f traj = traj[~is_anomaly].reset_index(drop=True)
! o, m/ f1 `1 w8 ?: W# N is_anomaly = np.array([False] * len(traj))
3 f( a5 L0 s, r4 M' P if len(traj) != 0: 6 G" l! L' U+ W- c8 J- H
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean() 9 B$ t7 X4 e; E; f, b# G& P
lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean()
! w7 }1 f) K7 p: L" j! ?) b lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std & v5 l, ]2 v% x+ B
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std * b( z U4 n# W a4 R* M
is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) . y) V; w2 p* f( C
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
: A+ x/ W) j. L# z4 s, h1 A traj = traj[~is_anomaly].reset_index(drop=True) ; x1 h" }% ]: M
return traj, [len(is_speed_anomaly) - len(traj)]
: _. g* ~1 I; V+ B; m df=get_data(rC:\Users\admin\hy_round1_train_20200102,train) 5 _% j: \1 M$ a
#对轨迹进行异常点剔除,对nan值进行线性插值
H8 T3 y8 z# O2 b ID_list=list(pd.DataFrame(df[ID].value_counts()).index) * z8 u2 d% g7 e J/ G+ U* Y
DF_NEW=[] 7 B; k; W( o9 w! A; @! w
Anomaly_count=[] 8 {- d1 F- N9 b. w) s r
for ID in tqdm(ID_list):
+ N1 D- q: ~* C+ \ df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) $ T5 X8 @& a5 b* @
df_new,count=assign_traj_anomaly_points_nan(df_id) ' L4 v/ p$ O2 ]0 ^1 a2 h$ G! o6 P
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
" F1 o' ]/ X- I9 y- Z df_new = df_new.fillna(method="bfill") ; Q0 I; i$ L% I3 O% k: i) ^, y
df_new = df_new.fillna(method="ffill")
6 [1 b F4 j" D" I5 z df_new["speed"] = df_new["speed"].clip(0, 23)
% B# H$ d4 j8 u' q1 C! Z, C7 Z. N0 O Anomaly_count.append(count)#统计每个id异常点的数量有多少
$ w; k! k/ a2 b% b) \0 A5 ? DF_NEW.append(df_new) ' f" Z' H/ ]+ W- Z( S: m* f
#将数据写入到pkl格式 % o# o6 ~$ ^- k' J( P/ D$ O
load_save = Load_Save_Data() . g! d7 _# v9 l1 F
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl") + I% g1 K4 Y3 i6 @
#### 三类渔船速度和方向可视化
! e' E; _3 }3 F& L9 ] # 把训练集的所有数据,根据类别存放到不同的数据文件中 ! S& x6 N' f' C7 N& Q' ]1 U4 o
def get_diff_data():
- t: E: O" }. ~+ X p Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
! V( O2 B; F; ?: F* P1 l' s: v with open(Path,"rb") as f: ( ~% j3 t. f5 `1 V& n
total_data = pickle.load(f) . s) Y- D, L3 j) y8 S3 h
load_save = Load_Save_Data() , N& f( p3 F# t, R3 x7 `
kind_data = ["刺网","围网","拖网"]
3 _4 @5 r* q2 Q file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"]
' C- r; R- U h5 f. d for i,datax in enumerate(kind_data):
/ R4 A0 K6 z. }5 }: ]4 ?5 N data_type = [data for data in total_data if data["type"].unique()[0] == datax]
# A& S/ e5 r# g: X8 r+ t' d load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i]) 7 Y5 X- ~. e1 `( {2 z. A; W7 j
get_diff_data() 1 [7 ?" d0 h4 }- Q
#对轨迹进行异常点剔除,对nan值进行线性插值
/ J! L( u8 K3 h1 c- ]; g ID_list=list(pd.DataFrame(df[ID].value_counts()).index) ! ]3 |9 v$ z7 Z
DF_NEW=[] 7 v! b l$ O6 d% r- P; _
Anomaly_count=[]
) L h3 [& b4 m4 w1 V for ID in tqdm(ID_list):
+ O; k3 R& h1 s0 t! Q8 [ df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
- j1 T8 Q% \8 F. k- b/ E4 y df_new,count=assign_traj_anomaly_points_nan(df_id)
0 Q2 v" h% j D9 J' f! d8 i* f# c9 y df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) F6 `4 L; K- }# l
df_new = df_new.fillna(method="bfill") ( n& j4 D7 N* R4 n1 H+ T
df_new = df_new.fillna(method="ffill") 7 k4 [* @8 E& _4 p: [/ C% D
df_new["speed"] = df_new["speed"].clip(0, 23) 9 r+ e% Z0 a7 V9 u" B
Anomaly_count.append(count)#统计每个id异常点的数量有多少 % h7 }% y4 x- ~$ q3 K
DF_NEW.append(df_new)
2 T+ ?8 _' ~# n8 F" c O2 s # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列 & ^1 m. {/ \8 T$ Z/ ]/ m: _
def visualize_three_traj_speed_direction(): 1 A% B- {, F% a, [# X
fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15))
' ^$ H( D E) ]( W' n plt.subplots_adjust(wspace=0.3,hspace=0.3) % H7 d, i. u" g2 w4 u
# 随机选出刺网的三条轨迹进行可视化 % _; @; @1 w; u
file_types = ["ciwang_data","weiwang_data","tuowang_data"] & d) `- ~9 Y8 Y- t
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] % E& m5 l3 ]1 }
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"]
# O0 c; C( l+ x W1 O$ ?0 J a. _ colors = [pink, lightblue, lightgreen]
- p- V5 n7 A; m3 S; M) J5 \ for i,file_name in tqdm(enumerate(file_types)): * v: A5 h; Z8 A
datax = get_random_one_traj(type=file_name)
" _! G; ^6 ^' N( \ x_data = datax["速度"].loc[-1:].values
0 q$ d! ^) J _/ i( o; X+ z y_data = datax["方向"].loc[-1:].values 5 a5 a0 p- w4 X1 e2 ~4 M& y3 U
axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) 0 K' i; |4 W, q8 s9 L' X& Z1 g
axes[i][0].grid(alpha=2)
# ^0 e$ |5 ?. M! l axes[i][0].legend(loc="best") / z) |9 l' d* {" r+ F2 O# O
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) " _: H |- f* k( O
axes[i][1].grid(alpha=2) ! I/ `4 b4 k1 n" o( |1 u
axes[i][1].legend(loc="best") 2 T+ o4 R# z J0 h. q; J
plt.show()
- V4 X) d$ ^, x2 a visualize_three_traj_speed_direction()
: e$ F5 j* [- q/ g% f& J. b
2 |7 v9 S5 A! ?6 P 作业二:相关性分析。 6 Q1 a7 R7 W3 I* A0 j3 o: i
data_train.loc[data_train[type]==刺网,type_id]=1
1 S) w- c/ ?0 k+ Z/ j/ m0 d0 { data_train.loc[data_train[type]==围网,type_id]=2
/ \, q9 k% f9 B data_train.loc[data_train[type]==拖网,type_id]=3
3 n5 }0 F- h6 Y/ C; u f, ax = plt.subplots(figsize=(9, 6))
( Z! a t3 b N" Q, G ax = sns.heatmap(np.abs(df.corr()),annot=True)
2 q0 ^. a- X9 m4 w! }! W plt.show() ; N1 ^; e3 \1 ~8 ~" z
0 C) `% \- x; K) M
从图中可以清楚看到,经纬度和速度跟类型相关性比较大。 ( L* y% o+ ^+ b$ Y6 Y+ ~2 @5 Y* c
& U# ^* A9 l5 Y% n
# k' D2 h7 V8 m% I* W
% m4 J" y+ c$ h0 |
2 Q1 h5 M0 C8 @. s |