|
6 F# A9 d; r2 F5 N. k9 W/ c 此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设$ D$ T9 E3 ?1 b$ X6 D: i. ^" b/ H
数据分析的目的: 2 a5 M, L- p! b% c k3 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
# `8 f5 Y9 Z. @8 U8 ^4 I/ x( [ 2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布 ( l% i% a3 Z4 u9 r$ l4 y$ p
三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd
0 Z# q/ o1 \ ]( C import geopandas as gpd
: T( c7 F: x+ T from pyproj import Proj
: {2 C: @( ~ ?2 i7 A% ]1 s from keplergl import KeplerGl 6 a, o1 ]( }$ E* \2 t$ I6 Z' V
from tqdm import tqdm
1 I5 e: O4 `* D9 H) n) | import os
% k3 X8 @- `& K% H- a+ P7 \ import matplotlib.pyplot as plt
3 h8 C. V' S( S import shapely & _; C7 Y d% Q! f4 X$ X
import numpy as np
; V0 z2 U% _/ s3 p; I from datetime import datetime ; N# t2 H# Z' k) D, V$ V+ H, U
import warnings 5 ^ A I5 N. u0 Q0 `
warnings.filterwarnings(ignore)
9 d; \* H# z% c2 W% D# O: j( g plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。
: w! E$ @: ]* V, Z3 L( b plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。 w- Z7 d# d+ j2 _4 N
#获取文件夹中的数据
6 f; Z# W7 Q) @$ K# h0 V4 U def get_data(file_path,model):
/ r/ j7 M$ J7 C+ I8 [ assert model in [train, test], {} Not Support this type of file.format(model)
+ n. C% }& O# {5 t paths = os.listdir(file_path) 4 F C& w' m* g
# print(len(paths))
" a2 A0 V% ]. N# Q( R/ x) N tmp = []
4 w9 J# W% @, O& F8 ] for t in tqdm(range(len(paths))): , u5 B. F* ~' s j, t4 w# q) E4 ~
p = paths[t] 8 Y8 B, G7 C* \; Z0 `" Y% n0 @/ S
with open({}/{}.format(file_path, p), encoding=utf-8) as f: $ b# V5 V8 _9 n5 h1 ^, A
next(f)
0 ~1 Y4 j+ @5 a' F$ g for line in f.readlines(): , g2 j: z5 K! T# W& j4 d6 |( T
tmp.append(line.strip().split(,))
7 |. X4 o5 _4 J% r2 ^ tmp_df = pd.DataFrame(tmp) . z/ B6 G5 j1 O' j! p9 t4 H% L
if model == train:
6 u2 T( U) R. W B$ H tmp_df.columns = [ID, lat, lon, speed, direction, time, type] 7 J1 B& S2 d8 t. ^" v( ~6 t0 I
else: & Q8 ?# U, m( Q8 X+ g
tmp_df[type] = unknown
; f N) ?- {% `1 Z$ B; I$ C% U( Q tmp_df.columns = [ID, lat, lon, speed, direction, time, type] 6 \% F. w, ]# |( |) A" _/ W
tmp_df[lat] = tmp_df[lat].astype(float)
& {9 e1 {# a6 ^; o2 z# E6 l tmp_df[lon] = tmp_df[lon].astype(float) " M$ O9 r% |8 G& f& B
tmp_df[speed] = tmp_df[speed].astype(float) . r9 N" M+ H* Z5 K
tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本
$ A" d9 f- Z6 o return tmp_df
3 A' i) ?( p" ^3 q, u- p # 平面坐标转经纬度,供初赛数据使用
( G; |6 M Y# `/ o5 K8 O" V # 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud + e5 g9 d" \; ^) f
def transform_xy2lonlat(df):
' N* a% P4 g3 `! v& \ x = df[lat].values
" W$ B9 g& ^9 C$ [ y = df[lon].values
" I8 J ~+ g6 X2 Q9 U 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 ) . i4 c# W: }5 J! Z
df[lon], df[lat] = p(y, x, inverse=True)
% t, t C9 U+ ]7 B' I return df
, o+ I: h2 M. s! n6 r/ z& B; y #修改数据的时间格式 + G& @% t, L( K- v) w* X; d" Q
def reformat_strtime(time_str=None, START_YEAR="2019"):
M: }7 n- ?" d* a5 \! D( c9 l' ~ """Reformat the strtime with the form 08 14 to START_YEAR-08-14 """ " B. l, n& J Q
time_str_split = time_str.split(" ")
z6 c5 [6 O5 Y5 i: U1 B4 N: D time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] 7 u! u! n! O5 D3 G3 j" Z
time_str_reformat = time_str_reformat + " " + time_str_split[1]
$ M3 w! S, y6 w; B) Y # time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S)
! D6 [/ L6 [5 l" W return time_str_reformat
6 W* |) G; K: v; Z; m" P$ B- s #计算两个点的距离
. _/ b; O, n1 ~% w: N2 W def haversine_np(lon1, lat1, lon2, lat2): % F7 T: t, R0 h6 m0 T
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) - _) H! [+ u I+ ]
dlon = lon2 - lon1
* n# _6 D8 m% `, p' n* Q dlat = lat2 - lat1 8 S* L1 v3 N+ r8 U- T+ m" Y+ }
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 ! ]* s: K5 y* G6 X4 n$ M
c = 2 * np.arcsin(np.sqrt(a)) ( Z. ~5 x$ q" S3 n+ P/ D0 O& J
km = 6367 * c , b) z5 f! c" k8 c
return km * 1000 , k6 Y4 I, Q, l( `; l: Q0 l/ R7 G* [
def compute_traj_diff_time_distance(traj=None):
' s: |% d8 s9 s/ ^ """Compute the sampling time and the coordinate distance."""
; L5 i! E' i$ |' g' q: b: W # 计算时间的差值 $ c. ^, q* n* E8 W& ~! n) V* \; H
time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[
# `3 o$ R- l+ p/ S( x- Y8 G7 x "time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60
3 D8 Z5 o) s; d e1 m* `/ E # 计算坐标之间的距离 $ z0 j, o" h3 ~' h
dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0
/ z3 v. g0 b5 Y traj["lat"].values[1:], # lat_0 ' m5 L# V3 s: B& j9 A2 r: K6 y+ C
traj["lon"].values[:-1], # lon_1
/ O) _) ~8 a9 [) Q traj["lat"].values[:-1] # lat_1
) h7 h8 z5 V% |: i )
- {3 T& z* `: y1 r: Y* D # 填充第一个值 ) p) y4 s- H# u' @: h: i
time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist() / P D8 K3 b8 s" |3 B" Z
dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist() " U U+ f1 h" A7 l; x! d! t8 y
traj.loc[list(traj.index),time_array] = time_diff_array
K4 N% A: t4 o% r0 b traj.loc[list(traj.index),dist_array] = dist_diff_array
, S6 N0 b; _& x5 ? return traj
8 O* a% \! V V* I4 ] #对轨迹进行异常点的剔除
: q- }/ }: g- L5 |0 o6 L1 b. n def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,
! q4 I3 @8 u4 e6 M7 Q1 i time_interval_maximum=200, & k! w& w: l# z0 k$ w
coord_speed_maximum=700): 3 z, v% Q: L6 g/ M
"""Assign the anomaly points in traj to np.nan.""" % Q; \ f, M: c& R) l8 R& M
def thigma_data(data_y,n):
* \* p6 P; M! S3 C2 l/ G N; G: a data_x =[i for i in range(len(data_y))]
0 k! n; E7 J+ Q; w& N9 R ymean = np.mean(data_y) & U- a, ]3 |+ _/ E @7 X3 R
ystd = np.std(data_y) 0 q |$ A! P$ ?1 |
threshold1 = ymean - n * ystd 0 i, _& l0 ^# H% J8 x' T2 n
threshold2 = ymean + n * ystd
' B: z) c3 n+ r3 K, J* i judge=[]
( C/ m1 [) T! d+ M9 g5 e! g1 ? for data in data_y:
* O! q9 B. r* e ]# Z8 B8 `) o% F; P if (data < threshold1)|(data> threshold2):
. u4 S0 n; h7 [1 Y/ M1 ?& O judge.append(True)
7 W% O% E! B' B {- H7 ^ else: 9 \4 F# `; c+ s- t% G$ a
judge.append(False) # B: n$ }; @3 _0 q8 B, Q
return judge & P; f/ d6 F5 e$ K7 x$ N' _
# Step 1: The speed anomaly repairing 2 _" i. u# @, m. T
is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) ! y& I0 |9 T4 p8 f7 G% T
traj["speed"][is_speed_anomaly] = np.nan
3 C* g+ e/ S5 ?5 ^( O # Step 2: 根据距离和时间计算速度
4 w$ p+ |( H- B1 a2 L1 b; { is_anomaly = np.array([False] * len(traj))
9 p1 ] S' j$ w [! }4 M+ G traj["coord_speed"] = traj["dist_array"] / traj["time_array"]
7 E( b! L: J* h. [" [7 o, A. k, c # Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点
5 V/ g; ^' P/ M8 B is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) - ~. w/ ? i9 S8 s: x4 [
is_anomaly = is_anomaly | is_anomaly_tmp : d, {3 t& b( L/ k: B
is_anomaly.index=traj.index 7 a( b8 @4 A/ j9 N
# Condition 2: 轨迹点的3-sigma异常处理
8 S( c* H E1 x' u2 j, a7 C traj = traj[~is_anomaly].reset_index(drop=True)
' q9 s% N6 m$ Z% _+ u+ ~ is_anomaly = np.array([False] * len(traj)) ) a, @( S, _0 Q
if len(traj) != 0: 3 r2 F$ r1 P# U& s* }
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
+ p, P( ~$ Y6 z/ F2 \1 m lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean() - q- b2 a5 W; W- ?& W. I- {
lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std ; f0 ]% D, {, W2 [
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std
/ F# Q/ k4 q0 q7 ?2 u8 C) d& B is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) + |' R% A$ F7 e2 v+ {/ }9 B% D
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
/ f, ?' l8 r8 n traj = traj[~is_anomaly].reset_index(drop=True) & Q0 r, z1 e0 {6 x+ Q" P* L- v
return traj, [len(is_speed_anomaly) - len(traj)]
5 t7 \; H/ N+ y* N1 F% M7 U/ u df=get_data(rC:\Users\admin\hy_round1_train_20200102,train)
) F( w1 ^1 a% }3 n6 d& ~ [ #对轨迹进行异常点剔除,对nan值进行线性插值
0 ^' ~. q. S" b0 i2 M0 s' c1 ^ ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
9 c+ [; y- }7 O DF_NEW=[] , p6 C* |# v" i4 ^, y3 o! G
Anomaly_count=[] 8 b% J" F1 h2 p" y) R1 h/ D
for ID in tqdm(ID_list):
) F$ A7 i1 w! {9 x j0 y df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
i! A% q5 H- d2 C, \4 i" k df_new,count=assign_traj_anomaly_points_nan(df_id) " e& F/ b8 C0 |
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) 7 U3 U6 v4 S& l' f- N
df_new = df_new.fillna(method="bfill") / \+ |& E1 g5 Q9 Q" C& B; z
df_new = df_new.fillna(method="ffill")
L; q+ N( }5 y2 L U9 x df_new["speed"] = df_new["speed"].clip(0, 23)
4 L! Y: _- h& ? Anomaly_count.append(count)#统计每个id异常点的数量有多少 # y. ]: ` S5 w
DF_NEW.append(df_new) + M/ x) Q( r+ S7 M
#将数据写入到pkl格式
8 e3 _# v$ |% m8 ^5 t: s/ P, g% E( o load_save = Load_Save_Data() , s( C0 W7 {3 X
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")
$ E: ?; w5 `$ m1 f4 } #### 三类渔船速度和方向可视化
" y/ a" f9 M' f0 \2 R # 把训练集的所有数据,根据类别存放到不同的数据文件中 ; e- ^3 p' Y/ M
def get_diff_data():
! T5 _8 g7 N6 h1 ^9 G Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
, K# u$ p1 P2 Z) k, W# x with open(Path,"rb") as f:
2 W D0 F8 r1 r) d! _6 f total_data = pickle.load(f) & M4 `& e+ z% m2 E3 k' v
load_save = Load_Save_Data() " x6 |& X6 m0 j' h
kind_data = ["刺网","围网","拖网"] * w4 y1 U/ G2 ]2 d, R n# h" b) D
file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"]
( n2 u1 p( C9 w5 R for i,datax in enumerate(kind_data):
9 u/ Y, L( V4 J# E* P% D0 X data_type = [data for data in total_data if data["type"].unique()[0] == datax]
+ X" t7 @7 ?7 b+ \& y- } load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i]) + {+ \' P7 |) y: A8 [$ r' b4 |0 G
get_diff_data() 1 t( r! S$ K' M0 ^7 o
#对轨迹进行异常点剔除,对nan值进行线性插值 4 q2 R& k' u8 r f- X- i
ID_list=list(pd.DataFrame(df[ID].value_counts()).index) * M- ^4 B% P D# d' p: }
DF_NEW=[]
4 g$ p. a3 p5 o9 y! V$ D9 g Anomaly_count=[] / P2 R% l( ~5 o
for ID in tqdm(ID_list):
: n7 h5 ^+ ^. M3 [2 Y% W4 R df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) % @' t; Q$ a% c$ I
df_new,count=assign_traj_anomaly_points_nan(df_id)
e8 h) B+ t M1 \2 P" ^4 U4 w. [ df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) 0 ]3 Q! M8 L2 ~) F( g9 q
df_new = df_new.fillna(method="bfill")
/ ~1 l* b' n1 d* D df_new = df_new.fillna(method="ffill")
7 B* i! f2 N1 h6 o1 p df_new["speed"] = df_new["speed"].clip(0, 23)
6 J0 g" @' p' x! T2 L( N Anomaly_count.append(count)#统计每个id异常点的数量有多少 @; a2 f+ O2 f2 r! t# |
DF_NEW.append(df_new)
, [1 k! F2 d) i/ c, ~3 n# x # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列
: Y0 |$ m- M0 l def visualize_three_traj_speed_direction(): 1 q- @9 r( [+ u! J* J& t0 I
fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15)) ) z3 ^& Z. D; ~
plt.subplots_adjust(wspace=0.3,hspace=0.3)
V( b2 U5 i% c. b # 随机选出刺网的三条轨迹进行可视化 / E8 ~* y* q" M8 h8 y) F
file_types = ["ciwang_data","weiwang_data","tuowang_data"] " n, U' Y7 s( i, d8 C
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"]
. z' }7 j4 H) u$ Y" b1 Y4 N doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"]
& w( W) i \- ` v2 \( e colors = [pink, lightblue, lightgreen]
4 G$ |3 V* d5 _- ~$ R! O% { for i,file_name in tqdm(enumerate(file_types)): 1 h# B/ r7 s& ^7 l( Q" \
datax = get_random_one_traj(type=file_name) 1 \+ t& i# V5 l4 D7 |' C) ?4 }
x_data = datax["速度"].loc[-1:].values - x0 [! ?7 ?1 t( g
y_data = datax["方向"].loc[-1:].values , A6 T! t, {, r- R' r2 |
axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) . `: H- g* I# `+ M) ]
axes[i][0].grid(alpha=2)
2 l# a" q; b/ o3 y* O4 N* `* z, [ axes[i][0].legend(loc="best") $ z) S& L' D* a
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i])
4 Q. s2 c5 K3 U) N% o axes[i][1].grid(alpha=2) # \6 M3 _4 p7 D0 M2 I$ i
axes[i][1].legend(loc="best") $ s+ D" E$ R7 [* N
plt.show()
0 @2 b3 D. N, f: x visualize_three_traj_speed_direction()
$ ^# _* h; p8 }9 |$ a' t* Y 3 \! S- G% ? \0 u1 r, x/ p
作业二:相关性分析。
[; o0 g% Y/ T% L# X3 z4 l data_train.loc[data_train[type]==刺网,type_id]=1 F- G' E9 j' r+ k! U- u, F
data_train.loc[data_train[type]==围网,type_id]=2
/ q5 V+ f+ Y5 e9 l: v- o3 ~ data_train.loc[data_train[type]==拖网,type_id]=3 , _1 U# t, _2 Y9 s& J
f, ax = plt.subplots(figsize=(9, 6))
+ k3 q: l9 x: X* i ax = sns.heatmap(np.abs(df.corr()),annot=True)
9 X/ b2 c1 X6 H L plt.show()
2 c4 U) l1 B6 y5 p. ] % Z% e, q; W4 I. c
从图中可以清楚看到,经纬度和速度跟类型相关性比较大。 3 l! T0 P( _$ d$ W
- W @9 c% V4 H* j
% t, U$ G% |' F. B& E$ n* V' U9 O. M. h) y' y
' `0 F7 v }9 @3 e
|