|
. i9 f+ [; n/ g+ j 此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设
9 y$ c2 D' i# I4 [" ` 数据分析的目的:
3 _! H5 ~3 F/ r7 x/ w 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 ) A6 t" m) q, q0 X, O
2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布
% D, ]3 X! `% U* w, ~7 E6 j 三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd
+ h c( ^- K8 P* i" s import geopandas as gpd % G% |; @- B" B
from pyproj import Proj
! I; L F: K7 D: H- ^# ` from keplergl import KeplerGl
! Z( I; x* e# ] G" ? I3 @' [ from tqdm import tqdm 1 _+ V: z4 b/ W8 R2 H
import os
. f( g5 v9 D I8 Z8 n* y- ?. @ import matplotlib.pyplot as plt 5 y9 s3 o7 s2 x
import shapely [- Z/ B) R; y$ J& ^
import numpy as np
. w9 Y* w% ^! X& A# Q from datetime import datetime
3 a, ?4 [' X7 D' ^1 A import warnings ; p: q7 @; }, {# p. Z7 W& {
warnings.filterwarnings(ignore) " K5 L9 p/ p, d" b( J+ {
plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。
9 i m2 x% S. I6 L plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。
\1 P, s, h0 n9 i2 h7 K #获取文件夹中的数据
/ }3 r- _& z- h, T# a$ s def get_data(file_path,model): 6 K; r4 O+ Q& \9 H
assert model in [train, test], {} Not Support this type of file.format(model) , i. I1 d# U$ ^9 M8 m7 ^+ m
paths = os.listdir(file_path)
' n7 E' v$ A- L/ G" k% g3 w, O& f; }* k # print(len(paths))
( ^6 S* K; \% Z9 x tmp = []
2 ?. C: ^' h. k: }" D for t in tqdm(range(len(paths))): 8 `# c( C. Z( P1 R! x
p = paths[t]
; T) t5 K; U; z. D9 f' ~ z6 c with open({}/{}.format(file_path, p), encoding=utf-8) as f: M/ ]3 f* f X
next(f) 6 l# n' d# q( x) u) Q
for line in f.readlines():
# Y0 |! o/ F, S' Q8 P! } l/ g R tmp.append(line.strip().split(,)) # g) ?! F* o' I% E
tmp_df = pd.DataFrame(tmp) ( |1 s& m, F1 ~8 _. U& B( C% b( @3 f
if model == train:
3 t+ w) q/ A% V2 s! J tmp_df.columns = [ID, lat, lon, speed, direction, time, type] * o; _, B: e( r, Z6 I F9 Y+ a
else:
$ ?" n) J' ?- {* h tmp_df[type] = unknown + j5 K+ E( ?9 |, d' U. O
tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
. b) T) m5 O4 \% u t tmp_df[lat] = tmp_df[lat].astype(float) ; g. B. q& p k3 a6 c9 ~1 w. I
tmp_df[lon] = tmp_df[lon].astype(float)
& \" Y( q3 q% P8 L tmp_df[speed] = tmp_df[speed].astype(float)
2 @& [7 g! z5 S* R1 q* u) X6 \0 b tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本 ! e) i8 S# a) Y) v7 g2 L8 ] b- o
return tmp_df
2 C' H2 ~7 Q5 o* m5 v # 平面坐标转经纬度,供初赛数据使用
$ ]& ], x/ x, L$ b1 t # 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud $ G4 P( n6 y5 n9 n( Z8 d! h k
def transform_xy2lonlat(df):
2 K% l0 y( \9 Y. u4 L- W7 ? x = df[lat].values 9 |3 V U9 d/ B4 z$ P% z5 Y" o
y = df[lon].values * } A7 ]% O2 i h0 k
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 )
' i' T4 k' J6 S" _2 X/ X8 S B df[lon], df[lat] = p(y, x, inverse=True) 5 i1 ` g; f* ?, z" N& ~, A! v9 y0 n
return df
& z& r1 `4 a: u! V6 @/ i2 z2 X9 M( W #修改数据的时间格式
( B1 ?: w" v) s def reformat_strtime(time_str=None, START_YEAR="2019"):
7 p; l( Z) C' D1 K o """Reformat the strtime with the form 08 14 to START_YEAR-08-14 """ # K7 n; [9 `* @( B+ F# U |
time_str_split = time_str.split(" ")
8 R. h1 E/ n+ n% a time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] ' v* _, P5 T5 R( F
time_str_reformat = time_str_reformat + " " + time_str_split[1]
9 W! X* w! F) m, e0 ]1 v' E # time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S) % C# V0 I o/ k; w2 S/ E
return time_str_reformat
) q& L" z% L: }/ t; _ #计算两个点的距离 / J/ S9 A* u& c: Q/ ~
def haversine_np(lon1, lat1, lon2, lat2):
# e9 t& _' q* F, q( D/ Q lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) 5 Z3 E" g0 c( J+ Q& J/ _/ w, l
dlon = lon2 - lon1
% J* ?6 o$ B( V8 i6 S" [4 { dlat = lat2 - lat1
& l5 x5 Q# g" g, U# U6 V" c0 f a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 [ T4 `- u, G
c = 2 * np.arcsin(np.sqrt(a)) 1 B( G' s* \" }8 |: w9 K1 R, Y
km = 6367 * c
/ u/ w) `! g* l return km * 1000 . M1 {2 p' Z9 f$ y4 j
def compute_traj_diff_time_distance(traj=None):
, [9 A: ]9 {6 Y% ~: q! U """Compute the sampling time and the coordinate distance."""
* L+ K$ I3 S8 F9 i A. a) J. z0 t # 计算时间的差值 . O9 _2 Z7 A, u2 l! G
time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[
2 D- _- X$ \/ j! k% H4 w "time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60 / B; C5 X2 p. @$ N5 h$ G
# 计算坐标之间的距离 - P; `4 a7 A5 @9 H7 i$ v
dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0 5 e9 a2 [- e! `6 K) M5 c+ z0 A
traj["lat"].values[1:], # lat_0
, b. Q& i, P5 D. V, b. Z traj["lon"].values[:-1], # lon_1 - c$ D: s9 ^7 B5 ~, r
traj["lat"].values[:-1] # lat_1 4 z7 m. Y% p* j5 l6 e4 Y: y5 G
)
; E+ x7 d& E9 y0 m2 H/ c" ~. _ # 填充第一个值
5 a! T2 ?7 G8 X. x$ j' j3 g# c time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()
6 Y' s" T& [$ ^* g/ A' F1 g dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist() 8 D g! x# z" s5 v5 t
traj.loc[list(traj.index),time_array] = time_diff_array
( @' z: [( y/ Z* ?% o C7 f traj.loc[list(traj.index),dist_array] = dist_diff_array , |, x, S4 w8 A) [' p- L/ e
return traj
0 Y9 h9 l' O, V M. S) ? #对轨迹进行异常点的剔除 6 V9 _( z& X# _! |/ \
def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23, . v5 w& m% p J/ H6 `
time_interval_maximum=200, : |7 v+ u4 _0 m$ C) E
coord_speed_maximum=700): 9 _, W; D% L+ [8 D
"""Assign the anomaly points in traj to np.nan.""" + j( i; ?+ N7 v8 w
def thigma_data(data_y,n):
, b$ Z' H7 @9 s: |9 Y( u/ A data_x =[i for i in range(len(data_y))] 9 w) I, |# b3 {; [- z, m
ymean = np.mean(data_y) - l1 V5 u8 @ L6 ]( ^5 @
ystd = np.std(data_y) A* |$ ?( Y+ Q2 V5 z9 X2 N# W
threshold1 = ymean - n * ystd Y4 t! _9 a) v" Z9 m, N" E
threshold2 = ymean + n * ystd
( P& P( e) _; L3 q9 n7 C+ t( a* w judge=[] # G3 D$ K o7 `. d$ y
for data in data_y:
\& H) l- L- |. J% S! T- ]* A if (data < threshold1)|(data> threshold2):
& E) C2 y0 m4 w2 i' b judge.append(True) 3 t8 G6 J, z- \4 e `- k3 }% e
else:
/ @+ D' D% }) @! H judge.append(False) + a! X) Q' O6 s# ]
return judge
1 y; D6 j8 X) d # Step 1: The speed anomaly repairing $ J; f5 F' z0 q% ~* L
is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) 8 a0 }0 m( i# z, t& j) T, M
traj["speed"][is_speed_anomaly] = np.nan
1 {# ^. V: C6 a5 s # Step 2: 根据距离和时间计算速度 . B- Y7 ]& T4 E+ t& a$ @
is_anomaly = np.array([False] * len(traj)) ) W' b( X# ]( J- ]% N/ J
traj["coord_speed"] = traj["dist_array"] / traj["time_array"] ! z- ?9 E# L0 [( F* C6 F% n& G& M
# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点 - j4 v( ]: ~- H0 H. L
is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) 5 x$ @" J0 M6 U8 M; ?: R
is_anomaly = is_anomaly | is_anomaly_tmp 6 A Y! Y$ g9 f9 Y
is_anomaly.index=traj.index
* A& y9 G$ G @6 L- Z$ ^ # Condition 2: 轨迹点的3-sigma异常处理
% E0 A7 r- m3 k# | traj = traj[~is_anomaly].reset_index(drop=True)
5 _3 o; g7 |+ d* {* Z! z is_anomaly = np.array([False] * len(traj)) " \$ K& ~/ G3 G+ C: @0 `
if len(traj) != 0:
! ~- g* ~, w1 f+ ^6 F lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
+ _6 z8 g5 n, h: c+ n0 o lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean()
$ q! U6 n1 X d( G lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std
- l! E/ k: r. T0 @3 ?% Y) R lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std ( V8 N" R6 }: x5 _. d
is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low))
( O. ^# ]% r! a" ^: c% ]* [2 r" o is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low)) * L( o" R% D4 A0 t/ q6 ~
traj = traj[~is_anomaly].reset_index(drop=True) 9 r) @% ^3 G+ b- S% B
return traj, [len(is_speed_anomaly) - len(traj)]
8 D& z" l( R* h7 d1 S df=get_data(rC:\Users\admin\hy_round1_train_20200102,train) 4 q, F+ p' c, U7 D" p2 _4 {& p
#对轨迹进行异常点剔除,对nan值进行线性插值 6 n: y% r' }/ k, l; F: o
ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
+ E, K* J, R# v DF_NEW=[]
" P+ Y) F# N9 ~ Anomaly_count=[]
7 ?$ @8 _7 a/ L- A for ID in tqdm(ID_list):
! h( p. g9 x" E; g df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
& u9 j+ a& }7 J6 K" k df_new,count=assign_traj_anomaly_points_nan(df_id)
: n& D* \) G: J3 [( F- A df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) 0 U0 h$ ]' Q* N
df_new = df_new.fillna(method="bfill")
' x& I2 o. p8 T df_new = df_new.fillna(method="ffill") " f. g( W# E" V, i9 ]/ s
df_new["speed"] = df_new["speed"].clip(0, 23) ! [& u4 |" j8 r- t6 m
Anomaly_count.append(count)#统计每个id异常点的数量有多少 9 b9 a- c3 G- t8 I# i* J% [7 A
DF_NEW.append(df_new) + z1 ^& v" N: z) O6 H1 a0 u
#将数据写入到pkl格式 & } T Q; i6 G: J0 l( F/ W' w
load_save = Load_Save_Data() $ d" Y8 ?/ A; ]/ W4 A
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")
) {+ O; {1 z' F* C `( ]8 t #### 三类渔船速度和方向可视化 & l7 q& e1 R) C. l! ]& m3 y
# 把训练集的所有数据,根据类别存放到不同的数据文件中
- k: D$ y$ S2 N/ ^3 ]- M7 o! O def get_diff_data(): ; f! y5 l+ F( N& Y; D; x
Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl" $ \7 _9 S/ i4 j
with open(Path,"rb") as f:
$ q8 o. W+ i2 B' U- `! n1 x# c total_data = pickle.load(f) , }5 v' O# \, V q% R8 Z
load_save = Load_Save_Data() & j& [8 ?* a% S/ U% v3 L" B
kind_data = ["刺网","围网","拖网"]
' [& E& t' j) g2 m) q+ ` file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"] 5 P% w* e6 h" d) U4 v
for i,datax in enumerate(kind_data): ' C: @, P9 k# g( X8 M
data_type = [data for data in total_data if data["type"].unique()[0] == datax] ; I4 u; g- `: t) D. U
load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
' G4 P/ D/ P- M get_diff_data() + D% }, s" t- ^, N
#对轨迹进行异常点剔除,对nan值进行线性插值
' f3 f' V( A6 Y- [ ID_list=list(pd.DataFrame(df[ID].value_counts()).index) ' n, B" m5 b) P R& M) q' n
DF_NEW=[] _2 ?' u2 A, D0 Q* `
Anomaly_count=[] ! }9 O# e; b( E' ^# a# J9 b& \
for ID in tqdm(ID_list): 3 u4 v4 L5 _: h+ m: Y) J
df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
4 Z; B) H6 e9 p1 R df_new,count=assign_traj_anomaly_points_nan(df_id)
! E2 @' c' i0 \! ^* V/ m df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
/ d/ D5 i# @6 _ B' e+ d$ s df_new = df_new.fillna(method="bfill")
/ n, X6 b3 f6 s& i# q+ n- @4 t9 P df_new = df_new.fillna(method="ffill") * h! z8 d, A! z9 I# w
df_new["speed"] = df_new["speed"].clip(0, 23)
" |+ A$ F7 J. ]! ]/ R' ~# M Anomaly_count.append(count)#统计每个id异常点的数量有多少 % E0 [8 y4 G* E$ G% U
DF_NEW.append(df_new)
' b9 F" A: f" g$ M1 D/ y2 k # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列 & ?/ \3 R; z" s/ M% K
def visualize_three_traj_speed_direction(): - k2 ?' s) h6 X6 O3 a
fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15))
7 W t0 h( H* U" g1 W plt.subplots_adjust(wspace=0.3,hspace=0.3) - W5 k3 K# B6 g/ e2 f
# 随机选出刺网的三条轨迹进行可视化 2 f) |2 m6 Q) `! w" y% C
file_types = ["ciwang_data","weiwang_data","tuowang_data"]
! u& F0 h. D5 U8 `) p& @5 {2 j speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"]
+ `2 D5 Y8 E, @ m doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"]
# K/ o z1 t9 s) v |) O colors = [pink, lightblue, lightgreen] 5 z( W. W5 E+ D+ ~7 x6 \$ @. e! \
for i,file_name in tqdm(enumerate(file_types)): ; x9 I, m$ u2 N+ E$ h1 e( t' N& c
datax = get_random_one_traj(type=file_name) 5 v( Q9 f. m. f" i' Y& E
x_data = datax["速度"].loc[-1:].values
- k+ M0 K1 d4 m5 g y_data = datax["方向"].loc[-1:].values 5 v- x) i$ ?, j* P8 n2 T
axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) 9 z# P" S. f5 y
axes[i][0].grid(alpha=2) . \5 J2 h: q* }" {1 r$ P& R
axes[i][0].legend(loc="best") 8 F, L+ l* _& G) E" i' j
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) # F5 Q: T$ B, B8 w5 r) v2 Z
axes[i][1].grid(alpha=2)
2 m8 }$ P0 I& j+ R! d' V1 E axes[i][1].legend(loc="best")
# w' t+ u/ L4 v) b3 a& ] plt.show()
9 o( u V" V% A1 k( ]2 x2 c visualize_three_traj_speed_direction() " W) F5 D" n* y2 A4 c7 h D! \" e
) W# `5 Y3 ]( T) Z( a
作业二:相关性分析。 / U' ~, Y9 M$ W" l7 ?1 t. o
data_train.loc[data_train[type]==刺网,type_id]=1
2 d" L4 k2 T- v1 j) [/ \ data_train.loc[data_train[type]==围网,type_id]=2 / v# s8 N2 F" K8 ], ]- B/ u+ t
data_train.loc[data_train[type]==拖网,type_id]=3
8 q" S& s! G% `& m- j& t2 p f, ax = plt.subplots(figsize=(9, 6))
: f& b0 T3 x* f' ^8 G ax = sns.heatmap(np.abs(df.corr()),annot=True)
) c p4 w! C! Z8 w plt.show() d) q: k9 ]# F. v X
% s7 _% E4 ~7 ]9 M \" y* x 从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
* [9 z3 Z' ]3 n* }( `/ o; [" l2 D( W% C `# K
# c+ f% N% v3 ^ d" n2 _
( z- o/ l* r2 M' G/ J7 X5 H6 V9 H3 s5 S) ~, r, i3 n
|