|
5 J% o' O6 X, K/ |& R& q* \9 { 此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设/ C0 d% n) Q; m5 X
数据分析的目的: ; }; [6 r9 c4 J7 e
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
. Y6 ^: g. l4 \& r v% E 2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布 4 c4 H2 f5 f [# p8 I, I! l! j: e
三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd - S! q! v1 S# s+ G( ?
import geopandas as gpd ( {- m/ Z( D% O1 W9 B9 p9 g
from pyproj import Proj
6 l# c2 T/ ~8 u4 m from keplergl import KeplerGl
: y, F; p/ E. l* ^6 J. @ from tqdm import tqdm
& U8 n+ \; {, G/ K5 {% c import os
5 j: G+ ^6 S4 n3 z import matplotlib.pyplot as plt " z! j) o7 k3 a$ M) |
import shapely : _# K6 H2 J) U- d7 }& S' {3 z
import numpy as np 2 D4 b# w7 K8 L Q: j Q* C+ S: S( P
from datetime import datetime
4 ?8 H3 o2 p3 g- I; y/ `4 @' z# E; c import warnings
3 q+ E; {! y% f* b warnings.filterwarnings(ignore) ' D4 ~, u5 ?' m$ o8 _
plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。 : [3 h @, q, W6 @& [' i
plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。 - S" O$ d; S; m/ M& a% N
#获取文件夹中的数据
R4 d. K4 H: C, z3 @7 j def get_data(file_path,model): % M* S, L8 c1 F: S
assert model in [train, test], {} Not Support this type of file.format(model) , a+ n( |9 _, Y% W3 D* H
paths = os.listdir(file_path) 2 }- A1 U$ E3 P0 f& s. Z0 Y2 n+ V, }3 j0 ?
# print(len(paths))
# V- g5 L' K5 O0 I% q8 ^ tmp = []
# S9 }( W+ t: Q/ W2 Y for t in tqdm(range(len(paths))):
" r6 ?! v" U$ I1 V3 k p = paths[t] ! f" W3 C' X1 V) Q$ }" L( f
with open({}/{}.format(file_path, p), encoding=utf-8) as f:
4 c; |& K; `7 m' C2 v) k( q6 S4 E next(f)
; ?. M( M2 R$ t, V: v. H; q for line in f.readlines():
/ g3 h3 X9 h$ o" d tmp.append(line.strip().split(,)) 8 p9 ~' K* x' U" C/ [8 f' \5 r
tmp_df = pd.DataFrame(tmp)
* `5 ?! l$ \& z E if model == train: $ Z) l* s% S a' A% {0 Y
tmp_df.columns = [ID, lat, lon, speed, direction, time, type] 6 R) ?% Q7 Z; m' I9 X7 L- U- _; k# r
else: 1 @& e, c: I$ j% N" d! X
tmp_df[type] = unknown $ s+ p9 s8 ^; k ^+ K
tmp_df.columns = [ID, lat, lon, speed, direction, time, type] ( {6 v2 e3 G8 w5 k; A9 }# }
tmp_df[lat] = tmp_df[lat].astype(float)
. u, O. R% \" x tmp_df[lon] = tmp_df[lon].astype(float) ; D* ~% r) l! d1 n
tmp_df[speed] = tmp_df[speed].astype(float)
; c, L$ ^* i' U+ F4 Q$ V* c tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本
' @5 u" a( `* H- D return tmp_df 0 V$ H n, w A1 b$ \5 C
# 平面坐标转经纬度,供初赛数据使用
* I( N, q# a% B% M6 \! n0 W% P # 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud
. n6 L6 w( N8 ~. G _; Q! }7 R1 F" E def transform_xy2lonlat(df):
" H! A, n( V6 \( Q2 h# m9 _# l x = df[lat].values
5 X/ s' J4 M* m7 Y, f$ V' y' n y = df[lon].values 1 J: n: m' A, J1 M/ A
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 ) ! D( g+ g! V1 H
df[lon], df[lat] = p(y, x, inverse=True)
7 v1 w5 N# J5 i8 Y) B return df 3 }% M: }9 e6 _ s S, s0 L- g
#修改数据的时间格式 6 l) c' T% X2 r& y9 s C q9 H0 N
def reformat_strtime(time_str=None, START_YEAR="2019"): ; U+ `, n: n# h. l# a5 R' _+ P
"""Reformat the strtime with the form 08 14 to START_YEAR-08-14 """ 2 y7 a1 p9 {# |0 y M$ m, C
time_str_split = time_str.split(" ")
8 z8 B# A2 I$ B/ u) a2 E time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4]
7 L4 X, H; R' ? time_str_reformat = time_str_reformat + " " + time_str_split[1] $ j. \4 n- G3 ~1 a
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S) . G4 l; ~- N! y9 Z1 _/ V9 }
return time_str_reformat ( G2 e, h* V; n; N
#计算两个点的距离 & R/ {0 h1 O: f4 d0 M1 t
def haversine_np(lon1, lat1, lon2, lat2): 0 g% ?: g9 O1 Z, B
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
) C# k8 p" T' o( Z. c9 n dlon = lon2 - lon1
\, r$ K" L3 L6 G! Y; F dlat = lat2 - lat1 7 {( G% w7 L. b; C
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
( _% N* X1 N* p' a; _5 P c = 2 * np.arcsin(np.sqrt(a)) 5 } o/ K4 c- }0 T% E
km = 6367 * c
+ d, R* O% V$ a. c; ?) \- c return km * 1000
4 g9 ]8 p, o7 y& y' i2 V' Q def compute_traj_diff_time_distance(traj=None):
0 F- K: P/ C1 S+ ^ """Compute the sampling time and the coordinate distance.""" 5 S! t5 \& o: x3 f2 o8 t
# 计算时间的差值
* {* C" d; e0 M& o time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[ : K. h3 ]4 ^+ @' I, q" G* \6 q
"time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60
4 G7 g1 O, ]0 z9 s. S # 计算坐标之间的距离 0 E# |- d0 ^+ J5 u4 U1 u
dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0 - x; t# ?( ]4 j$ `
traj["lat"].values[1:], # lat_0 ! x4 H$ \) x" [. L! F
traj["lon"].values[:-1], # lon_1
# S0 Z* [ a4 j, t traj["lat"].values[:-1] # lat_1
! }% I) q2 ?) G- n/ W ) 4 M% i8 |3 B) {8 b
# 填充第一个值
6 t0 V/ I& Y$ P m% L time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()
& ~3 Z" f: ~$ R N$ d dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
9 i k1 C$ J) o traj.loc[list(traj.index),time_array] = time_diff_array
8 x: h! h) ?0 ^* H4 O traj.loc[list(traj.index),dist_array] = dist_diff_array ( ~: C& k1 q& |2 J
return traj * o2 b: `2 Y8 N4 J6 p3 s
#对轨迹进行异常点的剔除
& P3 H- j( A" D1 X def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23, 1 q0 K2 J n3 @4 v
time_interval_maximum=200,
; v" N0 z* e( t* y/ F2 W coord_speed_maximum=700): 8 O0 N! i5 { x/ @+ r
"""Assign the anomaly points in traj to np.nan."""
# t5 q5 M4 \7 a2 t& U( A ?( E3 C7 f def thigma_data(data_y,n): 5 x' z F: z) U' B8 K+ X
data_x =[i for i in range(len(data_y))]
! t, k3 A8 j; W ymean = np.mean(data_y) / E! e! |5 _) I7 ]
ystd = np.std(data_y)
7 R( t& v/ q5 Y v threshold1 = ymean - n * ystd
3 {% c! t8 c( m) A. y threshold2 = ymean + n * ystd - P$ m6 N+ Q! l
judge=[]
, J( Z+ E) Z: P- U6 D9 Q for data in data_y: , @" W- \# u0 ~* y* Y& |2 W- [
if (data < threshold1)|(data> threshold2):
# v0 ^6 t# Y9 z. b1 M judge.append(True)
% C# [0 ]# f% g' V/ U$ `/ p& Q' K else: $ @9 O x' W% ^6 T
judge.append(False)
9 A1 \! U! R7 h' J; S! n1 Z' q% E" v6 q return judge 3 O4 v# E+ d0 R( J6 U5 J$ k2 h1 H
# Step 1: The speed anomaly repairing
: q6 {* W( k1 {9 R4 F/ Y is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) : E) I& P/ Z- [; B
traj["speed"][is_speed_anomaly] = np.nan / V8 a& D' |, A4 H: {
# Step 2: 根据距离和时间计算速度
0 w! Q; a' H! ~! X% G3 G is_anomaly = np.array([False] * len(traj)) 8 Z0 {0 f5 J: Z
traj["coord_speed"] = traj["dist_array"] / traj["time_array"] ' `, @$ Q# v H, u
# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点 + g0 j) c8 G' E
is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) 3 A4 t/ Y1 K2 R/ g' g
is_anomaly = is_anomaly | is_anomaly_tmp 1 T+ j, x7 n$ b/ [1 \- H$ Z- u
is_anomaly.index=traj.index 8 n y; U0 G" ]7 Z) ~
# Condition 2: 轨迹点的3-sigma异常处理 2 A8 ?+ a- n- ^8 W: S% J
traj = traj[~is_anomaly].reset_index(drop=True) . D5 M, v( E- X
is_anomaly = np.array([False] * len(traj)) * F: Z$ x8 |' A% X' N. P( W6 V& Q
if len(traj) != 0: 3 @9 B* R- Q) c; M- _5 g
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean() $ @7 r4 q7 O1 P' i% k
lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean() 3 j2 ?; S: T( \7 l y
lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std # V8 `& c- J( O
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std
6 D$ }8 | g* c; r" | is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) 4 I0 ?& Z0 c4 y
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
) M/ m4 r5 \7 \ traj = traj[~is_anomaly].reset_index(drop=True) 6 b9 R. J5 B% E9 M+ h
return traj, [len(is_speed_anomaly) - len(traj)] 4 T) o& t8 w/ B" j
df=get_data(rC:\Users\admin\hy_round1_train_20200102,train)
L2 t, S' {& N$ m #对轨迹进行异常点剔除,对nan值进行线性插值
" z# p! j) I7 S: B- P ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
% R& l0 n; ^$ |: I4 A DF_NEW=[]
3 a6 m0 B( w6 O. v Anomaly_count=[]
2 z! @2 T [" b& X for ID in tqdm(ID_list): 8 B% \; a; w/ r) J# E: g2 v6 [0 J
df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) 6 L) P9 H9 x8 P* N7 C. E, d
df_new,count=assign_traj_anomaly_points_nan(df_id) 1 n# [0 A; z0 X
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
0 |2 J1 \6 Z. g4 I, y df_new = df_new.fillna(method="bfill")
( w0 d- L7 i4 [& Q: h- z1 s8 |) ` df_new = df_new.fillna(method="ffill") 7 M" j# x* K$ c. Y' G
df_new["speed"] = df_new["speed"].clip(0, 23) 5 Z7 W1 ~6 g$ y, u3 B
Anomaly_count.append(count)#统计每个id异常点的数量有多少
2 r, Y' `( X, F7 Q2 ~ DF_NEW.append(df_new)
# {- L/ `5 o) i4 N/ m #将数据写入到pkl格式 2 g% p/ [ o4 v" W* t) K
load_save = Load_Save_Data() 0 d5 N7 o7 ]# J8 H( h
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")
; a- V0 X3 ]! g8 E2 Z6 ^9 W } #### 三类渔船速度和方向可视化 : z' p) o6 S6 d3 _6 C4 Z
# 把训练集的所有数据,根据类别存放到不同的数据文件中
% {( ?" @% f% S6 `( Q def get_diff_data(): + S+ W* A/ O8 T# \$ a; R( a
Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
8 T5 D1 ?4 W0 K1 R8 w- u with open(Path,"rb") as f: h" o: A' S6 J
total_data = pickle.load(f)
, N$ S( d3 C1 ~+ V load_save = Load_Save_Data()
* k" m6 c6 ?1 e2 I( S kind_data = ["刺网","围网","拖网"]
/ A7 v* v# \& [ u9 r' T f6 @ file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"] 5 y/ U/ W* w% | _6 S( i
for i,datax in enumerate(kind_data):
4 D3 G! r* @) p data_type = [data for data in total_data if data["type"].unique()[0] == datax]
+ y9 G1 w6 p" s: `1 E$ C load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i]) + k+ D4 \, l/ T2 A
get_diff_data()
+ i% B% t; _! T, O; c" z/ ^ #对轨迹进行异常点剔除,对nan值进行线性插值 2 C6 y3 W+ L( N% L8 C' b C7 E( @5 G% ^
ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
# }5 P" z4 I/ S- G+ ~: S3 e& W* Z DF_NEW=[]
4 u: n1 U$ H: G6 h1 b Anomaly_count=[] , ^: z; I. L/ [! e) G; C* b) J* Q# n
for ID in tqdm(ID_list): 3 y) w) O" W1 Y" _
df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
! o( j A/ f- l" _ df_new,count=assign_traj_anomaly_points_nan(df_id) 2 U7 O$ h7 w6 B" A. p
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) & @! O8 o8 p" T5 N4 Z
df_new = df_new.fillna(method="bfill") 4 D7 q! ?; t. o5 b" @. u' f1 U
df_new = df_new.fillna(method="ffill") y* I" x& v7 i6 r6 {$ D
df_new["speed"] = df_new["speed"].clip(0, 23)
) b: u5 ^2 a3 a- a Anomaly_count.append(count)#统计每个id异常点的数量有多少
, ~/ K1 R6 g, W DF_NEW.append(df_new)
0 |7 K% i% d& p$ Y2 c # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列 3 x" l# p$ D! @
def visualize_three_traj_speed_direction():
: h. P6 \, Z ? fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15)) & [' n) U' J: X5 C
plt.subplots_adjust(wspace=0.3,hspace=0.3)
6 ^0 y8 X2 Q3 [ # 随机选出刺网的三条轨迹进行可视化
2 J6 G5 U) a: ^* a, E r. s file_types = ["ciwang_data","weiwang_data","tuowang_data"]
( x: t6 i- Q) y3 ?5 x5 K: U speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"]
8 N/ g9 ?5 i" D( t doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"] : _: d7 h7 A6 c8 O" Y' J
colors = [pink, lightblue, lightgreen] + b6 T0 t+ j- |* I8 c* [/ S
for i,file_name in tqdm(enumerate(file_types)): 3 ]9 i4 S m' z8 P2 Y4 E
datax = get_random_one_traj(type=file_name) ' |6 f% O3 w/ \
x_data = datax["速度"].loc[-1:].values
9 N6 l: c0 o G( z/ ^5 l y_data = datax["方向"].loc[-1:].values ; m6 W+ M2 ]* d/ `
axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) / Y& ]+ `9 r& R; Z: B( n2 X I1 R
axes[i][0].grid(alpha=2) 5 h. ^6 O/ {1 K* j% Q- x
axes[i][0].legend(loc="best")
9 ` v( P) X8 J axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) ) Q4 Y' c+ U. Y% I- w: F& f0 [4 _) b
axes[i][1].grid(alpha=2)
! ^/ K& N% S# H. N8 ~( g7 ` axes[i][1].legend(loc="best") , n# H6 ?+ _; ?0 m6 p8 \
plt.show() 7 ^% Z7 M9 G3 f/ {/ m |
visualize_three_traj_speed_direction() * v' x4 K% K$ x- i8 m, P* m
% {+ Y) P4 ]$ Y 作业二:相关性分析。 5 C3 Q# \3 \" Z2 Y4 w
data_train.loc[data_train[type]==刺网,type_id]=1
# I" u8 d' B7 b data_train.loc[data_train[type]==围网,type_id]=2 6 s y3 b& r) t1 i
data_train.loc[data_train[type]==拖网,type_id]=3
' V2 K& I6 m3 h; L f, ax = plt.subplots(figsize=(9, 6))
& P- P! d2 I2 z7 J2 w2 p+ ]5 C ax = sns.heatmap(np.abs(df.corr()),annot=True) 5 D- {# h- D# I$ n2 ?
plt.show()
1 V* v1 N# D2 n+ w `3 R9 f9 N4 e( Y& v9 f3 J
从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
1 V2 Z9 ^5 s" j# W2 q7 |! f1 y8 k' C
0 b3 |' P- p. x) A0 T7 X- R* W0 t
4 [5 t ] w1 }6 o$ Y1 O/ K
1 f% \0 a, E, X |