M5 }& d0 Y7 O3 } 此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设1 L" v3 r2 _- P+ R
数据分析的目的: ( N: r% J3 |: H: ^8 v
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 4 O. [! d, s/ S! H: A
2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布 - U' {3 E: y+ V) R6 g
三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd ' \( s' Y. g/ b6 k3 J# T- [
import geopandas as gpd
3 a+ i% r3 Y+ Y" f% S0 C from pyproj import Proj 7 d8 f# ]1 c0 ]; k0 B& F6 ^
from keplergl import KeplerGl
6 |% }; Q; C7 y, c. `( ^7 t0 f from tqdm import tqdm $ m" `- x& n2 t3 r6 s; A% k2 m
import os $ v9 ]0 D- Y4 M$ x( C
import matplotlib.pyplot as plt
4 s+ N7 I z: e import shapely
4 [" B h4 L: T9 K7 e: H N import numpy as np 5 F" @$ w( V% B) T) C, [
from datetime import datetime 7 @2 s- h' ^; e0 c2 C
import warnings ) _# t3 P) L! X& {+ o& Y
warnings.filterwarnings(ignore) ; \; ?; O! V1 |( D$ f
plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。 + @) a- j; ~6 r9 I: n1 w
plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。 4 o* K P, G( L1 p
#获取文件夹中的数据
" |8 ? U" M* r: d' m! X7 d def get_data(file_path,model):
! Y( I8 n0 M. v6 X% Z* @) H assert model in [train, test], {} Not Support this type of file.format(model) : D- p& m/ X \& \! G/ G2 F* N& l
paths = os.listdir(file_path)
) b$ @/ D. v9 V/ t# |9 Z0 u # print(len(paths)) # ?5 d% e/ S: r: u
tmp = [] + W; b7 a: l. g' N
for t in tqdm(range(len(paths))):
6 Y. r& Z- j q# l& d0 k% ` p = paths[t] + W& v0 ~" L$ B3 J4 J0 p
with open({}/{}.format(file_path, p), encoding=utf-8) as f:
2 _% `8 a9 U$ G* m! i next(f)
# G2 Q- U/ A' a for line in f.readlines(): 3 }! B, s; `9 w
tmp.append(line.strip().split(,))
& @/ ]. U' V# ?# X5 F3 Z7 }% ]: u |' w tmp_df = pd.DataFrame(tmp)
( v a$ ]# F# j9 x, D( s5 c# I if model == train:
) x4 \9 F# M R4 L T tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
) H$ G* g: |: V else: ' o4 O# u) T) r; M8 @
tmp_df[type] = unknown " e* T h" f9 ?! t
tmp_df.columns = [ID, lat, lon, speed, direction, time, type] 8 S: \2 V9 @+ X2 f! q& _
tmp_df[lat] = tmp_df[lat].astype(float) $ G p }5 ? }- Z W
tmp_df[lon] = tmp_df[lon].astype(float) / h1 h4 ]1 E* @) _
tmp_df[speed] = tmp_df[speed].astype(float)
+ ]3 H6 l' L% [ [1 O( O tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本
- X" ~1 X0 M" x0 H/ m' A return tmp_df
( v* B& k7 J" O) s- J# \( l # 平面坐标转经纬度,供初赛数据使用 % Z# P+ s) W# l4 D" ~+ O( @
# 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud # R1 q/ L1 q& o- e. e. A
def transform_xy2lonlat(df): ( a/ R: p# i7 _0 {
x = df[lat].values 5 [# R0 H$ M) D8 P- b' ~! M
y = df[lon].values
* X+ E' X# r# u' O* Y 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 ) # [& Z7 O) t6 g
df[lon], df[lat] = p(y, x, inverse=True)
0 J0 v# {( z0 _$ ^" P/ @ return df 4 ?1 B% `9 T! I w! _* \* M
#修改数据的时间格式
# B( D, T, n- T def reformat_strtime(time_str=None, START_YEAR="2019"):
) @6 f% O& K5 V" k! U8 B """Reformat the strtime with the form 08 14 to START_YEAR-08-14 """ ( ~* Q) M% E: Q
time_str_split = time_str.split(" ") 3 D N! D0 y& C3 m3 z% |
time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] l9 x6 o5 }7 z6 |
time_str_reformat = time_str_reformat + " " + time_str_split[1] ) b4 Q1 s- x5 v& {
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S) ( T. y# j& Z( M5 e# E6 h
return time_str_reformat
% F1 B y/ c& M4 ^ #计算两个点的距离 # F; ]3 z* U, ]* ^, ^8 P+ v
def haversine_np(lon1, lat1, lon2, lat2):
* r4 R0 V3 f0 Y% g* ?/ D- w lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
' m" _/ d: A E dlon = lon2 - lon1
! P% r8 Y+ g3 n8 X; v dlat = lat2 - lat1
+ N+ P3 Z' w* E' Z' w" v4 Y7 Q L" _ a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
7 D; W& n: X t& b$ Y c = 2 * np.arcsin(np.sqrt(a))
: K* \, V/ k) X- G; M km = 6367 * c
9 `9 ~6 a4 L2 c1 l- X return km * 1000
" U- K' n7 D; c. p/ s/ x* B# f def compute_traj_diff_time_distance(traj=None):
- o @- u0 w. Z4 j6 R- _ """Compute the sampling time and the coordinate distance.""" , Q: v2 _: k2 p. h: ?
# 计算时间的差值
; {0 t* C4 S ^$ @ x time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[
7 `; a( r }1 r9 {- v "time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60 4 {. N: I( E" E2 Y0 M, a5 C; Z
# 计算坐标之间的距离
: p# B% v! c2 z2 }6 R dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0 6 Q7 q5 l& F2 c" }* c! [0 ]
traj["lat"].values[1:], # lat_0 8 F5 y% B* ?7 e4 n* g9 C% |
traj["lon"].values[:-1], # lon_1
) U" \+ z/ N( R5 r3 M0 ^- g4 L" c traj["lat"].values[:-1] # lat_1
7 F1 k5 X# O2 ?7 | )
; c% M& e# i) K7 L$ ? # 填充第一个值 " r2 ~& B6 n9 B
time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()
0 Y3 ^4 x; z. w8 Q dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
1 c$ D. g. N3 Q traj.loc[list(traj.index),time_array] = time_diff_array # Z5 [# B8 L2 k" }; O) P, Y
traj.loc[list(traj.index),dist_array] = dist_diff_array 4 A/ `1 u2 d/ W$ \6 O7 o# ?
return traj
a1 o/ \1 l# K P! g% u #对轨迹进行异常点的剔除
, [3 s) H) g; k( U8 Q, Z def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,
( f" q) `" \: a8 b; ] c4 W, g& W- y time_interval_maximum=200, 3 O/ g7 U7 J; u/ t; G1 \
coord_speed_maximum=700):
( }( h% H8 J$ N """Assign the anomaly points in traj to np.nan."""
2 M3 ]8 ?8 [! @2 b! ?$ h def thigma_data(data_y,n): : G. L. i3 I6 q$ ~$ U+ Q+ r
data_x =[i for i in range(len(data_y))]
6 A7 M1 \9 I8 v1 p3 x7 o ymean = np.mean(data_y) ' q! c* o" l/ |, j* \8 s2 F4 a
ystd = np.std(data_y)
& J- ~3 g: Q ^1 W4 g threshold1 = ymean - n * ystd X" M! V2 F4 Q, p* M2 p y4 z( \
threshold2 = ymean + n * ystd
5 W; A! K1 Q% T) `' E( u judge=[] : I. E$ p9 Y' n& R# T
for data in data_y:
% t7 e( \: }( v$ N. _% t1 d if (data < threshold1)|(data> threshold2):
. w/ P4 f* s3 X judge.append(True) . A! t: ~2 _$ S( x- b
else:
' e; b7 ^0 b! j$ P2 B- H7 D2 y judge.append(False) ' R! T8 |% \5 V' X' k
return judge 4 F7 B) _$ u! g, U7 D) ^% g6 p
# Step 1: The speed anomaly repairing
$ ~; E6 Q0 Z- O2 j is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0)
( T5 `5 |9 h6 ]( @ traj["speed"][is_speed_anomaly] = np.nan
% C8 k" N O6 Y( e # Step 2: 根据距离和时间计算速度 . j' V ]- H. i# j" i" Q+ z4 x- s
is_anomaly = np.array([False] * len(traj))
6 G, u& |% [- Q- V traj["coord_speed"] = traj["dist_array"] / traj["time_array"]
0 v( f; y5 F8 G5 h$ v& o( q # Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点 * d# W9 {$ V _
is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3))
) T: r8 N9 @: ~3 g c! q+ s is_anomaly = is_anomaly | is_anomaly_tmp
: L# u# v$ ?3 [4 N( L$ c" ~ is_anomaly.index=traj.index
& Y0 F" i. y9 [) j9 Z* X! v* [ # Condition 2: 轨迹点的3-sigma异常处理 J% y* K# ?8 z
traj = traj[~is_anomaly].reset_index(drop=True)
- F$ D' Z+ N5 T is_anomaly = np.array([False] * len(traj))
, t3 }$ j- A. j7 g; x- o6 j$ D$ X if len(traj) != 0:
6 i- {: n2 C7 i2 |1 U' |; I( K! k lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
! H# V# @, i7 _0 Z% v, U$ _$ j. B lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean()
: u" g& d F% R/ _% J" { lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std 3 a4 S* Y" C% F7 i
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std
. c C4 Z$ W) w8 _ is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) - \9 J9 n. r" |) v
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low)) ; U6 j, A D( o; d
traj = traj[~is_anomaly].reset_index(drop=True) # u" W; @% V, f' ~
return traj, [len(is_speed_anomaly) - len(traj)]
/ s& \2 K7 P9 y0 G6 m; u df=get_data(rC:\Users\admin\hy_round1_train_20200102,train) / I4 f; V* t; N7 v ?# w- v/ n
#对轨迹进行异常点剔除,对nan值进行线性插值
, q+ K; c% T! G4 c ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
/ [* R4 V- M7 C" v* N# B6 c DF_NEW=[]
( g. S: W# h" y Anomaly_count=[]
6 D7 ?. k6 _8 ?9 p e for ID in tqdm(ID_list): % I" M2 N- b& ?6 e0 x
df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) . l9 `9 q; [ a) p6 y
df_new,count=assign_traj_anomaly_points_nan(df_id)
$ x o t' L0 U7 a: V df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) ( l$ h& E5 c, I( m2 D
df_new = df_new.fillna(method="bfill")
! V; I# w" `( L+ D7 \, U' v5 c df_new = df_new.fillna(method="ffill") 0 \; X3 |- J% ]4 D2 `
df_new["speed"] = df_new["speed"].clip(0, 23) * x( d! I6 a5 v+ R/ r$ r
Anomaly_count.append(count)#统计每个id异常点的数量有多少 ) O. b/ d! x* u; [3 V$ y0 n$ w6 |: d
DF_NEW.append(df_new) ( d! W; X2 I6 @9 T# P
#将数据写入到pkl格式
6 N* |% ]0 K3 M! O load_save = Load_Save_Data()
) P0 s. A8 X: L( M( [7 } load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl") 2 N1 i$ E) |# V7 x6 J* g
#### 三类渔船速度和方向可视化 ! e' l" t" _0 D! B
# 把训练集的所有数据,根据类别存放到不同的数据文件中 5 F+ C) v% v, Q7 O% R0 d
def get_diff_data():
6 P. Y7 v# ~0 a# l( ~ Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl" 0 W' C5 ~& m2 v& [: ]: t
with open(Path,"rb") as f:
6 q# ]# x) C+ j5 d# ]- y( J total_data = pickle.load(f) / X0 v9 @; ^/ O, c
load_save = Load_Save_Data()
" B( e1 p: f, f9 R7 O' S) S+ n kind_data = ["刺网","围网","拖网"]
1 b! [9 p0 g$ ?# {" `, V file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"]
- R& `7 ]! [9 W, J$ ^) d for i,datax in enumerate(kind_data):
7 G b7 Z, O3 C: N! p( g* j; v data_type = [data for data in total_data if data["type"].unique()[0] == datax]
: u$ q; F( I3 T load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
' k& A: s' D, f1 u* V get_diff_data()
8 h4 o/ B( w7 k #对轨迹进行异常点剔除,对nan值进行线性插值
; u% p+ F( Q! h l0 x ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
& R4 S( R6 m3 \5 f& {' ~# J DF_NEW=[] 8 Z, @! K1 h& ]; o+ n4 d
Anomaly_count=[]
" ^- G" w3 b, z. A) r! s# m for ID in tqdm(ID_list):
: w& V8 G6 J+ j! I$ E df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) 4 C% E- I% o, n. i, J3 F, E0 {" |( r Y
df_new,count=assign_traj_anomaly_points_nan(df_id) $ c( l' u/ `1 n8 m
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
. ~% e) F' F. o* q/ X df_new = df_new.fillna(method="bfill")
' {, V1 T) F; D/ K# A9 t df_new = df_new.fillna(method="ffill") 0 j, N5 e" L% h9 u
df_new["speed"] = df_new["speed"].clip(0, 23) 7 w% `+ Y: z) Y, k0 ~ |8 x
Anomaly_count.append(count)#统计每个id异常点的数量有多少
2 U, o+ x0 w2 B( F0 x DF_NEW.append(df_new)
: C9 z/ s4 b9 z2 N$ e, }4 a # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列
: H3 a# n2 G& f& t+ C def visualize_three_traj_speed_direction():
9 x9 l, v+ B, y/ W7 @% c5 D fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15))
# l5 B7 ?: X9 U0 X- J5 n& g plt.subplots_adjust(wspace=0.3,hspace=0.3)
; `% K! N Z; f) {1 m/ S8 @- Y # 随机选出刺网的三条轨迹进行可视化 1 V R1 _1 Z" n6 t
file_types = ["ciwang_data","weiwang_data","tuowang_data"] - Q0 t5 t* m" U
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] 1 E# w& n. S* g2 A: i
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"] 2 l" |3 t8 s/ ^+ g0 U1 L
colors = [pink, lightblue, lightgreen]
, {# n0 G/ @* d' k Q for i,file_name in tqdm(enumerate(file_types)):
) s G3 e6 Q$ `# m" N8 H datax = get_random_one_traj(type=file_name) 0 U Y1 C# X3 }' R, O2 _
x_data = datax["速度"].loc[-1:].values
# x- N, E0 J+ N5 d. b y_data = datax["方向"].loc[-1:].values
9 X$ A/ l8 q$ Q. K% i) m axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) " Z# B8 ?* ` O- s% ?/ ~
axes[i][0].grid(alpha=2) % ?, p( \; W! J
axes[i][0].legend(loc="best") # f/ g F. U) o0 s: s* j1 {6 q( @
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) ! l& O$ S6 }" g
axes[i][1].grid(alpha=2)
, _4 W }$ j! E) B: \6 Q) ?1 \ axes[i][1].legend(loc="best")
- _& a. C3 o: V P" {) q plt.show()
. ?$ s$ Y1 K1 f* m visualize_three_traj_speed_direction() 4 `, }3 S% z$ S- |9 G- I
' |7 T2 h: g! r! I: a: v( c 作业二:相关性分析。 & d4 c/ a6 _0 e+ E6 W. K! p# ?
data_train.loc[data_train[type]==刺网,type_id]=1
( C! K2 }- C8 R# U3 b" K# g1 \0 S data_train.loc[data_train[type]==围网,type_id]=2
+ f' K7 }2 u' B8 V4 f6 R1 r data_train.loc[data_train[type]==拖网,type_id]=3
r$ G# v, Q+ w- w f, ax = plt.subplots(figsize=(9, 6))
1 p- F5 H; f4 |& Q ax = sns.heatmap(np.abs(df.corr()),annot=True) ! X9 N% O, B6 o6 ^) W; @
plt.show() $ c; O; K, e7 n
. {7 b) y3 B6 @9 G
从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
|7 ~3 n) F9 @2 j) m% W3 M
* C$ i& @9 I N- w( i& e6 E. l, L5 H/ W, H
+ J( l% r. n: z; }/ D* m: t" K: w
@( l4 y U2 a- ?4 O |