|
, W& A: a) y. X3 s* r9 J
此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设9 W! ]" u% t* ?& C w- X
数据分析的目的:
# c& | ~* m) u) A+ e+ I5 i 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
/ P. p; V0 o# O 2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布 4 g+ A2 b( d4 t/ n
三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd ! q/ D, P* Q5 E
import geopandas as gpd
% @: x1 f( t) { from pyproj import Proj 9 j1 V1 j, q# a0 p8 z
from keplergl import KeplerGl
9 Q- U$ ?. {, |5 c, W+ v from tqdm import tqdm
: c# ]1 |( S5 H/ T0 i8 r2 l import os
5 N4 {/ v& j: ]* y1 ? import matplotlib.pyplot as plt 5 I8 c* N* d# w$ x, I
import shapely
1 P7 C- r5 Q) B) N import numpy as np " [1 x1 {9 b6 y5 l4 y: v
from datetime import datetime N# G! j) A% Z% B8 y2 F0 L
import warnings # B$ x4 T# x4 j$ `8 W! j; o
warnings.filterwarnings(ignore)
: |# y5 e2 D' O plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。
7 y2 z6 z( o& K% f6 ] plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。
" }! A! D( k, P3 g! p3 B #获取文件夹中的数据
* Z0 J, R3 i$ o$ c' { def get_data(file_path,model):
" E( d% B+ u' G) _ assert model in [train, test], {} Not Support this type of file.format(model)
( j8 d; J5 l0 O% b paths = os.listdir(file_path) ) G! v* G/ t! ^4 L/ {' D
# print(len(paths))
: i& K# X6 L( x1 F tmp = []
+ Y: q- k- _( a) L g2 l/ i for t in tqdm(range(len(paths))):
6 Q6 G: D4 G: e+ K) W ] p = paths[t] 4 M% M z/ G; B, U+ i
with open({}/{}.format(file_path, p), encoding=utf-8) as f: C- m7 O) [6 H& C9 @+ V6 [) g
next(f)
6 ?% D$ R, q0 D! E1 z* p( m9 ~0 c6 q for line in f.readlines():
7 s5 H' `; @! b* q# h: J) J. D q tmp.append(line.strip().split(,)) 5 ]* T8 e6 \0 f- p: D# b! Z
tmp_df = pd.DataFrame(tmp)
- N: ~$ G# N! L7 N$ S if model == train:
9 m3 r( f/ M5 S4 h! w tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
# q ?2 w- w6 h2 b3 r else:
, a3 I% w) a+ K9 `* o% d9 y4 C tmp_df[type] = unknown
4 r" G5 J3 V# m( I1 o' m tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
2 k, [ R. I" Y3 p' D tmp_df[lat] = tmp_df[lat].astype(float)
/ ^' R& b% p+ C' Q& r/ k* [ tmp_df[lon] = tmp_df[lon].astype(float) 3 U' }# B2 y$ D
tmp_df[speed] = tmp_df[speed].astype(float)
% w \' b% l5 z( c y9 \ tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本 ) X& A' I3 N/ ?% [/ S
return tmp_df
3 B% T# X4 c- X! q% |3 p" c O # 平面坐标转经纬度,供初赛数据使用
' v1 Q; z* c5 J) A # 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud
; U; y% k$ h, C( k3 u# T# T8 ` def transform_xy2lonlat(df):
: \0 i$ A( b3 I x = df[lat].values + z) y& `8 j6 e2 o0 s! B5 t
y = df[lon].values
! U: m6 C3 v) V" d5 i* E# ^" b8 i 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 )
# l+ X. B# k6 D) W df[lon], df[lat] = p(y, x, inverse=True) 7 I6 k+ _& E {) k$ ?& j: }' u
return df 8 U; Q4 ^% D( u) P# _3 Y
#修改数据的时间格式
" `( x0 O% W' n* I3 \ t def reformat_strtime(time_str=None, START_YEAR="2019"): }+ m" X R. G- c
"""Reformat the strtime with the form 08 14 to START_YEAR-08-14 """ : N3 L8 ]1 a, F* ~+ d; b$ \- a1 X& n
time_str_split = time_str.split(" ")
% g5 W8 a; \) R6 m time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4]
# J( p, F [+ {# I _7 D/ d time_str_reformat = time_str_reformat + " " + time_str_split[1] ) o" {# V$ Y* v. K' J, N! i
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S)
6 J% o4 n$ f) ~* B9 K0 u8 N return time_str_reformat
3 ^# ?6 p; d: |; U7 b #计算两个点的距离
9 e& q8 K, Y; I; [3 k9 g3 w# s def haversine_np(lon1, lat1, lon2, lat2): 3 s! g: g+ i! f3 W0 |1 M' b9 [
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
4 v ?8 L- p& g+ S/ A dlon = lon2 - lon1
& @- F* y8 A. [3 i2 P) o dlat = lat2 - lat1
; E2 w& b$ t1 l, s+ }+ H' M8 N a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 7 T4 N3 F, C+ f/ m
c = 2 * np.arcsin(np.sqrt(a))
N6 b( S: U: l5 f km = 6367 * c
) n0 f& u* g& w4 X3 {9 J return km * 1000 ( P/ P6 ]3 S2 o4 \
def compute_traj_diff_time_distance(traj=None):
. I- r8 K7 ~: b4 v8 O """Compute the sampling time and the coordinate distance.""" 9 M E3 R! a4 ]6 x1 Q& F8 S
# 计算时间的差值
! k3 j/ w @7 p* A; ?2 }! n time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[
, S. `# X2 R1 R4 W m, Z "time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60
3 C5 e* u1 P b* E# \ # 计算坐标之间的距离 / g- S! J- k) h4 ?' _5 R
dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0
: O; b2 e2 @' A traj["lat"].values[1:], # lat_0
. u2 j7 @1 Y3 P6 m3 n1 F% O% R7 e* _ traj["lon"].values[:-1], # lon_1
( r b6 m5 R6 v8 z7 b4 | traj["lat"].values[:-1] # lat_1
/ e$ Q; v: U& A) h) r )
. _0 m3 u _0 X2 K/ m# z # 填充第一个值
g$ j) G9 d- t time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist() & {/ \+ W1 [( d6 m/ U
dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist() 1 a. |4 |: I8 K1 y7 a* {) g5 [
traj.loc[list(traj.index),time_array] = time_diff_array
# a9 b M) D2 A9 [ traj.loc[list(traj.index),dist_array] = dist_diff_array 9 |) ^7 A4 A+ B! `# |6 {4 M I0 l* `' I
return traj
) |6 A; m$ k8 ? #对轨迹进行异常点的剔除 * t# @3 x @5 Q' K
def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,
e1 X7 c7 V* D4 \% n2 u time_interval_maximum=200,
; n# F0 i4 E7 y coord_speed_maximum=700): 2 S* }! U/ }" m: ~% @4 c) V
"""Assign the anomaly points in traj to np.nan."""
/ F* O% X3 N& F+ d6 I$ E def thigma_data(data_y,n): ! |8 I Z% c( c
data_x =[i for i in range(len(data_y))] 0 c/ W. I- Q; j$ H2 x" Q' w
ymean = np.mean(data_y)
: C7 \1 [! L% U0 T+ _6 [ ystd = np.std(data_y) ; U9 l! r9 I1 w l3 o @
threshold1 = ymean - n * ystd 2 k$ X& Y. Z$ [3 D% `
threshold2 = ymean + n * ystd
; H8 J$ d6 A6 \+ N ?4 s; Z1 n judge=[] 1 s8 s1 d* ?* x# n
for data in data_y: ) ?! l) C* m5 g' i8 r7 P2 A
if (data < threshold1)|(data> threshold2): $ S* A2 _- C: f) f: \# V
judge.append(True) , a! U6 x( ^( U9 J4 w+ o& o
else: ) J) Q! ~5 a( {, d* P8 S
judge.append(False) 7 K* q' b: y+ {( u
return judge , P. ]3 ^% @1 b4 i3 u+ u. b6 B% a3 F/ q
# Step 1: The speed anomaly repairing 2 N0 Z! N" w6 q! H" [
is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) + c8 Q) ]3 T- O" K& @3 U, H
traj["speed"][is_speed_anomaly] = np.nan
8 i- R0 E9 `3 M; R; [6 M" w # Step 2: 根据距离和时间计算速度 $ F1 L' L' I- G1 `2 }, I# e
is_anomaly = np.array([False] * len(traj)) # U0 R. K' x8 F2 B1 U
traj["coord_speed"] = traj["dist_array"] / traj["time_array"]
$ Y2 _, I& g3 M& Q3 j8 m # Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点 ' r2 x3 @5 b0 c& M( Q$ Y' h
is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3))
- O" g+ H+ h" h+ s5 M8 D2 y* k1 M is_anomaly = is_anomaly | is_anomaly_tmp
6 i: |( K W3 I! I is_anomaly.index=traj.index 0 m* j* F6 o& J( K9 ~/ a
# Condition 2: 轨迹点的3-sigma异常处理 1 X! k1 C1 z6 T3 z- M$ j
traj = traj[~is_anomaly].reset_index(drop=True)
8 Q. z% x$ ]( S& n. Y is_anomaly = np.array([False] * len(traj))
8 \- ]4 V2 l& C% I9 q2 d if len(traj) != 0: 6 g. ]( p, |" P' e, ]
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
- V4 v, C: O) l% e) f0 F6 {4 Q lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean()
+ J' h; ^/ L. J; }' A8 Q lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std 0 e$ U. y! n3 O/ X
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std
: [ K8 i; i* G4 _0 l is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) $ Y3 @. R4 F# f1 r' E
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
5 p, B* d* M4 |, X traj = traj[~is_anomaly].reset_index(drop=True) " G* `- N& j4 g: l5 N
return traj, [len(is_speed_anomaly) - len(traj)] " y! A8 E0 t) \, H s7 v6 U
df=get_data(rC:\Users\admin\hy_round1_train_20200102,train) # d: m1 x% w# i0 l
#对轨迹进行异常点剔除,对nan值进行线性插值
; J0 q$ W7 {3 [- X7 W0 V; } ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
3 f2 ^9 ?" g- p2 S% x$ M, T DF_NEW=[]
$ U, v: z" X' C( m% O9 J; k Anomaly_count=[]
5 j" `1 t3 V! Z2 w% V9 ^" K for ID in tqdm(ID_list):
8 O- z2 z: b5 I+ ` df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) ' z) K8 h2 j; @0 u* ?
df_new,count=assign_traj_anomaly_points_nan(df_id)
; s# }: G3 O) k% L1 ?" y- A# ^. e df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) / m1 A- c4 Z' B3 v- u- g0 N
df_new = df_new.fillna(method="bfill") / Y) M. q8 W" i1 ]3 M) S. F3 b
df_new = df_new.fillna(method="ffill") * \4 Y- M9 E+ R% r- F- ?0 M( h
df_new["speed"] = df_new["speed"].clip(0, 23)
' Q' _$ N$ _" G' a Anomaly_count.append(count)#统计每个id异常点的数量有多少
& O6 @& Q0 {% F; d DF_NEW.append(df_new) # }. R$ z7 b$ y7 f, V" b
#将数据写入到pkl格式
/ |" p" F. a* L load_save = Load_Save_Data() 0 F3 h' }& ]" a) J( T' r4 ?: C
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")
/ o/ ^" a+ A1 i; k4 W #### 三类渔船速度和方向可视化 % ^0 M! Y, {/ ]8 p* b# [8 M/ S
# 把训练集的所有数据,根据类别存放到不同的数据文件中
+ e' ?) a" U9 i% Y* p# i" h def get_diff_data(): ! G% ?3 }! r3 p0 R4 \
Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
7 u) T3 D! ~* W: y5 {) K& { with open(Path,"rb") as f:
+ t, e) V( w" k1 a( }2 F total_data = pickle.load(f) & R6 V7 ?% O k" J& B
load_save = Load_Save_Data()
2 _9 q; {3 R3 L# k5 r* K& U kind_data = ["刺网","围网","拖网"]
3 s1 L8 ^( V3 J( x& n3 u file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"] ' b0 T' Q# ^! B9 r$ y1 a. d
for i,datax in enumerate(kind_data): 3 V7 k8 B' R( p" n; R( Y
data_type = [data for data in total_data if data["type"].unique()[0] == datax] 9 p6 E) I$ O; I9 f* B
load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
4 m4 E& c0 R% g l* h get_diff_data() & T9 N9 `' c8 u" \- ?/ g
#对轨迹进行异常点剔除,对nan值进行线性插值
' [5 q3 H. L, _1 C2 L" V% K0 W5 u8 R ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
' d4 y) z# y; Q2 `1 Z DF_NEW=[]
/ w8 I \) g o2 p3 b Anomaly_count=[] " l- B4 O& [4 B4 ~% i
for ID in tqdm(ID_list):
: M8 }6 G5 J: h7 S1 g9 A df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) 0 \1 T; n1 S4 m) a' T
df_new,count=assign_traj_anomaly_points_nan(df_id) 0 w* }* J6 m. Z5 {6 E5 ^
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) / L4 }6 u, D+ W# V- r" l) o- ?: ^
df_new = df_new.fillna(method="bfill")
# @/ h/ x1 l# J# ~1 } df_new = df_new.fillna(method="ffill") 2 K- Z& r) o, i6 C( r: x& o
df_new["speed"] = df_new["speed"].clip(0, 23) 5 z: F$ b! t3 T$ Q$ W$ A7 g
Anomaly_count.append(count)#统计每个id异常点的数量有多少
( Y# d* m; g% y$ {! d8 |, Z/ F) u DF_NEW.append(df_new)
! f; p# U1 l+ o4 L- d! ^ # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列 # B- A8 s0 O$ `, v
def visualize_three_traj_speed_direction(): - G; \7 l2 \; y' w) w8 Q! y
fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15))
8 u" C; z! n. @) c. d, W plt.subplots_adjust(wspace=0.3,hspace=0.3) : M o4 J i* G5 b! r
# 随机选出刺网的三条轨迹进行可视化
$ `- F6 [* Y" K, X4 w file_types = ["ciwang_data","weiwang_data","tuowang_data"] " I' g! N8 U; [2 e
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] % m3 K" z4 O( ?; y
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"]
% w H: r q% w: X# u: f1 L colors = [pink, lightblue, lightgreen] 7 J0 C9 r' y# O, t" K
for i,file_name in tqdm(enumerate(file_types)): 2 y9 L: L6 s. A! f& _. d. I2 p
datax = get_random_one_traj(type=file_name)
- V/ j9 A" v0 i+ R x_data = datax["速度"].loc[-1:].values + F6 U; Q8 x, Z1 } C
y_data = datax["方向"].loc[-1:].values . v `6 [1 j t- }' C
axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i])
) p E* F& S& q) l8 `& G axes[i][0].grid(alpha=2) # L Q% `9 Y0 h! n6 V) [ p
axes[i][0].legend(loc="best") \% b% e$ g; z1 v, V
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) . A# N. B* M$ N$ Z6 w& _
axes[i][1].grid(alpha=2) * Y$ p! C1 P# J8 G
axes[i][1].legend(loc="best") ) x \' ]8 M2 Y, I \" a' _
plt.show()
2 L2 G7 e* n8 G* H$ j% j visualize_three_traj_speed_direction() ) e% U% g( Q# l6 M5 z
0 U' K) h! H# b2 z8 |% ?; J5 e
作业二:相关性分析。
1 j9 Y* e/ d* O u) j data_train.loc[data_train[type]==刺网,type_id]=1
" v% f# l( h# U* E data_train.loc[data_train[type]==围网,type_id]=2 ! c7 q0 P# t s' Z
data_train.loc[data_train[type]==拖网,type_id]=3 / f' u. b& K: @( D3 R
f, ax = plt.subplots(figsize=(9, 6)) 8 D+ c7 F, w% B- b/ \
ax = sns.heatmap(np.abs(df.corr()),annot=True)
( A6 E7 A& H- q( v/ T plt.show()
# G' B* L8 |$ b: t% b- w- f4 E % I* ^/ b \8 G' f
从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
: z- J( {$ a, ~6 ? o$ U9 ^; J/ q2 B2 ^, t" u/ C: v7 ]+ \
3 q7 r4 ~9 z7 I* I) `) v9 @' C
' [1 I( _8 u0 k- ~& u, v
3 G Q: c2 B0 x! u! G. c3 N- k4 j
|