|
% }5 v4 b- V( }1 z4 p; l 此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设0 Y3 a; e ~( R& z1 Y# p
数据分析的目的: 0 O- @% b7 p" l" B7 U8 @/ ~
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 3 |, P4 X p) n, Z. S' I
2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布
e% P! Y+ U f( a 三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd 1 r: }* |, ^1 D9 ]/ b/ N9 P) F2 r
import geopandas as gpd
$ o9 f6 j! s9 x7 |1 L- {: s from pyproj import Proj 6 j# \% L) u2 R; F3 h8 L+ F
from keplergl import KeplerGl F7 |6 x! w3 A/ {! C
from tqdm import tqdm - z& D2 {3 X3 i" R$ X) e
import os
, Q% \( D# y8 z, f. Y8 E$ H- f import matplotlib.pyplot as plt
2 F# w6 p( H* a5 ?& I- ~' ` import shapely & q, G! d1 \5 l3 p& k2 [! }% N
import numpy as np
" g& V0 |& b: K+ m! ~+ T8 ^ from datetime import datetime 4 W2 `6 v+ X$ `- I! ]% S/ \/ q( @
import warnings 5 z: c. g* k7 J4 L. o
warnings.filterwarnings(ignore)
: r) ^* V5 ]& | plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。
; i: K9 ]7 ]& E7 n J plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。
/ Q+ m- X+ }2 W" }- z1 e #获取文件夹中的数据
7 }7 O( P+ e' d3 [7 [ u def get_data(file_path,model): 3 D* y& H3 u }6 i6 o
assert model in [train, test], {} Not Support this type of file.format(model) . z+ D8 g4 W. A+ d- d2 t' U
paths = os.listdir(file_path) 4 @! s& P6 o2 X" ?
# print(len(paths))
& N2 J; v8 w) }! I: z tmp = [] 0 a4 `4 ]7 o* M( e3 @
for t in tqdm(range(len(paths))):
) z; k' g8 N, _2 A ]7 {: G) \ p = paths[t]
, L) g- B0 A$ w% k: C `3 H with open({}/{}.format(file_path, p), encoding=utf-8) as f:
2 t- E1 p) |% ] next(f)
+ Z2 r9 M3 K2 S6 s% G; Q3 Y5 S' { for line in f.readlines(): ' g. ~( s3 Z' p/ t- A/ ^4 j
tmp.append(line.strip().split(,))
2 H" B. j7 R& C0 N- ]* } tmp_df = pd.DataFrame(tmp)
$ O% o' k8 v6 Y8 l2 k if model == train:
. b# {- a7 t) h& F4 g9 u9 X tmp_df.columns = [ID, lat, lon, speed, direction, time, type] . c7 M" Y1 F- g$ ^
else:
D" l2 q2 {4 L& b tmp_df[type] = unknown 2 m/ x, y8 X0 ^
tmp_df.columns = [ID, lat, lon, speed, direction, time, type] : A) I. W) C& k% U$ W
tmp_df[lat] = tmp_df[lat].astype(float) 7 X1 S6 O3 i* K
tmp_df[lon] = tmp_df[lon].astype(float)
- `. @4 x6 Q7 S) v- C7 s tmp_df[speed] = tmp_df[speed].astype(float)
( K& ]6 Q# h. S4 X2 Z; \ tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本
4 B; @: g7 `- P2 ~( y8 e7 U. `# c return tmp_df # C2 Y# k+ |( J+ C' w
# 平面坐标转经纬度,供初赛数据使用 1 L* l9 ]8 k8 ~# ?9 h4 X
# 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud
* V; t0 x+ w. F+ D4 n0 J9 o def transform_xy2lonlat(df): 6 C' e3 M" K2 ~) b' S3 J
x = df[lat].values
) c5 _8 @9 e8 |: x. Y/ v) B! o y = df[lon].values 1 C3 _4 y+ b& v/ C2 ^( H
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 )
" o2 y9 | M$ {7 a df[lon], df[lat] = p(y, x, inverse=True)
, s4 T- \2 N. u+ J, Y return df / n6 D% Q) E; G" ]: ^
#修改数据的时间格式 # f. o J% z7 z+ p* `
def reformat_strtime(time_str=None, START_YEAR="2019"):
. ]: ], _4 n0 d5 L; C """Reformat the strtime with the form 08 14 to START_YEAR-08-14 """ 3 a5 u5 r3 U' U4 i$ d& y
time_str_split = time_str.split(" ")
0 |/ E/ g* C( X time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4]
0 N0 ~! B' l6 G$ p' T3 K# w9 @ time_str_reformat = time_str_reformat + " " + time_str_split[1]
( |, @0 o2 P( M' F% _ # time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S) # ~3 F" [3 ]$ I" n$ w f
return time_str_reformat 9 Y/ m! O$ P2 H
#计算两个点的距离
/ Q7 g- }* i1 Q, _( c2 U def haversine_np(lon1, lat1, lon2, lat2):
) x7 q1 F2 ^( C$ T lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
4 {* I) X9 |5 S5 _ dlon = lon2 - lon1 # |/ R V& G; D5 D. H
dlat = lat2 - lat1 & o u& T" s& {& W o5 l
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
+ q1 h$ f4 v" G, r# T% A0 B# C7 _ c = 2 * np.arcsin(np.sqrt(a)) 1 ~' i. z7 m! J0 S9 F0 n
km = 6367 * c : z2 D/ k3 |5 ^+ a J9 s
return km * 1000 * P2 y. b2 Y: N% Y/ u8 B' y
def compute_traj_diff_time_distance(traj=None):
- d1 i1 z; v1 d+ N8 }) M% h """Compute the sampling time and the coordinate distance."""
( U; a+ o3 d' O5 i # 计算时间的差值
" k: V, R% z: G- i% M* j time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[ " j0 R' d# V6 J
"time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60
' y- @9 b- E. O, O # 计算坐标之间的距离 0 _6 p' I( m9 I
dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0 0 f: j( p& ^' Y1 _1 ~& X5 w
traj["lat"].values[1:], # lat_0
( R, L$ L. C8 _& Z( I3 k' T( ] traj["lon"].values[:-1], # lon_1 6 o4 D. |" ~& e% c0 u w* l; F
traj["lat"].values[:-1] # lat_1 5 s! G: J& b, o' Z" y, q0 ?, c/ W
)
. u: D. s C& l* h; J # 填充第一个值
- L. k( i: d% @ time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()
7 `; K! e! y( w4 x: ?; Q' n0 | dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
! b* Y; F5 g' P3 y, E traj.loc[list(traj.index),time_array] = time_diff_array
8 _- M7 l7 |9 D- M% g4 v) t8 V traj.loc[list(traj.index),dist_array] = dist_diff_array 6 [: w* ~3 o1 m `
return traj
3 t0 I) B! a! |9 M #对轨迹进行异常点的剔除 & }; a7 D2 Z! ]$ i
def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23, 3 N- w% K. R$ Z$ K6 Y
time_interval_maximum=200,
' a9 K" U( S) Y) i; k7 r( R( W) b/ A coord_speed_maximum=700):
6 N( @9 j5 d7 _- V """Assign the anomaly points in traj to np.nan."""
, Y# G0 P3 v$ f4 j* `$ O4 Y/ } def thigma_data(data_y,n): 7 k7 p9 d$ V0 I2 ?7 s) Y1 n9 v
data_x =[i for i in range(len(data_y))] 0 S7 E2 e, g! R' \/ Q! w- ~: p. |
ymean = np.mean(data_y)
' E/ N6 u- ~) }/ P ystd = np.std(data_y)
* K3 @! B' N; W" l/ L' E; z* M threshold1 = ymean - n * ystd
$ _* T- ^0 r2 A; s# G1 { threshold2 = ymean + n * ystd
2 F: `' C9 U+ e$ t' [( ` judge=[]
; _9 Y7 z$ _8 R7 x for data in data_y:
# z- V. b+ o+ S: P3 d, J. v if (data < threshold1)|(data> threshold2): 7 V" C( k- |) {) u! c
judge.append(True)
/ h; E6 ~$ k! x' a# t else:
9 T5 B5 b( `6 J% y judge.append(False)
+ L) ?$ [# d! [) F! V9 S* j8 N return judge
+ h# ]) s B2 F. f+ L # Step 1: The speed anomaly repairing
% j. h* R! f* k/ L5 T6 R7 A is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0)
9 d9 I2 ]% j$ l6 A8 e traj["speed"][is_speed_anomaly] = np.nan
; W0 T! _6 D5 Z9 k+ C7 ~ # Step 2: 根据距离和时间计算速度 - L! Z5 J" J' Y+ U# L6 \: e
is_anomaly = np.array([False] * len(traj)) , {$ ]7 N9 A8 h. Z
traj["coord_speed"] = traj["dist_array"] / traj["time_array"] 4 @- p4 x- j& _3 }7 _. G) s" T
# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点 / ^+ P6 \ {' \6 }5 y( U
is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) , b/ Z7 S$ A# l2 S" y7 g
is_anomaly = is_anomaly | is_anomaly_tmp
7 L* e D# K! ?" Z5 g% E/ E* T is_anomaly.index=traj.index ) @) u' m2 w2 |2 W( U1 e
# Condition 2: 轨迹点的3-sigma异常处理 7 G( ?2 o2 {" ]7 P/ V" _8 i
traj = traj[~is_anomaly].reset_index(drop=True)
q1 `& T$ m6 [+ h is_anomaly = np.array([False] * len(traj)) 8 S7 r. T6 c* J2 }7 J, l( b
if len(traj) != 0: 7 t- T4 a/ U% W
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
: G1 w& y% Z2 ~* I! O lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean()
- Z# {1 r+ o3 Y0 p9 v8 I. } lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std
# l7 i$ v7 C/ o lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std
2 J, c) u5 N$ V6 I7 U8 o9 v* R is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) - Q5 O: E2 N% ?9 c6 C
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low)) - ^9 l% s7 p, i% H! C2 c0 _$ y- P
traj = traj[~is_anomaly].reset_index(drop=True)
, w) q/ o& `% A9 S return traj, [len(is_speed_anomaly) - len(traj)]
* T4 D4 A6 P4 Y$ j2 z' |, i df=get_data(rC:\Users\admin\hy_round1_train_20200102,train) ; N$ h4 o- [ P0 I' n6 [; ^
#对轨迹进行异常点剔除,对nan值进行线性插值
3 E3 [! u/ ]! F+ @1 g ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
+ c3 A6 R5 k) o2 ?! C& A, W/ p DF_NEW=[]
4 Q1 f3 ~$ _1 H; C- Z6 q Anomaly_count=[]
$ N. ^" |& O7 n for ID in tqdm(ID_list): , x8 U# r! h3 s# c- ]2 t$ z: m
df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
[# c. \& O2 c7 I" C df_new,count=assign_traj_anomaly_points_nan(df_id) $ O/ e( j0 W7 K
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
; x* |% {! n. f) l df_new = df_new.fillna(method="bfill") K( p; W! Y, H. ]' t
df_new = df_new.fillna(method="ffill")
7 j u& o6 M% h# p1 N df_new["speed"] = df_new["speed"].clip(0, 23)
9 s" c1 E+ }& ` Anomaly_count.append(count)#统计每个id异常点的数量有多少
9 M8 x" B3 l/ d6 v, T DF_NEW.append(df_new)
; G K: |& D K" E+ P/ C #将数据写入到pkl格式 " e% M; n3 L6 k( I! @5 h
load_save = Load_Save_Data() ! G/ P, ?* i/ a: F, n ]7 K1 h
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")
# u2 `4 S2 ^+ @4 s #### 三类渔船速度和方向可视化 * M( Y- |% z! F4 u5 {* r4 m
# 把训练集的所有数据,根据类别存放到不同的数据文件中
7 v* l; h8 |+ ~8 a f" ]* B def get_diff_data():
" d( P7 G" x' W% u; x Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
/ B1 v; M7 D( L* l& {( M' ` with open(Path,"rb") as f: 6 ]' m3 w8 d2 S
total_data = pickle.load(f)
9 p! z6 D ?% O) [ load_save = Load_Save_Data()
0 Z% p+ V% R& r- B1 A- S kind_data = ["刺网","围网","拖网"]
: v! i3 z7 {9 d1 ]3 ^+ E file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"]
6 N( R& h! D4 u# `8 N0 o for i,datax in enumerate(kind_data):
) j, h/ ?& e8 r data_type = [data for data in total_data if data["type"].unique()[0] == datax]
~# L! k+ j) |1 o" v load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i]) 5 h- Q. H3 S3 D p
get_diff_data() # ]2 Q( ^0 f- f, U( I0 I
#对轨迹进行异常点剔除,对nan值进行线性插值 ; O- n* R, {( m
ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
7 A* L; k8 C1 q2 `' A, G DF_NEW=[]
6 u7 G" h; P! m- U Anomaly_count=[] 0 ]: a l+ ]6 A4 s$ P* U$ r4 }
for ID in tqdm(ID_list):
* o/ c1 s/ Q, h7 r df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
1 m/ l# Z/ D1 D9 Z. _8 X df_new,count=assign_traj_anomaly_points_nan(df_id)
6 j6 \2 Q% B* Z! a" u; B9 v df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
1 E+ V; v. W1 W1 `% E df_new = df_new.fillna(method="bfill") % D z& Q. v* S) M1 M5 K; V
df_new = df_new.fillna(method="ffill")
9 P# @' z M, j; } df_new["speed"] = df_new["speed"].clip(0, 23)
3 T! ~* g5 R7 R Anomaly_count.append(count)#统计每个id异常点的数量有多少
/ x" K1 o+ @5 Z9 Z) [; L6 m4 v DF_NEW.append(df_new)
- M+ a! G9 b- }# N& g' X! F7 F. p # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列
( K) s, t) c- F+ B8 X5 ]/ l def visualize_three_traj_speed_direction():
6 O$ x+ D2 E6 p' @ fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15)) 6 |5 |! ~1 V% }7 g7 A, t
plt.subplots_adjust(wspace=0.3,hspace=0.3) R u0 m, K4 a8 t6 o
# 随机选出刺网的三条轨迹进行可视化
0 v$ H/ w! R/ b, @ file_types = ["ciwang_data","weiwang_data","tuowang_data"] ' D& x: h7 {3 |/ u u
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"]
1 H6 z1 Y4 a' F B/ }. g; ?+ n$ } doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"] 4 t; V% _8 P& a( O. B0 y- L
colors = [pink, lightblue, lightgreen] 3 D4 _: I9 b1 [; a8 M
for i,file_name in tqdm(enumerate(file_types)): 7 P& m9 m) P) p# a, f- {
datax = get_random_one_traj(type=file_name)
* @( n) l; u. {$ ]$ B x_data = datax["速度"].loc[-1:].values 8 ^" z2 Y( g8 f* Q' }9 t# d
y_data = datax["方向"].loc[-1:].values
) m0 \+ O' f8 T* x axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i])
* b, W) X' B2 f$ m1 T4 ` axes[i][0].grid(alpha=2) 7 E9 p3 p$ T5 D# d! L% R6 j
axes[i][0].legend(loc="best") ; N4 y7 E5 Z4 |' \4 g
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i])
, ~* \; s9 I$ u# E" }7 A5 V( z axes[i][1].grid(alpha=2)
( K0 R: @+ i/ o$ E axes[i][1].legend(loc="best") % J8 S+ n; I$ _" F( H4 n% o
plt.show() , I1 u, r4 ? K9 ^7 v, V
visualize_three_traj_speed_direction()
) D7 }0 I d d1 Y! C4 P9 R ' h8 L p4 @& I# ~
作业二:相关性分析。
. G0 D3 Q/ C/ A7 k: \7 O- {/ g7 o8 f data_train.loc[data_train[type]==刺网,type_id]=1
, n9 D) | T2 b: p7 u data_train.loc[data_train[type]==围网,type_id]=2 : S* O3 C( c8 V# {. S8 S& A
data_train.loc[data_train[type]==拖网,type_id]=3 3 x0 a/ J J! O' u/ w
f, ax = plt.subplots(figsize=(9, 6)) / ^' s( y- ]) q6 A6 _8 U
ax = sns.heatmap(np.abs(df.corr()),annot=True)
, K I6 y$ |( k# C( N. E" N plt.show()
7 X; N% `8 D! I& K- ~) K9 \2 R
9 M. \' D- j/ | 从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
8 r3 \" D5 W- {3 L5 [ D, b. Y
! Z/ d9 x- P/ {% E/ Z* D1 T: a9 u/ \4 U6 L0 A. x
( e6 O6 f) I5 ^, m/ Y
5 G! [, u2 I) U: K
|