- ^& a& v: U( V. V
此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设
7 K0 ]. U. q9 b$ `2 e 数据分析的目的:
3 P8 o& C2 U; P 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 2 A* K& a+ q) H4 [
2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布
+ ?' E, i' Q' l/ z2 X 三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd : v( F' w9 D( x7 E* z
import geopandas as gpd
7 T0 E! E6 L& U$ ?- c from pyproj import Proj
/ [1 ~7 u, `7 q" U; D from keplergl import KeplerGl
r# r; M, c# ]7 w1 J' { from tqdm import tqdm 2 C* _& x/ {9 y, c
import os ! M5 d/ h7 W5 r+ s
import matplotlib.pyplot as plt
0 g( q3 q& q# [/ V1 Y import shapely ! N; |& B% W1 M
import numpy as np
1 V8 }8 f8 X8 ~1 L6 P5 Y! B from datetime import datetime
! \( ?; G% L# R% A! z; t import warnings 8 u* R1 t- [5 {2 T
warnings.filterwarnings(ignore)
% d, E5 d" i7 M7 @8 V plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。
3 V6 D3 L7 `/ n( A M* ^ plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。 5 m3 x# U# l1 E) r) W) B4 j' G; W5 j
#获取文件夹中的数据 4 B" f4 q l# l5 j2 E
def get_data(file_path,model):
5 @) {) s. q m5 y assert model in [train, test], {} Not Support this type of file.format(model) 7 `) l9 t" N5 R" |
paths = os.listdir(file_path) $ v. @: ~$ Y* I, q! R
# print(len(paths))
4 z$ z2 z G( U3 T d$ I8 o2 t tmp = [] 5 I" n& u& H- c) A" X& B. C/ Z
for t in tqdm(range(len(paths))):
) t( m- R# Y% [8 K5 L4 z0 m' m+ c' \ p = paths[t] : t* A9 k3 t8 S8 \, z8 O
with open({}/{}.format(file_path, p), encoding=utf-8) as f: / t0 H& {2 T% T; y
next(f)
+ u1 t( w2 n2 F# X. ` for line in f.readlines(): ( b- v: w2 w1 n! ^% ^
tmp.append(line.strip().split(,))
& {1 t- \. h6 u ]3 X tmp_df = pd.DataFrame(tmp)
5 _7 n* `' {6 Y& s1 ]' z if model == train: ( }" A: K# q! i7 f
tmp_df.columns = [ID, lat, lon, speed, direction, time, type] 5 O. { o. F" K8 L4 J
else: 7 C9 f& C8 w, Z0 j: s/ K
tmp_df[type] = unknown
8 E9 Z& b. Y% Q8 z0 h6 {9 k. H* x tmp_df.columns = [ID, lat, lon, speed, direction, time, type] & g7 A" b& {' C7 P! ?
tmp_df[lat] = tmp_df[lat].astype(float)
+ y5 q3 B" F3 x7 K6 h1 F tmp_df[lon] = tmp_df[lon].astype(float)
4 q. L+ g# i9 i2 X1 s tmp_df[speed] = tmp_df[speed].astype(float) # u/ ^$ y# {) q' s( ], R8 @
tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本 4 }& k% V1 n" g* Z+ f/ m% G- ^& H
return tmp_df
% O9 U$ O. f' |/ A/ j" B! F # 平面坐标转经纬度,供初赛数据使用
/ D/ {4 g/ H. b$ s- F1 W# Q # 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud + i. U! i/ l P8 J( H6 U
def transform_xy2lonlat(df):
8 q: C- @0 }4 } x = df[lat].values
6 I3 e8 ^# c7 g# V y = df[lon].values ! T7 h4 V( X8 Q0 k, F3 M! f
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 ) & x4 o- J$ j6 ~6 N& s X9 \# O
df[lon], df[lat] = p(y, x, inverse=True) 7 i5 w% n6 ~" g* w( T
return df
& M6 h1 _6 G# P0 Q2 U8 V #修改数据的时间格式 0 G8 G8 k/ c$ `) w- U
def reformat_strtime(time_str=None, START_YEAR="2019"): % i: l- R& S! w/ P6 c/ L1 { u
"""Reformat the strtime with the form 08 14 to START_YEAR-08-14 """
6 E! ~6 v4 `' f/ L4 V- }4 e5 V time_str_split = time_str.split(" ") R$ `9 [+ ?6 C# M
time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] 5 [. R) V1 {8 L( D% V1 b
time_str_reformat = time_str_reformat + " " + time_str_split[1] - d- X4 v2 m, |& c8 G
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S)
8 v! z5 l/ p N5 E. K return time_str_reformat
, {$ ]% R4 l v7 f8 \/ N1 }" |" A7 ? #计算两个点的距离 : A% V* J& T. h& S
def haversine_np(lon1, lat1, lon2, lat2): 7 O* ~& q8 `3 c! E7 E
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) % c2 O- b/ \5 y7 ~& m7 l
dlon = lon2 - lon1 0 H5 P+ C2 y. B: V7 s( B, }# o
dlat = lat2 - lat1
& U; u$ X# O. C$ | a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
! _8 k2 B( {6 J c = 2 * np.arcsin(np.sqrt(a))
9 j+ O7 O+ A- u+ o X+ Y1 g km = 6367 * c $ L& J& l, S/ w( s+ n+ }
return km * 1000
8 x( j7 j% \( Y R def compute_traj_diff_time_distance(traj=None):
/ k% [& ]; t+ m& y B; x """Compute the sampling time and the coordinate distance.""" % W8 B; {- g C( N/ J. l5 i% s
# 计算时间的差值
5 ]: q* ^) R! Y! F time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[ 5 ^; X, U: }8 L0 ^( g
"time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60
1 M- _) i" r" ?3 @, t # 计算坐标之间的距离
. G" N" t7 k( \) f$ k0 I dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0 3 M! @4 ?9 ~ }- Q& J" |$ K
traj["lat"].values[1:], # lat_0 . ~/ i( N# U5 s# r/ O
traj["lon"].values[:-1], # lon_1
; _. Z) H1 g: t% k7 }: n/ r traj["lat"].values[:-1] # lat_1 J9 l7 |- G! w y a( z$ w
) 4 u( T. n4 _2 {/ }+ @2 c. Q
# 填充第一个值
" p% b5 L2 L0 V) ~ time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()
|6 k) U5 o$ { dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist() % v# j; V' P$ F
traj.loc[list(traj.index),time_array] = time_diff_array
! w# l! c! U) B- J4 `6 n+ Y traj.loc[list(traj.index),dist_array] = dist_diff_array
# h/ @/ i0 D4 K- x6 k return traj
; J6 m9 O) P4 @1 S7 i; Z ? #对轨迹进行异常点的剔除
2 }8 Y2 ~* ^% E6 ?$ l def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,
9 z; L( [4 I. f3 h1 f/ J time_interval_maximum=200, - m" j6 I4 j; S: T
coord_speed_maximum=700): ! c6 W# r$ E7 r. U( M+ o, m
"""Assign the anomaly points in traj to np.nan.""" 2 U* s8 w' U/ I) T8 k
def thigma_data(data_y,n): ( e& [# g5 i E K
data_x =[i for i in range(len(data_y))]
# E& Z8 ]( ?8 m3 u! b ymean = np.mean(data_y) / _. f$ s0 |0 s4 s5 P
ystd = np.std(data_y)
6 Z- R, g, o0 I1 v% A) g threshold1 = ymean - n * ystd 5 m8 a* K1 ` j" C; M% p9 J u
threshold2 = ymean + n * ystd & S7 @/ o u& g
judge=[]
* x0 o; T" D4 j/ j for data in data_y:
i) N* { g0 ^. v! e' }! _: G if (data < threshold1)|(data> threshold2): 8 c- E" Y( ?( {" [, w1 p" B
judge.append(True) 0 j/ t7 Y5 d% [/ Y+ O
else: 7 h3 |4 p' X9 }& B3 F e
judge.append(False) * I9 `, e$ n6 P+ { W6 J0 @ j
return judge
0 J8 D# X# b1 l4 l! x ` # Step 1: The speed anomaly repairing 8 l& A" E4 @3 Z; f3 O
is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) # K! U+ Z# y. D. J( r0 v) U
traj["speed"][is_speed_anomaly] = np.nan
" U* }& h/ [1 F T9 D9 b. R # Step 2: 根据距离和时间计算速度
' |6 j6 M2 u2 y% x8 w is_anomaly = np.array([False] * len(traj))
8 [ n0 U/ k0 R8 b$ ] traj["coord_speed"] = traj["dist_array"] / traj["time_array"]
* E- _9 u0 U2 s' h7 E3 ~9 {& a # Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点
3 C+ w9 ~# @- B5 K$ Q7 k is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3))
' l( O' [: o( T$ I is_anomaly = is_anomaly | is_anomaly_tmp . |$ V; k' ~5 O2 ~" |
is_anomaly.index=traj.index + G6 y" @0 _( O- P
# Condition 2: 轨迹点的3-sigma异常处理
' H' ]0 _- p; y traj = traj[~is_anomaly].reset_index(drop=True)
; v* N, r" ^; r& P3 a8 S: V is_anomaly = np.array([False] * len(traj)) % o& M/ s$ W/ l" B
if len(traj) != 0: 2 L$ w" d7 @- I! L) S$ l
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean() ; N! c" |; n L+ {
lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean() : L: N7 b! w' Q% v X; S
lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std " t" u# C8 h8 \# U
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std / ~% N+ p1 o4 Z& Q
is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) - u) o! t! b/ R: ~) B
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low)) : R) s. c3 l8 w, s
traj = traj[~is_anomaly].reset_index(drop=True) 5 [: h2 b: A1 O
return traj, [len(is_speed_anomaly) - len(traj)]
1 U) g3 I( E7 B- K df=get_data(rC:\Users\admin\hy_round1_train_20200102,train)
; Y: \$ L C% k5 n0 p/ P* z #对轨迹进行异常点剔除,对nan值进行线性插值
! d9 I& ?2 @1 w+ H0 j7 n1 P ID_list=list(pd.DataFrame(df[ID].value_counts()).index) 2 o0 b v; p+ M; a& J* d, K
DF_NEW=[]
6 n% B9 ]4 o4 ^8 b4 ^ Anomaly_count=[]
3 f4 _0 e% X7 e for ID in tqdm(ID_list):
3 T. w; j/ d( M# W3 s- |1 p df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) & U& [8 A4 P% c% y' n0 f, }: e
df_new,count=assign_traj_anomaly_points_nan(df_id) ! W( o' ?% X5 l6 k3 w
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) 6 g; r% d2 g: r$ T: k) `
df_new = df_new.fillna(method="bfill") ( O0 J. ]7 [. \9 Z6 ]8 A# K1 C4 E6 B0 J
df_new = df_new.fillna(method="ffill")
3 A/ V. O z5 f) q$ _' {( n df_new["speed"] = df_new["speed"].clip(0, 23)
" }, H( y4 F, ?. Y7 P Anomaly_count.append(count)#统计每个id异常点的数量有多少
5 f1 T$ w6 E6 T1 S4 y DF_NEW.append(df_new) & ?8 C: c9 m" r
#将数据写入到pkl格式 ! ?) c, z* w' X0 R, e0 r/ a
load_save = Load_Save_Data() , Y3 e) Q: v' U3 ]% t
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl") ) T, ?- H/ t0 S: x1 L0 ^
#### 三类渔船速度和方向可视化 " w# \$ `7 O4 M- |: R: T2 W
# 把训练集的所有数据,根据类别存放到不同的数据文件中 . r( u# X8 n; @
def get_diff_data():
- [' D7 z4 k, M/ L2 ?, ^; ` Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl" 8 D3 z9 y, Z7 p& v
with open(Path,"rb") as f:
. ?4 c1 I B' ]$ Y4 E total_data = pickle.load(f)
. M) Q; w2 B+ `" d" U- L" g load_save = Load_Save_Data()
+ x8 G' _7 A, {5 C: g kind_data = ["刺网","围网","拖网"]
3 \2 [0 z' C' Y6 ^3 ^( \; v file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"] 6 z, u% R& N- w- V v' M3 {$ J& ~
for i,datax in enumerate(kind_data): . h e- ^2 C S/ S, D7 W
data_type = [data for data in total_data if data["type"].unique()[0] == datax]
]8 }- z3 R$ e+ ~1 K load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i]) - o5 a) g( M3 ~3 X5 `
get_diff_data()
; J8 {7 W$ [) b/ y4 R) v9 e( q #对轨迹进行异常点剔除,对nan值进行线性插值 # s& h l8 ?5 s! W' y+ r
ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
) H/ @2 r8 ~/ i; L4 \ DF_NEW=[]
8 {/ |$ d6 I5 T$ W1 M+ H# d Anomaly_count=[]
: D1 E1 y6 v% g: ` for ID in tqdm(ID_list):
: M; Y) J3 N! `& z: `7 [+ G df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) $ K2 D: W* a* S* ?
df_new,count=assign_traj_anomaly_points_nan(df_id)
8 E8 p( M( b/ ~8 [ u$ y$ H) R5 D df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) J, u2 k1 W$ A# R& N4 K/ v. i2 b
df_new = df_new.fillna(method="bfill")
7 x/ O7 |/ [$ j% F+ m! M6 F( } df_new = df_new.fillna(method="ffill")
# {( ^# @ e M% g. t$ W; ^ df_new["speed"] = df_new["speed"].clip(0, 23)
' j W1 E2 H1 f! s3 B% K+ e Anomaly_count.append(count)#统计每个id异常点的数量有多少
1 R+ l. U, W0 X2 U8 O. @ a) l DF_NEW.append(df_new)
. K5 ^9 ?% ^& l2 e # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列 6 G. |$ Y) J9 r/ r
def visualize_three_traj_speed_direction(): * T# Y1 n0 u( t* w. J3 E
fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15)) % h$ V# x# E1 E
plt.subplots_adjust(wspace=0.3,hspace=0.3) 5 a5 e* w/ B" f% F" q
# 随机选出刺网的三条轨迹进行可视化 ( i2 g# L2 F- K( O& R! _
file_types = ["ciwang_data","weiwang_data","tuowang_data"] + p" I6 N5 ?2 A$ Q
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] , A( X* Q1 J* K8 Q0 P
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"] ) Y! o2 s) I: M# } G! X
colors = [pink, lightblue, lightgreen] # T9 C5 D2 q* A Q9 D5 r
for i,file_name in tqdm(enumerate(file_types)):
' A! s* A) K8 ^/ S6 K9 s. k datax = get_random_one_traj(type=file_name) p7 U* y; t- _6 B( y
x_data = datax["速度"].loc[-1:].values
. z9 @" L( o0 F3 W+ s" J y_data = datax["方向"].loc[-1:].values
0 v3 f1 W0 m3 ]3 V P. r axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) 3 N3 a, D5 c2 |$ T0 A! @& O
axes[i][0].grid(alpha=2)
; o$ _6 x# C+ p* I: G. w i" ^ axes[i][0].legend(loc="best")
7 t/ w$ ?! F# i6 T0 Y9 N$ r axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) % u! ^% @6 _+ ?
axes[i][1].grid(alpha=2) ( `8 B8 X8 x- J6 E8 n5 Y" o" A" D
axes[i][1].legend(loc="best") ! J8 e' X; p% j# q# [2 H1 `
plt.show() 3 M) K: u/ T; f$ X
visualize_three_traj_speed_direction() % l2 d( L3 o9 r* e. I$ b5 ?
2 K0 }5 s: s) I# f: j! C0 p8 @ 作业二:相关性分析。
# w+ f) F$ ~6 N) n# |- c' h data_train.loc[data_train[type]==刺网,type_id]=1
4 n$ f& f/ W0 ?, o7 t data_train.loc[data_train[type]==围网,type_id]=2 - `: e& a, p$ T+ i3 U2 S
data_train.loc[data_train[type]==拖网,type_id]=3 . e) z- w1 I% h1 ~1 Q( [% {3 R
f, ax = plt.subplots(figsize=(9, 6)) ' o: y4 G# j% J% i! T( y
ax = sns.heatmap(np.abs(df.corr()),annot=True)
/ {. j @7 ]7 z7 Q/ O8 i$ H plt.show()
; K$ D& l, ^- Z* E% m" f/ j c + k( A/ M0 g, _& R% Y' Q. j
从图中可以清楚看到,经纬度和速度跟类型相关性比较大。 ; Y! ]2 u0 T7 S, K. i& K
0 y0 E' y* c& l2 ?$ C5 q
+ b- M9 z4 L2 v4 }9 a7 F' S& U i: L3 m8 h0 F, ?
) V0 P8 H$ \: E |