|
- ?7 _' W# _2 j% ]
此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设
7 t; p9 E& \! D 数据分析的目的: : I0 I+ T9 V/ [- k! b7 V7 Z
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
: L5 r5 k8 p9 u9 ^+ _ 2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布
' M" r5 Q4 \9 C 三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd
5 b0 ]+ p6 P, e w" x import geopandas as gpd
1 X0 R7 O. S% N- S from pyproj import Proj
$ h& [' L" d3 E, A. w" ~3 S# y from keplergl import KeplerGl
+ S/ S0 s- U1 O/ ` u from tqdm import tqdm
: D. j, N/ @' d R$ v% [' q import os 0 A: {4 G& l u. b
import matplotlib.pyplot as plt , o& w5 w+ ~- R- a: l
import shapely " x7 `- X e6 ^5 c2 k; [* v. z
import numpy as np
/ R0 i* x0 ]+ `( h from datetime import datetime
) I0 m: r' M& Y- S/ n4 \ import warnings 7 z3 _: H( C5 \* R `
warnings.filterwarnings(ignore)
2 o6 C7 P n, J5 A3 c plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。 ; X6 j6 {3 i5 O7 G
plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。 , o/ d8 ?7 _0 j/ g
#获取文件夹中的数据
- A s# O6 Z$ d def get_data(file_path,model): * G+ [! w, m* i
assert model in [train, test], {} Not Support this type of file.format(model) " @6 V, I6 P5 ]) @, a: f8 g
paths = os.listdir(file_path) 7 j$ H" X2 E8 D. [7 S4 G" B* ~
# print(len(paths)) ; G+ W$ v) f2 B1 j2 _. Y$ q% t$ p! K
tmp = [] ) F* c- b& k! C" q* B* ~6 g0 d
for t in tqdm(range(len(paths))): 8 f `2 S9 J' k0 B0 D9 y" B& Q
p = paths[t]
Q* |" |2 V0 i+ B) F with open({}/{}.format(file_path, p), encoding=utf-8) as f: 8 J8 g! P1 C* }3 r; k9 V' C
next(f)
% I" t0 T$ B, d$ q for line in f.readlines():
, r( t6 R& r- n) y; t tmp.append(line.strip().split(,)) 0 x$ R& y9 B; e
tmp_df = pd.DataFrame(tmp)
% b2 A+ i+ D5 d. e7 A% v3 x if model == train:
. A) F5 O7 }9 m& e. D- u tmp_df.columns = [ID, lat, lon, speed, direction, time, type] 4 \& L+ J/ H* b c& p
else:
9 \/ N0 y' p. g0 K/ _2 R- B tmp_df[type] = unknown ; w# G/ Y3 ?. I" X0 Q
tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
/ M9 c- y8 r9 K- s( O tmp_df[lat] = tmp_df[lat].astype(float)
( v ?% I/ |; d6 s% G; V7 q/ \ tmp_df[lon] = tmp_df[lon].astype(float)
: T' t; F: ^7 D, l, k9 T3 d tmp_df[speed] = tmp_df[speed].astype(float)
$ X7 a, Q+ _! z+ V# B tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本 . L, l. `: E% w) Q% ]
return tmp_df
: s/ j" ~2 `# n( X; h2 e( w # 平面坐标转经纬度,供初赛数据使用 * {' s7 }' s1 v5 u8 L& n& s+ @
# 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud . d3 \) _6 Y0 f( }2 x) g% f
def transform_xy2lonlat(df):
& A" c- `! T. G, k# K x = df[lat].values 3 n) b0 {- j' h- j
y = df[lon].values ! `. J; s$ F2 T$ v
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 )
9 f7 P/ ?( Q P df[lon], df[lat] = p(y, x, inverse=True)
5 _7 d5 m2 T1 K' D7 _ return df + @* y2 Y# p/ Z z$ n
#修改数据的时间格式 ) x, m2 a: q5 y* V
def reformat_strtime(time_str=None, START_YEAR="2019"): - K1 A& T, v" m- t, v
"""Reformat the strtime with the form 08 14 to START_YEAR-08-14 """
F) u3 m* ?; w1 l time_str_split = time_str.split(" ")
& k. u3 ? i9 U7 j2 W2 r' t5 W7 m time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] 3 |! C H2 P( \% V5 o
time_str_reformat = time_str_reformat + " " + time_str_split[1]
1 @9 z8 \ Z, J {2 Y( g& `* ` # time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S) . E6 ?- q2 D' B3 u0 ~6 a1 G
return time_str_reformat
/ }2 F! m& \5 f. j8 z+ R #计算两个点的距离 % a: e, b( R9 m
def haversine_np(lon1, lat1, lon2, lat2): 4 h7 z- Y7 K' j! j& {& N
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) * N# P4 z n* c t+ k% P' E, l3 r
dlon = lon2 - lon1 , q. ]( r. O' z& D. p6 W7 L
dlat = lat2 - lat1 ) g: @- k9 p. y! T* s; { K, j7 ~
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 + B, B5 ^" l9 B
c = 2 * np.arcsin(np.sqrt(a)) & U; @8 y8 B+ u; |
km = 6367 * c . b7 P7 m5 [; W( a1 W
return km * 1000
" E% A+ @) Z }/ ?# s! A4 f I* N4 ^5 N def compute_traj_diff_time_distance(traj=None):
$ V1 p' t: G& Z i """Compute the sampling time and the coordinate distance."""
7 I5 Q: Q. j- w- K2 D3 Q # 计算时间的差值 5 L; g) Y* ?1 {0 T
time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[ 0 o" v; d E4 h, L& x
"time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60
4 k* q3 ]$ ~% O0 L # 计算坐标之间的距离
' S# W( S! H6 d s2 S3 h dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0
x1 T* B: w d1 ?; w, ^ traj["lat"].values[1:], # lat_0 / q8 x( ~0 f: B$ [
traj["lon"].values[:-1], # lon_1
8 c8 k" J; a7 _8 j) x traj["lat"].values[:-1] # lat_1 8 d7 z5 {; M; z# W8 h3 u' b; h
)
8 o7 a7 S1 @. ?7 K # 填充第一个值 ' s3 G# S9 J+ m
time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()
3 G, B1 i. B5 ?$ q dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist() : P- x* t# C9 K+ d/ R( @
traj.loc[list(traj.index),time_array] = time_diff_array - b0 q/ j% N m) S, Z6 D$ ~5 N
traj.loc[list(traj.index),dist_array] = dist_diff_array 9 q6 T/ _3 k* R* f: g
return traj . \4 u C: p' o3 j; f) T
#对轨迹进行异常点的剔除 - U, Q% @- {7 `' o
def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,
: ?* T. s& H! _! n9 O- H5 a time_interval_maximum=200, # Q; k% W- j# [/ C8 p7 W6 y0 \8 q' B; x
coord_speed_maximum=700):
. O/ P! \! B: U """Assign the anomaly points in traj to np.nan."""
4 X# ]9 K5 \3 W9 @1 h2 H1 B def thigma_data(data_y,n):
# T+ b' [3 X2 X( v) [ data_x =[i for i in range(len(data_y))]
% C) A" g% e* [$ v2 k4 @ ymean = np.mean(data_y) & Z, Q3 ~" y( v8 w9 m$ a8 N+ q C
ystd = np.std(data_y) ' C7 N) X# d' y3 y( S6 `- q4 d
threshold1 = ymean - n * ystd
8 W/ F3 l/ A6 q" v: K& G9 p( D threshold2 = ymean + n * ystd
, v, d" l. {/ p8 x0 M `( R$ f, o! H judge=[]
9 Q' J$ k! T, j9 y$ g for data in data_y:
6 Z; F# O. i1 Q. m- [( ~ n# c if (data < threshold1)|(data> threshold2): 9 L8 a. u1 f4 {# S* w
judge.append(True) 9 }" T2 c! K. {# P
else:
" c! {% \+ m- N; k7 t& f* M judge.append(False) ' o1 [$ t: I+ V5 f3 ]: i
return judge
# e! `) K* F& {" m # Step 1: The speed anomaly repairing
% I! V4 x4 P* R( C& g is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) $ {2 C" k# m3 a i1 Q; @2 t1 A
traj["speed"][is_speed_anomaly] = np.nan
# a7 X/ Q8 d- B: v# a+ G+ u# p1 g # Step 2: 根据距离和时间计算速度 2 b2 u4 E0 R6 s# p) |- D
is_anomaly = np.array([False] * len(traj)) % e2 J! G. |- e5 u4 K& x
traj["coord_speed"] = traj["dist_array"] / traj["time_array"] & P6 t. U" B' C y7 q# h
# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点 : p: e- F8 |4 ]: O# l! `3 G
is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3))
' f0 r' E/ @9 ]" S" _ is_anomaly = is_anomaly | is_anomaly_tmp % L" D8 y8 P$ S) ]! r, D/ {- r, I$ j
is_anomaly.index=traj.index # O T9 V$ ?, m+ `- O( y8 x
# Condition 2: 轨迹点的3-sigma异常处理 % M9 x$ ]6 M% i) j9 h9 l9 q
traj = traj[~is_anomaly].reset_index(drop=True) 3 n% K1 _9 b: O: D7 {8 q4 o# I
is_anomaly = np.array([False] * len(traj))
) U$ S) S4 _; y8 L0 @ if len(traj) != 0:
4 s8 d8 s& P2 f" _ lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
1 W) }6 F7 e m. I! P! Q- Y lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean() 6 b5 Y: @& `- Z/ t* C$ ]6 e5 S
lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std 0 c) I& [' L. q/ z" R
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std / R# z% X, b. f& c# h% [1 g, Z) h
is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low))
2 u) e% E* w8 G( `! ]! ` is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low)) 0 Z5 v& I/ {& A6 t! g
traj = traj[~is_anomaly].reset_index(drop=True)
% X: W. [2 V9 A; r return traj, [len(is_speed_anomaly) - len(traj)] 3 |! G1 t; m% T
df=get_data(rC:\Users\admin\hy_round1_train_20200102,train) , Q" I1 h8 T# R, j8 K. Q
#对轨迹进行异常点剔除,对nan值进行线性插值 * }* N6 Z# d; n0 t8 R
ID_list=list(pd.DataFrame(df[ID].value_counts()).index) & Z$ x8 E# ]" O9 s
DF_NEW=[] 8 H1 g5 F5 d/ b0 c0 }
Anomaly_count=[]
4 \4 w0 v% [% |6 W% d for ID in tqdm(ID_list):
+ W" [4 t8 @! z( V df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) 0 v2 U9 @( F" G" z/ ?7 t8 Y* C4 f. {
df_new,count=assign_traj_anomaly_points_nan(df_id)
' P& @1 M8 ]$ B1 T' S3 o df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
! F4 ` G, ~9 b2 M df_new = df_new.fillna(method="bfill")
" V: [/ I g" ~8 [, k6 o0 `. w df_new = df_new.fillna(method="ffill") 2 |( ?$ ~7 p; w
df_new["speed"] = df_new["speed"].clip(0, 23) 8 v. I# E7 N- L( }- t& d
Anomaly_count.append(count)#统计每个id异常点的数量有多少 " U8 N2 Z- z1 e& l" r1 C% Q
DF_NEW.append(df_new)
" P, ?- m D- C+ Y1 k, v! c #将数据写入到pkl格式
' @! k8 Y2 O% `3 N: U4 X& _' Q load_save = Load_Save_Data()
9 t1 d: d, j+ d" y0 T load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl") " J+ k+ S! ^- b1 N
#### 三类渔船速度和方向可视化
+ Y1 {, y9 b' y # 把训练集的所有数据,根据类别存放到不同的数据文件中
3 B2 ?+ W- J8 w" p' z3 h i def get_diff_data(): " j, {+ N' B- C/ U2 k
Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
0 k3 K4 J) C8 ?, W& ~$ F+ m5 _/ ^4 ~ with open(Path,"rb") as f: 8 m: t6 m: A6 \' _; U
total_data = pickle.load(f)
j j7 w# N6 `/ e# K* e( G load_save = Load_Save_Data() 4 d+ T1 G* J" v
kind_data = ["刺网","围网","拖网"] & }! [9 d7 r/ n$ B6 s, e4 S
file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"]
( X7 C- t5 C2 m for i,datax in enumerate(kind_data):
+ z: Y. q$ t e8 _$ j# `* k b data_type = [data for data in total_data if data["type"].unique()[0] == datax] ( X* h) `; ? f. O% n
load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
$ x3 W8 I1 v$ J2 z4 j' x7 Q get_diff_data() 4 c F+ p5 J6 }9 l
#对轨迹进行异常点剔除,对nan值进行线性插值 ' z: k4 C/ O; ]. i8 E
ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
1 Q# j; I! ~0 @1 J DF_NEW=[] ! N) | Q1 C, D$ f; v# v) D
Anomaly_count=[]
* F: @- O4 c* a for ID in tqdm(ID_list):
$ A; q0 N3 `, J( o3 \/ o df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
- Q+ {& r/ ?* d& f' m df_new,count=assign_traj_anomaly_points_nan(df_id)
# ?- ~* r& S& T0 u; Z df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) 9 l. d' k& v" e% ], m
df_new = df_new.fillna(method="bfill")
0 l& z# J" o% V2 F+ P* c0 F df_new = df_new.fillna(method="ffill")
u( i! c- {5 R. A$ Y; ?; F df_new["speed"] = df_new["speed"].clip(0, 23) . l S: G: }! t' E' J* r' J/ Q
Anomaly_count.append(count)#统计每个id异常点的数量有多少
$ g2 ?) F+ r7 e0 M: K DF_NEW.append(df_new) " j* t. z/ v! @3 Y. |7 Z% @
# 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列 % z1 D0 [3 o! ^
def visualize_three_traj_speed_direction(): + f3 p4 F0 y4 J, Z+ h, W7 Z' t: O
fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15)) 3 \4 G# M# \5 }1 a' @3 y8 f" c
plt.subplots_adjust(wspace=0.3,hspace=0.3)
7 ^! k1 l2 c9 G$ P& M # 随机选出刺网的三条轨迹进行可视化 6 ^: U+ s2 I: t/ _
file_types = ["ciwang_data","weiwang_data","tuowang_data"] . W# w( i6 l+ V9 F3 v
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] 3 z. c4 o7 O( H8 r5 h' d
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"]
/ b8 j' t H. T4 H m colors = [pink, lightblue, lightgreen] ' Z8 V/ e( x7 s( H) q% J
for i,file_name in tqdm(enumerate(file_types)): ; _ Q2 y7 d' W+ r5 i; s
datax = get_random_one_traj(type=file_name)
- o9 b) x, I p' S2 l x_data = datax["速度"].loc[-1:].values . h3 ]) E8 \/ ~2 g* T# u
y_data = datax["方向"].loc[-1:].values 9 \6 r& v# h* n
axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i])
1 R+ @1 w, `4 D2 f: Y& U6 l1 m: p axes[i][0].grid(alpha=2) 5 I5 c1 ~, ?' S; e* X+ ]$ H
axes[i][0].legend(loc="best") / j4 E9 t+ n: R9 n1 f0 b
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i])
8 \$ B: r* r' t' L6 S axes[i][1].grid(alpha=2) . N3 D2 D; ]7 R
axes[i][1].legend(loc="best") ; ~0 l9 X4 A$ O" N
plt.show() * |" ~+ ~5 r: Q; s
visualize_three_traj_speed_direction() + k: ?/ l: f0 A/ X$ _) Z" x
! O2 J- {$ }) s5 F+ x
作业二:相关性分析。
6 w7 u! P3 t) D2 t. `, }/ w data_train.loc[data_train[type]==刺网,type_id]=1
0 h! I' S8 F% R+ x4 e* o% X' ] data_train.loc[data_train[type]==围网,type_id]=2 . z s! n! Q s$ \# ]# O, ]
data_train.loc[data_train[type]==拖网,type_id]=3 0 Q$ A3 _% r x9 x; P/ P$ H& Z
f, ax = plt.subplots(figsize=(9, 6))
9 j! B5 R! t! ~ K+ s$ A: ? ax = sns.heatmap(np.abs(df.corr()),annot=True)
) i+ Q) c" h6 `# |8 g0 d& h plt.show()
8 W0 S5 R/ w# p6 ]1 A
$ _6 l9 _9 z: P/ R- w5 c8 ] 从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
! H. @* Z+ R8 i) g8 y& x( P; a a6 t* |; x
, x1 y; z: u' V% `5 z' w& C/ B' J' q6 R6 V- H9 b( @
! j0 p. _& _" t3 Z; M
|