|
) X% A. b5 y- ]0 N 此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设
1 z% s7 [& C7 |6 o- A# l 数据分析的目的: , i" d6 o# T, a+ O0 J' J6 b, 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
9 u0 F( D- }: ~, D 2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布 : ?% y+ n) d3 n4 l+ q7 s
三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd & | r; {" V2 A9 P7 o
import geopandas as gpd
1 {. I) P+ t9 j" l( ~' y8 h from pyproj import Proj
. h5 } d* l, V/ J4 j& X: s4 U! S% K: Q from keplergl import KeplerGl 7 P. E) ^' N- e
from tqdm import tqdm
' a+ S. O1 e& |+ Y8 S* l import os
9 P! m. w; [( x, W0 x! M' e4 h' Z7 ` import matplotlib.pyplot as plt 4 U# x7 w$ e) G1 `
import shapely
Z2 z M0 d8 X1 k import numpy as np 2 H' B7 B2 p- s. M) n7 Z4 X
from datetime import datetime 1 g& D) N/ {8 ?1 G4 I% D
import warnings / y* l: h/ A$ }
warnings.filterwarnings(ignore) 7 C: f; F: g+ ^4 | q% l
plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。
( w! ~& V0 {. `2 o- s plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。
$ J/ x7 t }4 R" @* z #获取文件夹中的数据 ! K$ X# X- w. X% F. H
def get_data(file_path,model):
( G) O, N Y1 E* ~5 P assert model in [train, test], {} Not Support this type of file.format(model) & q/ E1 F. U/ o2 N0 ?7 S9 S
paths = os.listdir(file_path)
6 y. _0 Y& E. |& l0 b) d) l2 s/ R # print(len(paths)) " s+ u6 N8 H" ]$ p' V* b0 L& l
tmp = [] ! {! Z: |, s. A( C. v
for t in tqdm(range(len(paths))): 5 ^0 N/ s# T1 g9 Z
p = paths[t] 2 x3 R! R, g( z& k D
with open({}/{}.format(file_path, p), encoding=utf-8) as f:
# E; e9 g+ D! F, o6 |' G( u next(f)
9 o0 h H3 r1 D. p4 t9 G6 F for line in f.readlines(): 0 Z+ Y" B* N. c9 p5 |
tmp.append(line.strip().split(,)) 4 L7 N3 \- M; x
tmp_df = pd.DataFrame(tmp) 6 `1 q" W1 J1 }. Z
if model == train: ' v* i6 e# w+ \' ]9 }! S6 ]
tmp_df.columns = [ID, lat, lon, speed, direction, time, type] 4 t* V* C9 Y9 V/ F
else:
8 g' z) |# G$ X o- S: Z tmp_df[type] = unknown : C- f" U) ~- e
tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
' y/ y. m) m3 g9 f tmp_df[lat] = tmp_df[lat].astype(float)
# q* k! z4 |7 n2 A tmp_df[lon] = tmp_df[lon].astype(float)
: }8 n" m2 ^* V tmp_df[speed] = tmp_df[speed].astype(float)
7 ]( V$ n" g" }: C" B% Z6 H7 h1 S+ F2 I% I tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本
$ ?9 @' R9 r: m1 V return tmp_df
3 x9 ~ t: X6 I) B2 w x n5 S. _ # 平面坐标转经纬度,供初赛数据使用 $ F) H" k# ^& s0 k. h$ E5 ]
# 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud
7 ^& I8 @ [1 [( B2 d def transform_xy2lonlat(df):
. [8 |" L0 E6 l. K x = df[lat].values 5 U* ^0 P3 e; H6 Z- l% l/ E) o
y = df[lon].values
( v) |/ O: T0 P% h/ c) e 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 ) # w& L; i9 n- H7 M5 C4 Q) u, W
df[lon], df[lat] = p(y, x, inverse=True)
7 [9 C5 y/ r5 B7 I% R return df " c# W8 R: ~9 _. G- J' d6 ?
#修改数据的时间格式 ) W3 ^9 V& y( h/ D ]9 k/ U
def reformat_strtime(time_str=None, START_YEAR="2019"):
C4 }# `4 {' J0 v, ] """Reformat the strtime with the form 08 14 to START_YEAR-08-14 """ % B2 R. M7 n9 p9 c' F8 @
time_str_split = time_str.split(" ") ) Y* L) t9 N2 s" T1 d
time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] r$ S" c$ W; Q+ e# F
time_str_reformat = time_str_reformat + " " + time_str_split[1] 6 L& v; ?; T( T5 t" X7 w
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S) Q" U! J+ t( b5 v! a
return time_str_reformat
@$ m8 `% [7 Z' Q# P p #计算两个点的距离 - V1 C: Q1 K# }
def haversine_np(lon1, lat1, lon2, lat2): 8 G+ s$ l% l. F7 _3 d7 m
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
6 [7 n* I2 h( B P5 Y9 Q& x2 ] dlon = lon2 - lon1
/ ?! L1 c8 w1 y# N0 [0 J dlat = lat2 - lat1
' M- m2 C3 i" P5 M" Y3 s* M a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
. C8 k+ D3 \/ ~" k& j" t2 e$ K$ Z c = 2 * np.arcsin(np.sqrt(a)) % n& U& z$ j" V% u; [1 \
km = 6367 * c
. k/ Q$ A G3 s0 {& i/ D! _/ d return km * 1000 * d$ ~! B& i9 l8 M2 Z/ q. l
def compute_traj_diff_time_distance(traj=None): 1 U$ M3 g) Z; [$ G4 v
"""Compute the sampling time and the coordinate distance."""
$ m7 R$ _1 ?- J# S6 A # 计算时间的差值 3 f& \9 l- S+ p
time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[
) I" N9 {% M* A$ z/ H "time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60 0 ?4 X+ i. x$ G
# 计算坐标之间的距离 # F# P( t7 t; I3 L# }' l2 H2 L& a
dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0 # `+ v* m" w N2 n2 n
traj["lat"].values[1:], # lat_0
; t& d1 D7 L0 k4 D: @6 b1 {) p traj["lon"].values[:-1], # lon_1 # Q, R) J, c( ^& A" S
traj["lat"].values[:-1] # lat_1 7 ]4 m# g9 M7 J: Y; R! C* A
)
$ @# K/ X/ U! j8 k# n6 Y # 填充第一个值 5 l0 |; u2 l Q, {# p, Z% h
time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()
( A/ ]- H9 N& `1 V- r2 |5 }' G# L dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
5 u8 U# R. h8 {; N: j" o+ R+ u* U traj.loc[list(traj.index),time_array] = time_diff_array
1 w# [: p# D/ H: n! a% T traj.loc[list(traj.index),dist_array] = dist_diff_array
/ \: o% C2 o4 y6 m! R+ t return traj + N# a" y* |& [0 V8 P" b: o! W
#对轨迹进行异常点的剔除
3 d4 w* _$ l# b3 i1 L( _ | def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23, / G: _( C5 y% c; t4 \8 |
time_interval_maximum=200, ( N ?& @( [+ y7 H% n+ @3 l
coord_speed_maximum=700): 6 D* ~6 J& F, g8 N0 C/ k1 K
"""Assign the anomaly points in traj to np.nan.""" : h5 ` `& Z6 d
def thigma_data(data_y,n): " I- s) {' m. w
data_x =[i for i in range(len(data_y))] 1 p$ K/ g# p3 f7 l# `
ymean = np.mean(data_y)
0 R/ o9 O$ ^% q1 V& @) q9 h ystd = np.std(data_y) Q u' m$ {4 p( z, v
threshold1 = ymean - n * ystd
, S: Y' [' Y6 v9 c* q- z3 X threshold2 = ymean + n * ystd
, k) H6 R4 t% l judge=[] ! B& _2 d& U1 ?& t
for data in data_y: 4 Y- u% i% D( d5 v: o; q
if (data < threshold1)|(data> threshold2):
1 o. s4 V: J! D2 _- o judge.append(True)
' U2 Q j2 l; z3 ~7 c/ o else:
7 R2 J/ Y7 \. D3 ?) ^4 ]. ^ judge.append(False)
) z" t% r6 E1 x5 Y$ t return judge
- y( ?7 S$ g- ]: b J2 T/ E # Step 1: The speed anomaly repairing
; P% i7 u1 a" a2 }: y8 J$ u$ ~! c" i is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) - e: d( T% Q4 d. I8 u6 f9 M$ a+ f% A
traj["speed"][is_speed_anomaly] = np.nan ) T1 {' b/ I( @7 X3 r& ]" J
# Step 2: 根据距离和时间计算速度
7 {# @4 ~ M# M. J( ~ P. ~: p is_anomaly = np.array([False] * len(traj)) 4 z" p& a/ o0 B( H
traj["coord_speed"] = traj["dist_array"] / traj["time_array"]
0 Y7 f! V' d) I9 M: e # Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点
9 U0 O$ M U% r, w: O; H is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) % j4 e5 P/ l" A# [# w* T6 i
is_anomaly = is_anomaly | is_anomaly_tmp
# H3 X0 k0 ^. v5 f9 d8 K" z/ p is_anomaly.index=traj.index
& b1 K% |" z# k' _- r1 n% q # Condition 2: 轨迹点的3-sigma异常处理
" z2 G2 ?) q$ o$ w0 Z$ r traj = traj[~is_anomaly].reset_index(drop=True) 2 a8 `" W8 G$ l# j6 b: ?
is_anomaly = np.array([False] * len(traj))
) L) o" H( V0 j. o9 \) h if len(traj) != 0: 1 w/ @2 m$ R1 A' X; w/ {
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean() ! v: F- u N U: K+ }+ ~% p! @
lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean()
" u, t$ S* H- x! Z7 Y% n lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std
, u- j `# Y/ q* |: b/ h& ~! { lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std # P6 W$ P6 c# F& P8 M& f
is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) 9 R# s" H* X: F# Z* j0 q- m9 O% H
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
6 @4 u( M2 G% C; z0 D traj = traj[~is_anomaly].reset_index(drop=True) % m' | s4 j1 e) ^
return traj, [len(is_speed_anomaly) - len(traj)]
1 |6 G: ~1 P/ o5 a+ v1 f2 T# r" k3 ] df=get_data(rC:\Users\admin\hy_round1_train_20200102,train) - A8 ?# G: b, u6 q6 A( l
#对轨迹进行异常点剔除,对nan值进行线性插值 0 Z! v8 r, j0 ^& H! e' c: c1 W
ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
! h- ]$ {: z' {6 X+ p% W& ] DF_NEW=[] 2 W, h. [, a$ X' J
Anomaly_count=[] / s8 o% t$ k0 A+ k/ q
for ID in tqdm(ID_list):
9 N* d5 S/ y3 t& G+ e df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
, M% b8 j; Y+ P+ t# {1 V( n df_new,count=assign_traj_anomaly_points_nan(df_id) 7 A2 D) C& ]% e2 t6 T: s
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) 7 ~3 w" j8 J( E5 o4 ]1 S Y/ z
df_new = df_new.fillna(method="bfill")
% Z- V9 ]( ]: i, F7 Y4 a df_new = df_new.fillna(method="ffill")
/ k6 S( [/ K a df_new["speed"] = df_new["speed"].clip(0, 23) : D+ \; Q* k/ i. K. K( p0 ~
Anomaly_count.append(count)#统计每个id异常点的数量有多少
. |: ?5 F* B/ R w O) W& n9 F DF_NEW.append(df_new)
4 W) j5 U; A. d6 W6 e #将数据写入到pkl格式 1 g! [! C9 Y/ w8 y; i" Q
load_save = Load_Save_Data()
% g# s# ^' Z7 e% j; D _) M3 U load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")
3 N7 U& Y& }' D3 ? V+ O #### 三类渔船速度和方向可视化
( N) V: c* D: r$ W; b: r r # 把训练集的所有数据,根据类别存放到不同的数据文件中
" ]" N! \2 l0 k$ o' A def get_diff_data(): ' d" t( q* c- H) _
Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl" & h2 G* e# X0 N- i. P m! N7 ^& b. r
with open(Path,"rb") as f:
* ^8 h8 X0 S: D9 Q; c- e total_data = pickle.load(f) / W7 w3 F' r7 j& c' z* J
load_save = Load_Save_Data()
! P w* x6 S, U+ U; t" @+ v kind_data = ["刺网","围网","拖网"] 4 k: Y( k: D3 G' p9 w
file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"] , {- [! B1 Q7 `: X6 J) n
for i,datax in enumerate(kind_data): * U; t# J. k, t. X1 l& k
data_type = [data for data in total_data if data["type"].unique()[0] == datax]
/ e2 w' E5 @* c load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
, Y& k2 a* g0 ]" M' N get_diff_data()
2 Z3 I! F% U/ q9 I5 z' b/ j4 [ #对轨迹进行异常点剔除,对nan值进行线性插值
4 N9 T2 z9 W0 p Z; ^5 J- D) S6 {- s7 | ID_list=list(pd.DataFrame(df[ID].value_counts()).index) 4 S5 I0 i; |7 h; [- H
DF_NEW=[]
0 ~+ u$ _; Q- x& X1 p6 S Anomaly_count=[] 1 P# [" ^* u* q( F) |/ [' _6 y
for ID in tqdm(ID_list):
3 [) d3 x7 Q8 D) y! u. q) y df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
! k9 J# v* x4 _! x* \. e% C df_new,count=assign_traj_anomaly_points_nan(df_id) / R \; `. v0 N9 h
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) e/ W) _2 g7 G+ O
df_new = df_new.fillna(method="bfill") Z$ d/ m- b( {- R
df_new = df_new.fillna(method="ffill") 5 K6 x8 x& I3 ?- ?9 E7 I v8 w+ H
df_new["speed"] = df_new["speed"].clip(0, 23) 9 N* X4 \) T( D* [
Anomaly_count.append(count)#统计每个id异常点的数量有多少 9 {( I, l9 Y+ b1 M$ P- K' F
DF_NEW.append(df_new)
: g; r2 u, h! W9 E # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列 / y1 _2 a5 Q9 x- K
def visualize_three_traj_speed_direction():
8 D5 u$ k7 U f9 f5 H# h* y fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15)) ) U3 K5 u4 l0 h; W6 ]/ u. N
plt.subplots_adjust(wspace=0.3,hspace=0.3) ) @$ I- l6 C& w6 W
# 随机选出刺网的三条轨迹进行可视化 + N$ w: Q7 L5 Q% G# i S i; Y
file_types = ["ciwang_data","weiwang_data","tuowang_data"] * p: A' g( V8 R* ?$ r
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] 4 S% o: j& G! L; E
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"] 7 d9 s& ]' g0 P' R; x1 g
colors = [pink, lightblue, lightgreen]
6 k+ v1 o* T0 M2 d! g for i,file_name in tqdm(enumerate(file_types)):
+ R, B$ m( G$ m% I2 t datax = get_random_one_traj(type=file_name)
$ a6 w, S" c. o- \ x_data = datax["速度"].loc[-1:].values * O' B) h% G. B6 h7 C6 k0 {
y_data = datax["方向"].loc[-1:].values
- t$ ?, U* h- i4 P0 S axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) 4 n: X. o9 V4 X. r3 I
axes[i][0].grid(alpha=2)
/ o7 x5 W% j+ W5 P- n axes[i][0].legend(loc="best") ) V% d) Q( o. X. }
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) # I# E5 f3 h! {$ Q
axes[i][1].grid(alpha=2) 6 i4 a1 z- g# e+ ?4 z W& I+ n
axes[i][1].legend(loc="best")
! Z5 o- L! K H plt.show()
0 U% ?& K3 ~4 q5 F visualize_three_traj_speed_direction() 0 f& A; I& K M7 }# \
6 q, F( j1 g! y* X3 l
作业二:相关性分析。 * E. T- E" E, N# k* I! E
data_train.loc[data_train[type]==刺网,type_id]=1 ; G2 O+ s# h9 M" g. [
data_train.loc[data_train[type]==围网,type_id]=2 2 A5 ]+ }" v& m
data_train.loc[data_train[type]==拖网,type_id]=3 n `( t! D( D
f, ax = plt.subplots(figsize=(9, 6))
2 W; Y* x0 Q' M ` ax = sns.heatmap(np.abs(df.corr()),annot=True) 9 T) p/ h% B5 \
plt.show()
+ c/ |* o$ W+ K5 |
" T4 t' ^9 n7 V" G E5 d 从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
: N; o6 b" T% M' H
) w' v/ ?7 K1 m# l6 T# ^/ E1 q! q8 W' t
0 Z* o( I# U4 X+ _5 h: F$ O" }3 C$ O$ d
|