|
0 l1 O7 B. Z# D& D+ g: f$ I
此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设
& L$ ]2 L* |( r/ s- E 数据分析的目的:
% Z( |4 t7 P% |3 {" b0 | 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
0 ~* I! K# h% L2 C( M; \5 g5 v! Q 2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布
& J: S* L; s0 Z2 K 三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd
3 I( [ W( k8 C& v import geopandas as gpd 2 F7 T; e/ X& R, `7 l- Q( z
from pyproj import Proj ' t5 z! x* N/ {* o
from keplergl import KeplerGl % w @6 V. ~, M$ s: e" a
from tqdm import tqdm
# x9 d/ A; b* [1 M! I- L! v import os
, M6 P& U! L# P+ k import matplotlib.pyplot as plt 6 \+ n7 I. g$ K @& ]6 s
import shapely ' D$ N( H* w5 [' k4 E. k# W" F, M
import numpy as np 5 }1 C$ \# ]$ C: ?$ Y5 S+ [8 X! u
from datetime import datetime
! z* D+ t! d6 l( h import warnings
4 I- g9 |7 }% A9 f( V, H warnings.filterwarnings(ignore)
/ V9 X2 E" n$ K. G plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。
+ P# g% f3 D. i plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。
7 y6 g! S% ?4 I1 b$ @' m J- w #获取文件夹中的数据
6 S4 Z" T2 \; |! h def get_data(file_path,model):
F1 k" U4 E) X# B assert model in [train, test], {} Not Support this type of file.format(model) 1 ~) E5 w( U+ v9 f, D( Y" V
paths = os.listdir(file_path) 6 M( e: _$ G6 _5 \* X
# print(len(paths)) ; h O& U1 }5 ]9 W
tmp = []
7 n, A+ c. _* L* J0 k! w l for t in tqdm(range(len(paths))): 7 i( r7 y/ m6 @$ v: C" N5 w
p = paths[t]
8 M& m" l) o* W% s# \7 |0 N with open({}/{}.format(file_path, p), encoding=utf-8) as f: 9 l" G! q' A, P1 e9 J
next(f)
2 I4 q# F9 O8 H2 R0 [) D9 }1 N for line in f.readlines():
- u8 ~, ~6 Y% i- L0 n tmp.append(line.strip().split(,)) 7 O" `4 [# y9 c! G3 \
tmp_df = pd.DataFrame(tmp)
+ v2 K( d9 F) w% V if model == train: 4 U& S" ` I, h3 E
tmp_df.columns = [ID, lat, lon, speed, direction, time, type] 7 I( I! O5 O. k' |* w" k
else:
6 n* m& `' N$ i# O tmp_df[type] = unknown 5 L, V* X! J# V, ~; Z
tmp_df.columns = [ID, lat, lon, speed, direction, time, type] , l+ z$ a# G' r. z8 l3 h5 T1 M
tmp_df[lat] = tmp_df[lat].astype(float) 1 v( T, z/ T0 T% K! {* }+ i% n" d, w
tmp_df[lon] = tmp_df[lon].astype(float)
4 C+ E+ x1 O4 R8 K2 [4 r tmp_df[speed] = tmp_df[speed].astype(float)
2 I/ ?0 P% R# j4 f tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本
I. B/ H# `9 h1 s6 d" a. N return tmp_df , P P- m# N* w* m$ D, s
# 平面坐标转经纬度,供初赛数据使用
" F/ o" p4 v3 k% I8 N" J # 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud
% Y0 e2 o# L7 q: j! P4 ?* V def transform_xy2lonlat(df): 4 ?" V& t5 M0 D! J. J. m- W
x = df[lat].values " R0 @" \% ]% X* H% F
y = df[lon].values
8 d& i" x4 i! \+ t$ m 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 _) Q' c' T a# l: |$ ^
df[lon], df[lat] = p(y, x, inverse=True) ) B6 G6 g: ~& a) x" C! d2 |
return df 8 F& L ` N3 e; i7 T
#修改数据的时间格式 , Z; A: q: |' M& [1 m' u: e0 |
def reformat_strtime(time_str=None, START_YEAR="2019"):
/ N) Q; R9 |2 o, N q """Reformat the strtime with the form 08 14 to START_YEAR-08-14 """
) }( c+ G" {/ P3 X time_str_split = time_str.split(" ")
! }1 F$ i& I/ M/ J time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] % X# @9 O/ s' A; D: G4 ^0 e
time_str_reformat = time_str_reformat + " " + time_str_split[1] + S- k, C& [! k1 W, O- H* ` B, w9 ?
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S) " c( d1 l/ W W/ ]2 q' ~
return time_str_reformat
' U6 O3 U5 Q# t( | #计算两个点的距离
- {: ?# H# l: t3 A {4 c def haversine_np(lon1, lat1, lon2, lat2):
7 \2 l5 U8 f8 \! m- i6 w7 H; K lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
! Y$ }( M) \0 S- q; ^( ^ dlon = lon2 - lon1
# P5 d% j3 S6 [- r' ^ dlat = lat2 - lat1 " T f$ G: Z; p
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
) G- S. M! K( D8 a$ s! ^- P c = 2 * np.arcsin(np.sqrt(a)) 9 o7 d, @5 a# X2 N2 L6 `
km = 6367 * c 5 O/ P& [/ o8 `- G2 b
return km * 1000
( W8 y, m7 [7 T( a def compute_traj_diff_time_distance(traj=None):
( A3 B% q. {9 D& A """Compute the sampling time and the coordinate distance."""
+ g1 b+ I1 a9 w # 计算时间的差值
: t0 a+ J9 d) o. s: I z' D time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[ 7 y/ K/ E5 a0 Q! m
"time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60 % Y; u/ W& A7 N# A# U
# 计算坐标之间的距离
8 N9 a7 [; b) z; C) m dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0
$ L7 `% l' ~1 k4 ~8 C traj["lat"].values[1:], # lat_0 6 x+ o0 u' n. b8 S" M4 O( f/ u
traj["lon"].values[:-1], # lon_1 6 i9 L4 s; ?2 |& U$ j8 X8 | e
traj["lat"].values[:-1] # lat_1 7 D+ |4 A$ X% U/ y6 r& ^- s
)
/ F# u+ c/ t. B" U4 B% P. H # 填充第一个值
8 N( p% A' @, a time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()
- E( r1 v% B0 z. K; C6 \) Z dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
+ Q; _9 U; I8 ]- a; |& {3 R7 B$ K. N" { traj.loc[list(traj.index),time_array] = time_diff_array , y3 A2 m+ ~, {% v# X
traj.loc[list(traj.index),dist_array] = dist_diff_array
; D$ d+ b. |. H" { return traj
# w2 [2 `+ S' }! u A2 I; i #对轨迹进行异常点的剔除 0 L; r2 V* c8 f! {: j$ z* t
def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,
. B! Z8 P2 J# x, A: b time_interval_maximum=200,
7 n+ D' c! Y: b/ x coord_speed_maximum=700):
1 T4 G/ @) Y1 {! t' e Y p """Assign the anomaly points in traj to np.nan."""
& M: `; V! c8 G def thigma_data(data_y,n):
: c& v& k$ l; U, j8 [ data_x =[i for i in range(len(data_y))]
a) v Y4 G, s, N4 f! c/ t ymean = np.mean(data_y)
+ P. N# A; {2 z, s0 O+ _4 W ystd = np.std(data_y) " z. z J w9 t0 q! w
threshold1 = ymean - n * ystd % N; |. u4 e+ [
threshold2 = ymean + n * ystd
2 a. b# m F2 D( |) F/ a, x$ R4 b judge=[] & S& Q3 ]. B( B; H. \
for data in data_y: 6 n" B: P" x8 g1 F+ H1 z% z
if (data < threshold1)|(data> threshold2): , Z, N' u$ L4 S5 c2 [6 `3 q d' S
judge.append(True)
0 B f# v# b( y/ ~0 u+ B else:
* V7 F8 j1 y; u- i( E7 l judge.append(False)
; \+ I9 z" q; {/ _7 [ return judge 0 v" ]3 V" W3 k0 q
# Step 1: The speed anomaly repairing
8 G$ c/ C$ X# `, n6 |. v is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) ; h$ v3 X( M5 {, R) Y5 |, T
traj["speed"][is_speed_anomaly] = np.nan ' G5 k% l! b2 X1 r0 E
# Step 2: 根据距离和时间计算速度
- C* f* K+ [. d9 Y is_anomaly = np.array([False] * len(traj)) 7 N: a/ Z* H" j4 r8 ` g$ r
traj["coord_speed"] = traj["dist_array"] / traj["time_array"] 1 K! J% H" e2 O6 l9 }0 ~
# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点
}. D3 m2 X# Y, Y6 c is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3))
$ z) K" l7 w& |3 k7 I is_anomaly = is_anomaly | is_anomaly_tmp & u$ s/ G5 n& U$ V& X
is_anomaly.index=traj.index
% ]8 ], m8 b9 N- F2 d( l # Condition 2: 轨迹点的3-sigma异常处理 9 Z/ G2 p6 [1 b0 b
traj = traj[~is_anomaly].reset_index(drop=True)
$ K6 c" U9 }1 V8 w/ s* [ is_anomaly = np.array([False] * len(traj)) $ j! g. k4 Z9 u
if len(traj) != 0: 3 [. B5 E2 M8 V6 b6 u+ D+ ^
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
N, h0 }* M" M lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean() 9 J& Q2 j9 ~$ Z* [- y
lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std
; j7 D* G) B0 m# q, k# M lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std
$ b3 M/ P6 p& ^( K) o# } is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low))
& F/ w! g* K( C9 f4 u+ L is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low)) % ~/ Z& D0 Q* F
traj = traj[~is_anomaly].reset_index(drop=True) : f" ?# ]: X8 e
return traj, [len(is_speed_anomaly) - len(traj)] % L2 Y; `/ B" ]: ^( P- c
df=get_data(rC:\Users\admin\hy_round1_train_20200102,train)
! J+ C* H& P" X' B; n$ d ? #对轨迹进行异常点剔除,对nan值进行线性插值
0 l# h0 n3 n1 ~' v ID_list=list(pd.DataFrame(df[ID].value_counts()).index) 4 t) p1 U+ W4 k, L' H' d
DF_NEW=[]
, W+ d& l) Q7 M$ C& p& S t5 u1 J Anomaly_count=[]
% c" S; D. j# P0 |9 c5 Y, O7 z# ]3 W for ID in tqdm(ID_list): / B$ y! U3 k6 P( D4 r- D! R
df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) , F% `( A- n0 o2 ^- S6 n7 _8 r
df_new,count=assign_traj_anomaly_points_nan(df_id)
5 I" v4 H k7 t% y" d df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
/ g/ Q8 D# f6 V2 K- X" J. g& I df_new = df_new.fillna(method="bfill") 8 v5 T& J: t9 d6 L% `5 R
df_new = df_new.fillna(method="ffill")
6 z* r- i; Q) ~2 g# W9 w df_new["speed"] = df_new["speed"].clip(0, 23) 2 q) f2 ], t6 v+ r1 p" I5 x Q! E
Anomaly_count.append(count)#统计每个id异常点的数量有多少
$ r- u/ M: z, L/ C2 R- R$ ? DF_NEW.append(df_new)
7 u2 V0 F x0 f8 [' C' V #将数据写入到pkl格式 " r, Q8 J6 c/ N- \7 Q2 w. F/ z
load_save = Load_Save_Data() 6 \& {5 X+ [ l0 S( T
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")
1 x i0 W$ t3 w1 I4 u+ E$ g" w* d #### 三类渔船速度和方向可视化
# t$ N: K5 J2 C) r2 j # 把训练集的所有数据,根据类别存放到不同的数据文件中
! D: F. E# ]6 b( ^" T2 k def get_diff_data():
0 M- M) A# \ D; n$ ~3 f Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
8 K- h$ v+ B' h$ w! V with open(Path,"rb") as f:
+ H1 u( l% v$ @& n0 l2 r- F total_data = pickle.load(f)
P X% q( L- }8 p1 k load_save = Load_Save_Data() ) b! ~- a; q6 k
kind_data = ["刺网","围网","拖网"]
$ ~; j( s3 V6 Z: l8 z$ N. o- g file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"] - m: x0 I7 w. E h# B
for i,datax in enumerate(kind_data): , r! w- O \5 G$ Y$ _
data_type = [data for data in total_data if data["type"].unique()[0] == datax]
' ?5 Z- D+ C! e b- _- ]) K9 Y* ~ load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
/ T. k9 g4 s( Z5 x/ M+ F get_diff_data() : P5 t3 @5 @& R$ z
#对轨迹进行异常点剔除,对nan值进行线性插值
3 X/ A: ]; T K ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
f1 }" _: R% u R- B DF_NEW=[] 9 m) V( @; U9 ?. G2 b( q
Anomaly_count=[]
$ L. |% z+ J$ w- J/ B for ID in tqdm(ID_list): . G1 h( w" T( R9 h3 w. i) k
df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) 7 N$ Z1 k3 ], k( R( E: {5 P1 m2 D
df_new,count=assign_traj_anomaly_points_nan(df_id) * Y; k% ?# W- e& p0 J7 j
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) k) c! L$ N0 X7 b9 i% O; y
df_new = df_new.fillna(method="bfill")
" R2 G- O* N# Q' k5 A! i5 s df_new = df_new.fillna(method="ffill") ; L- _/ b1 D# g$ c$ `
df_new["speed"] = df_new["speed"].clip(0, 23)
8 o7 @, }1 m d9 R2 m Anomaly_count.append(count)#统计每个id异常点的数量有多少
* i* `& }4 a$ h) ~' Z& [7 r DF_NEW.append(df_new)
j; n" P6 z/ w: V' j0 @, t0 [ # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列 ]3 c1 ]. Q2 S4 d6 V8 J/ k% f5 ^
def visualize_three_traj_speed_direction(): 7 d1 u/ n4 N4 X% C1 Q
fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15))
4 c \! J9 t9 D: H plt.subplots_adjust(wspace=0.3,hspace=0.3) , |% a+ A' F! v, o' C
# 随机选出刺网的三条轨迹进行可视化 2 c9 F/ b4 ?# C: G7 M0 N4 ]
file_types = ["ciwang_data","weiwang_data","tuowang_data"]
3 W) r" S( \* }$ R1 { speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] ) p$ ~1 |$ |, s0 g+ @( a
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"]
/ ^. m9 `, Y# R# }6 H colors = [pink, lightblue, lightgreen] ( b2 P* F) s# b% f$ v
for i,file_name in tqdm(enumerate(file_types)):
! s I1 K3 z3 B( y% E datax = get_random_one_traj(type=file_name) ' Z8 {' P. T7 Z. ^# X1 @/ L
x_data = datax["速度"].loc[-1:].values 6 |$ V& J* b: k' Q
y_data = datax["方向"].loc[-1:].values
2 z0 R! `. u6 ^8 m axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) , d: F3 x, L1 [$ Z
axes[i][0].grid(alpha=2) 1 X7 i+ j7 }8 u! R4 k5 K
axes[i][0].legend(loc="best") , e5 s# `, ~7 \. N( W* \2 a
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) 7 X9 U. y" R' ~5 N) o
axes[i][1].grid(alpha=2)
: v# o$ _$ d3 v& S$ B f0 K) f axes[i][1].legend(loc="best") # w. Z8 x0 S3 P2 z; U# P
plt.show()
! K, v8 i$ F" J visualize_three_traj_speed_direction()
1 C3 s* t o8 y1 w, c" M1 N7 S; M
6 }2 U; C. f' M: d5 d: u* n. V" h4 W 作业二:相关性分析。 6 h8 T" U) I+ | k! [6 z; n' n( z
data_train.loc[data_train[type]==刺网,type_id]=1 ' e4 O0 j1 z4 f& ]- D! `
data_train.loc[data_train[type]==围网,type_id]=2 - H0 c5 `( w6 A& N) p" G0 m, e
data_train.loc[data_train[type]==拖网,type_id]=3 7 q* |1 s8 ?+ q* C1 e% I
f, ax = plt.subplots(figsize=(9, 6))
1 Z5 X7 F9 a' o Y% Y ax = sns.heatmap(np.abs(df.corr()),annot=True) # t$ |. |9 }+ [( _) Q
plt.show()
; u6 L* l# z" I. f7 O
- G3 j0 I! s' F- I* j 从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
4 g3 t+ t6 l7 W" z5 ~
7 [, l1 R8 P8 V5 n6 |' s3 |9 q
) W( j' f0 \/ k9 [3 K( w1 x4 t' u
/ |: w" d. `6 k& y |