|
/ B/ ?+ [8 D$ t, h 此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设0 w$ h0 t: Y* s. x( c4 |3 o6 ^8 ?
数据分析的目的: 0 L+ U4 S$ e' M- s- b
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 " @' _1 X: g) j
2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布 ! ^$ s& Q( ]% @
三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd 9 ^: ^0 v D$ T4 G9 z& f
import geopandas as gpd
1 |4 f+ R: G- D" B* m8 Q8 j from pyproj import Proj
5 t9 i Y4 s: S' C from keplergl import KeplerGl
) ?$ i7 l! w, J from tqdm import tqdm i9 s* w4 u) V
import os ' j: ?- l- K; H3 e3 G
import matplotlib.pyplot as plt
" b9 B& C. p2 ^5 i& i' r8 h# \1 Z import shapely / S2 _4 g3 r: e% b1 U. w8 W+ \
import numpy as np 2 S. h# Q! A) X) Q% i6 N" _
from datetime import datetime
1 O/ ~4 q# K) z9 O& Z! f8 [ import warnings ; w( U: z, q8 @# b
warnings.filterwarnings(ignore) & `0 i, j5 O, l- A- q
plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。 % l5 P* h7 ?* B% O; G0 }
plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。 9 g. d" {4 _- p4 w) ~& ^' x
#获取文件夹中的数据 ' Y9 R8 E& k j/ K3 X: e, H" W+ ?
def get_data(file_path,model):
# m$ a* D, F/ M4 @- c7 H' K/ w assert model in [train, test], {} Not Support this type of file.format(model) ; b( D3 I- I" q# U+ m5 u0 w; g2 H6 W
paths = os.listdir(file_path) # V0 J2 A. ^$ W6 O( A. ~" Q
# print(len(paths)) % |) P, a; d+ l3 K# x! b* R: q
tmp = []
) Z6 O* y% {* D; X for t in tqdm(range(len(paths))): 2 x& w- y8 O+ @' c) Q* J4 b. B
p = paths[t] 4 N3 x0 ^& ~1 b( F9 o# B
with open({}/{}.format(file_path, p), encoding=utf-8) as f:
: R+ ~/ }$ `' X1 ` next(f)
9 ]4 F: i F( d4 V6 j. G for line in f.readlines(): & C; o3 l% g8 b. d2 T4 J' n% N
tmp.append(line.strip().split(,))
: P* ?! k1 f5 _. @( b tmp_df = pd.DataFrame(tmp)
8 d, O" k$ ?$ c2 a* B( J' h6 R if model == train:
4 {! P6 T, I E3 ]5 y/ P tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
! h9 g- c0 e) S- W: a/ @* ] else:
6 `) Z9 s5 Z9 i$ j, e* Z4 i tmp_df[type] = unknown + |) k6 f: U& x2 K% ]
tmp_df.columns = [ID, lat, lon, speed, direction, time, type] , ~! c! D( l* k
tmp_df[lat] = tmp_df[lat].astype(float)
% z/ O* V* d% J9 w3 y' o( N tmp_df[lon] = tmp_df[lon].astype(float) : O8 z: b" ^+ W& M5 C6 d
tmp_df[speed] = tmp_df[speed].astype(float) 5 i. c4 V; r- w+ C7 a, @
tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本
5 T: j- G- \' _ I4 y return tmp_df ' U* x5 E- k' m/ A# \2 G! h: Y
# 平面坐标转经纬度,供初赛数据使用 ) ^" }4 t5 D2 l8 {0 ]- T; `0 E/ \! @* B2 B
# 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud
( K' b* V* q: t& d' K0 S% e: J def transform_xy2lonlat(df): ; {# A) q/ I/ {# T G. m6 D
x = df[lat].values
1 w6 Q* y; U# Q" r- W( y' X1 C y = df[lon].values ; `- X. k, ]! m3 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 ) - Z# |# o9 x1 z. |+ D( z
df[lon], df[lat] = p(y, x, inverse=True) ; f- u, k0 } C/ q2 W
return df
' w7 M- }0 p) d- G! u #修改数据的时间格式 6 p; _$ Y6 T2 G- a% a
def reformat_strtime(time_str=None, START_YEAR="2019"): ) w& \! N; M* X& T& }. |
"""Reformat the strtime with the form 08 14 to START_YEAR-08-14 """
* W0 f1 | u+ p R& d, U time_str_split = time_str.split(" ") $ H# _% {! b8 r/ @7 m
time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] ' l. B; b, |5 [9 l: _; V( e6 `
time_str_reformat = time_str_reformat + " " + time_str_split[1]
+ d* o0 h2 K4 P) @* | # time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S)
: r( P, s0 L! H: J return time_str_reformat
* @$ W- K7 |# I9 H. { #计算两个点的距离
- B5 t* S4 j7 C) ]9 @1 s3 a def haversine_np(lon1, lat1, lon2, lat2): ]7 G6 f' U2 k: U& ]7 A
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
& O: |# I- w! N dlon = lon2 - lon1 + S; Y [) `- O: \+ T
dlat = lat2 - lat1 ! g& \( K: c- N' C3 N3 w2 r" Y; e3 g% r
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
8 N) c p1 r) _, f9 x" {1 Y c = 2 * np.arcsin(np.sqrt(a)) + n$ |: U/ L; H: C% I
km = 6367 * c 0 n! B! {% t7 Z* F
return km * 1000 4 w Q' c/ w5 t# e8 O( e7 S
def compute_traj_diff_time_distance(traj=None): + _, j0 h" S+ d! q
"""Compute the sampling time and the coordinate distance."""
" Z: j9 h- R2 j/ H# n4 | # 计算时间的差值 : b. @! j2 I+ V9 P" T; c4 |' ?$ o
time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[
% \ M1 E; x7 L7 z "time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60
' v _8 y5 r$ _0 H' J # 计算坐标之间的距离
$ L" I3 s$ p% e2 A' \9 _7 _ dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0
3 \ E4 q" K& Q1 H5 g traj["lat"].values[1:], # lat_0 8 G p! w1 G I' S5 V K6 V& K
traj["lon"].values[:-1], # lon_1
# i" i; D$ `+ V7 Z+ q traj["lat"].values[:-1] # lat_1
4 w' p3 d) E- I ) G" t9 L! J$ L1 }5 k9 ]
# 填充第一个值 $ d# y: f, ]4 F0 d; f6 k) \
time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist() 2 o2 H' r2 z( }7 a4 |9 }- I0 `/ |( F
dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
& B" p9 _; A/ m" u1 }5 e, i traj.loc[list(traj.index),time_array] = time_diff_array
' _$ R* @( t: P5 |3 s, R; q traj.loc[list(traj.index),dist_array] = dist_diff_array 7 |7 W$ r% |6 C& _
return traj
3 o; _- L* Z* N0 l #对轨迹进行异常点的剔除 ; _2 M' X I m6 D6 e% L! C; Y
def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,
3 R0 e, W d0 G4 s- d time_interval_maximum=200,
5 z: G3 S4 u- p coord_speed_maximum=700): 0 ?0 [+ {8 p6 `8 F6 X; y: H
"""Assign the anomaly points in traj to np.nan."""
" K; k' E* j0 s def thigma_data(data_y,n):
# U! \ B. j1 S- e) W4 Y0 m data_x =[i for i in range(len(data_y))] ( Y9 A+ U: [% n- ]/ w8 v
ymean = np.mean(data_y) 0 \6 i6 c, l5 p
ystd = np.std(data_y)
4 O2 V9 g; h8 L/ l+ l0 w/ B threshold1 = ymean - n * ystd $ ^/ V" K1 @. D) m; h
threshold2 = ymean + n * ystd
" Z" W2 g- {# a9 ] judge=[]
+ [1 ^ t# h3 }, Z( L1 ~4 Z for data in data_y: 9 r5 u/ X( e9 p- y/ u$ t" L* X
if (data < threshold1)|(data> threshold2):
( n2 V! J3 l. S# P1 F2 ? i1 @ judge.append(True)
/ n( A, _+ v$ w% L- o else: 9 R$ g" W% w z# C8 v
judge.append(False) d) S8 M" y3 p3 h* H
return judge
7 q7 `* X# T4 P# t& N; X- z, h- D- G # Step 1: The speed anomaly repairing
0 ~2 a/ }' u, N, n( f is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) ]& T" w: N& r8 ], W- S
traj["speed"][is_speed_anomaly] = np.nan
% P, ^) T5 {3 u' _3 l # Step 2: 根据距离和时间计算速度
- B# Y% }9 l; a5 X is_anomaly = np.array([False] * len(traj))
/ N* e1 z7 ]) ^% m" I* B! {8 Y: _; L traj["coord_speed"] = traj["dist_array"] / traj["time_array"] 9 k0 P9 e1 l; z1 H' i
# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点
# C J7 P6 m2 ? is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) 5 {0 l, M2 ?9 a% J: [& ^
is_anomaly = is_anomaly | is_anomaly_tmp
0 g0 c6 ]% ]& C. o6 z is_anomaly.index=traj.index
0 w# M: u; F5 p$ N9 A9 E( Z% w0 S # Condition 2: 轨迹点的3-sigma异常处理
4 r! b" ]. n# j( w8 g traj = traj[~is_anomaly].reset_index(drop=True) % z3 {% b; n6 c& v8 q& f
is_anomaly = np.array([False] * len(traj)) $ F# M2 _& _5 u6 Y. `; f
if len(traj) != 0:
+ [/ i, p$ o4 r lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
4 m6 v s% Q# y# S- R' I lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean() ! _ u1 ?! [- C/ w. [& K4 Y
lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std 1 O; F+ k1 _+ E9 S
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std # ?; ^; Z) g. M1 A4 U
is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low))
7 U0 v" D4 k1 V is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
0 `5 d3 d1 ^# j" X& E5 k+ ~8 j traj = traj[~is_anomaly].reset_index(drop=True) ) ? l. g, d0 y u
return traj, [len(is_speed_anomaly) - len(traj)] - c9 D" S' F$ f. a! t- B/ _9 f
df=get_data(rC:\Users\admin\hy_round1_train_20200102,train)
; \3 R3 R8 q1 @/ }: J8 Z& T6 k #对轨迹进行异常点剔除,对nan值进行线性插值 ( T" v9 H& }- c- X. q# ]
ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
6 X, ?2 s/ [# ]0 O# g8 Q0 o DF_NEW=[] ' t% H" `5 Y: X" B7 O# b
Anomaly_count=[]
q D. @1 g' k6 Q+ } j5 k) e& A for ID in tqdm(ID_list):
$ D+ O% n5 c- m* Q b# C, l$ I df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
* z! m" C/ Z" D3 ^* D' z B( E df_new,count=assign_traj_anomaly_points_nan(df_id)
* q" u. q j% F9 V4 G df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) 5 `) _9 C) O3 c4 f( T) \, X- y' f
df_new = df_new.fillna(method="bfill") ( [5 Y" G7 o' R0 \3 q
df_new = df_new.fillna(method="ffill") ( I* v( W# s) e- d
df_new["speed"] = df_new["speed"].clip(0, 23) : v h' m( Y( m( n
Anomaly_count.append(count)#统计每个id异常点的数量有多少
- x, @( W: E3 E: e' L$ y DF_NEW.append(df_new) , K1 R3 O1 y) Y s( U# I/ X
#将数据写入到pkl格式
8 ?% Z# F* \ G0 s# J7 { load_save = Load_Save_Data()
& [2 _' m' G& ^ ~1 U$ _( H load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")
9 y5 h5 V9 R s: L+ u #### 三类渔船速度和方向可视化 3 @; b, }- O1 |8 ?9 z
# 把训练集的所有数据,根据类别存放到不同的数据文件中 * n8 L0 | `6 V5 d& u
def get_diff_data():
0 c" l: i. s6 M) f2 N2 b* [8 D3 [ Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
# `* v$ d9 {# N% v4 w: l! Z with open(Path,"rb") as f:
, E$ w! V1 |1 x5 |9 C' ` total_data = pickle.load(f)
' \( d$ P: m) _6 {7 Q load_save = Load_Save_Data()
" x; J# `5 H3 f$ I2 Q5 W' h kind_data = ["刺网","围网","拖网"] 9 I, W$ H1 ~ k7 Z
file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"] 2 |- A, d! U j( _ x
for i,datax in enumerate(kind_data):
: |2 _( Y) v& I2 u5 ]% A data_type = [data for data in total_data if data["type"].unique()[0] == datax]
: V& |% J2 F% m& a4 ]. A8 Z O load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
. z# ~, I+ t' Q2 e: Y6 [ get_diff_data() 6 j, n" H, e8 } N
#对轨迹进行异常点剔除,对nan值进行线性插值 N8 P# a1 G1 W }! V
ID_list=list(pd.DataFrame(df[ID].value_counts()).index) ! \: z* _ a# ^* T Z
DF_NEW=[]
; ?/ \$ ]9 _; F7 `! W, k Anomaly_count=[]
! _5 U' n# U7 g, m c( m/ Q0 a7 W for ID in tqdm(ID_list): ' B" P; |3 @) M# e
df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
1 Y8 x6 F, f, _% _ df_new,count=assign_traj_anomaly_points_nan(df_id) : |: @0 S9 I! R# s, D6 W
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) ; g R; Q! C) d( T; x( V
df_new = df_new.fillna(method="bfill")
: }! x; X1 Z$ V% w: C df_new = df_new.fillna(method="ffill")
9 l; B6 L# k+ W' _! F- N df_new["speed"] = df_new["speed"].clip(0, 23)
0 E$ h, i& |& j) Y0 q7 i, j) \ Anomaly_count.append(count)#统计每个id异常点的数量有多少 8 B2 @3 j' m+ @" W
DF_NEW.append(df_new)
0 N! |1 b. t; m* q # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列
2 Y! k4 }& x+ w0 f def visualize_three_traj_speed_direction(): , T) |6 L1 m1 @5 |
fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15)) 4 D# c: d0 _' P7 v4 g# w
plt.subplots_adjust(wspace=0.3,hspace=0.3)
6 k( l$ ^, b. c6 J7 s+ r/ V7 N0 k! b! I # 随机选出刺网的三条轨迹进行可视化 , P% W& W T" g7 b5 z
file_types = ["ciwang_data","weiwang_data","tuowang_data"]
( Y; ~; D8 J& G/ k- [0 q3 ^ speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] 6 m4 d3 r% T6 L
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"] 1 _, M# s3 R* I/ `% s
colors = [pink, lightblue, lightgreen] & E$ d7 M: V5 r4 y" p1 F' @
for i,file_name in tqdm(enumerate(file_types)): * N7 e( R4 K6 V5 v% |
datax = get_random_one_traj(type=file_name) / \# v0 c8 S! A/ e! p" y
x_data = datax["速度"].loc[-1:].values : r. Z) b& A9 o& p
y_data = datax["方向"].loc[-1:].values 3 A& ] L8 ~" c& X( m- k4 m% }
axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) 6 F1 S' ]/ U# Z5 V* I
axes[i][0].grid(alpha=2)
" z F" A) ]9 O( [, z9 d axes[i][0].legend(loc="best")
! l0 e& S$ E+ o) N0 o2 m0 `. U axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i])
% j, J5 E' Z8 A axes[i][1].grid(alpha=2) / T4 y U* C. A' m. @
axes[i][1].legend(loc="best")
4 S' ]8 W7 p! d# [ plt.show()
' c' q" e: O3 t: p visualize_three_traj_speed_direction() 5 l5 Z4 }* @% l- }+ _' Z
8 u# N/ N9 t# K! w! n$ ^7 h. K# w1 N 作业二:相关性分析。 0 { e1 s' K1 m. t( z3 g
data_train.loc[data_train[type]==刺网,type_id]=1
3 O+ ]' g* e% t+ h# B4 s data_train.loc[data_train[type]==围网,type_id]=2 7 z: m$ |. i: J" e$ Z
data_train.loc[data_train[type]==拖网,type_id]=3
( B* D' [, V" T3 R f, ax = plt.subplots(figsize=(9, 6)) * }& p- i) ?9 _* u
ax = sns.heatmap(np.abs(df.corr()),annot=True) # c0 O" U: ~" }" F" e' u; d
plt.show()
3 u4 }5 k8 ^7 I6 u1 [
4 s- ]* x2 ^$ k& {% A. j# M 从图中可以清楚看到,经纬度和速度跟类型相关性比较大。 6 x; O& z! W ^7 t1 R; X# O, ?
3 q- G5 K) t8 ?3 n4 A! r
# ]0 F/ k8 V& T. E% U; O/ V
% P' D7 j6 ]. Y R+ e0 d. m# D' B( E5 l! N' E
|