|
* ~1 N+ o9 t) O2 A( c1 t
此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设& E4 e' l5 r3 u2 F+ ?! M3 z' `
数据分析的目的:
T7 } R6 \* T2 N3 \ 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
9 v" ~1 X0 n4 o/ V' x- j' T 2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布 + e6 H; x p' |7 Z( k2 i. d
三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd 5 U. Z7 N* Q- }( o N2 l0 |
import geopandas as gpd
# f8 m8 R. N. {- A2 @" V from pyproj import Proj
1 o! s6 x Y* }% j' L* n$ o+ R$ V from keplergl import KeplerGl
. N# z2 m Y/ R s from tqdm import tqdm ' j; v+ c0 V& U1 M) b
import os 1 O# f& Z( |9 i0 O% I' e8 }
import matplotlib.pyplot as plt $ W7 m+ }# M4 d0 P
import shapely
2 B# r! q9 M! `' [1 s import numpy as np
, Y2 v+ ^8 R7 H/ ^% C: @ from datetime import datetime
q8 `. }* [) o t: G import warnings
1 i8 [ M' u7 a- D; y: k warnings.filterwarnings(ignore) 6 y4 k- B$ H0 O5 s; |. o8 R
plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。 ! [: z7 e6 C. y6 O# c- H; W! d7 Q
plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。
; v8 ]0 ^' F1 [/ t( `# M #获取文件夹中的数据
4 l. }9 W+ V* }. ]& _& {. z/ A; S def get_data(file_path,model): ! \7 s/ \ o" c6 ~7 s0 u; |3 U
assert model in [train, test], {} Not Support this type of file.format(model)
# E1 H7 r7 @7 g paths = os.listdir(file_path)
' r( C6 ]+ z: ]; z # print(len(paths))
1 x& M7 i+ H; `4 Q1 Z tmp = [] 3 P1 R. L O, s' ^* c
for t in tqdm(range(len(paths))): 6 w' U7 K" v5 ]
p = paths[t] : y4 P6 _8 g$ J/ I
with open({}/{}.format(file_path, p), encoding=utf-8) as f:
% L4 P& v# G/ e$ ~4 ?" O next(f) 0 M5 Q0 J7 A3 \' @$ l
for line in f.readlines(): $ o$ }' z F' e5 F, J G
tmp.append(line.strip().split(,)) . [7 `) H2 G" }/ n5 _" I& J {5 x, W
tmp_df = pd.DataFrame(tmp) ! l. W* L9 {/ _, a; n
if model == train: a& ^ x+ B, l$ w3 F5 w% e
tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
[0 e5 Q9 E; E7 T5 F$ O else:
1 P7 k" G( [1 p& B. b" |! X tmp_df[type] = unknown
v" R: f7 M" M8 Y tmp_df.columns = [ID, lat, lon, speed, direction, time, type] 1 a: @+ @. F2 q6 E$ m
tmp_df[lat] = tmp_df[lat].astype(float) 2 c6 P: O" `& Z6 G# c
tmp_df[lon] = tmp_df[lon].astype(float) / w8 ]2 q, H* U* o: w& m! \
tmp_df[speed] = tmp_df[speed].astype(float) $ g0 W7 ]1 }7 F( C* ?1 P
tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本 1 m; H6 x+ Q/ a6 ~ q' k
return tmp_df D7 l7 A. d8 ?, x7 B
# 平面坐标转经纬度,供初赛数据使用
@0 Y" k( g( B' D # 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud , c# s$ Y# x/ \+ Y8 i7 ^2 P9 L8 S
def transform_xy2lonlat(df):
8 O% @& H! s) G6 c x = df[lat].values 3 i% N; d$ i) G! J& i- z
y = df[lon].values
% E8 B, A* @. j. O( Q2 T& u1 v9 F 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 )
; X! c3 W* }3 ]8 v df[lon], df[lat] = p(y, x, inverse=True)
+ V: C, P4 e. b return df ! ?. N4 e9 j, ~% ], g' u( t- N
#修改数据的时间格式
$ q2 H6 i5 q' Z* v8 t! M9 R8 h def reformat_strtime(time_str=None, START_YEAR="2019"):
! |. J# A/ @" O; @ """Reformat the strtime with the form 08 14 to START_YEAR-08-14 """
- t: ~& ^& i4 ]/ ?6 B* W time_str_split = time_str.split(" ")
: {5 h, M+ b6 } F' x time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4]
5 i0 w2 M, j3 \5 [ time_str_reformat = time_str_reformat + " " + time_str_split[1] ) E5 `: U& I( ^4 T
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S)
; n) y( G' S$ j/ V, W return time_str_reformat 1 h! E, N' p; S+ ?9 Z" q
#计算两个点的距离
, E" p$ |6 r$ Q k @ def haversine_np(lon1, lat1, lon2, lat2): , f& n2 L" S4 W" W
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
4 g6 \ _3 ?9 _: h1 S3 v dlon = lon2 - lon1 . s p2 l4 y C- z
dlat = lat2 - lat1 % w* J; b5 ^: g' C. G' ~6 \! d
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 - t3 P: z# H6 ^5 x$ x
c = 2 * np.arcsin(np.sqrt(a)) 4 |! d5 X) r% ]+ Q) s; c# Q
km = 6367 * c
4 I9 k2 ]5 D) `! | return km * 1000 # E( f3 g# R2 T+ ^/ D3 r
def compute_traj_diff_time_distance(traj=None): * e1 k/ `3 @, B- e8 N# a. Z7 R
"""Compute the sampling time and the coordinate distance.""" ; {+ N! }7 U9 [. a7 Y# n ?8 C7 E% ]
# 计算时间的差值
+ r( `/ P/ D0 _( J; ] time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[
' B2 P5 N; R) c$ z% _2 D& N: Q- w0 \ "time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60 & y' m- E% _6 H0 ]: L
# 计算坐标之间的距离 % l" H$ A- O: R6 R
dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0 ) F7 K. I. n$ E" `/ r
traj["lat"].values[1:], # lat_0
4 q9 i& N. {6 ~" _# _+ P traj["lon"].values[:-1], # lon_1
r, c, C% |) Z traj["lat"].values[:-1] # lat_1
6 s) @3 z: s- Z4 ]- k' B2 b: N )
$ J" L( }: g# z: n" i # 填充第一个值
; i* B" M5 z; r( C- e. E' P, L time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist() 1 n. `- g) m6 y1 S9 J
dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
7 E1 \7 w) v. ~7 ~8 `/ \2 d. H traj.loc[list(traj.index),time_array] = time_diff_array
- s* n* n8 L) q; n, d traj.loc[list(traj.index),dist_array] = dist_diff_array
2 }1 E3 ?& S9 t, t. _3 H$ E return traj ' g( u, ?2 J( W9 X- F
#对轨迹进行异常点的剔除 9 s6 {+ Y7 H( i- p5 J+ e
def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,
4 H$ ^' u9 S; a+ o# s3 U, O time_interval_maximum=200,
% @7 }5 [* l; Z1 d/ Y coord_speed_maximum=700): 7 Z* n2 ^% D2 y3 G4 p6 A
"""Assign the anomaly points in traj to np.nan."""
/ E* d- Q$ W8 G" I2 ^1 J/ v- w$ e' Q def thigma_data(data_y,n):
7 \0 ~$ |2 N. T; ~! ~ a5 | data_x =[i for i in range(len(data_y))]
- y! b) s; C) C" Q ymean = np.mean(data_y) 2 p T. o! f; {0 `/ v0 g1 Z
ystd = np.std(data_y)
6 Y* p- i& z5 Z threshold1 = ymean - n * ystd
% t& H8 P9 m* S; E4 h* R: v# Z2 e threshold2 = ymean + n * ystd
* y2 H) L- g0 _9 i7 I* Q judge=[] & x A* h& c' Y( x9 [
for data in data_y: W/ a+ ~/ K5 n) T3 ~: M0 u
if (data < threshold1)|(data> threshold2):
& L# w4 g* l: t$ A judge.append(True)
( p( J! l3 N: u# y4 g' q else: 3 D) Z4 K5 Q+ G+ J
judge.append(False) & t7 N$ e4 {0 x) j, f& y
return judge $ h& q+ {( |, ~+ U l7 I
# Step 1: The speed anomaly repairing
, M3 f8 M: z9 M% z, ?$ V* ^! S is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) 0 q$ J ~. E( N3 v
traj["speed"][is_speed_anomaly] = np.nan
$ w* w% V# i2 h# Y' T+ }. J; @ # Step 2: 根据距离和时间计算速度 5 j4 ]/ C( l/ a3 X
is_anomaly = np.array([False] * len(traj))
; N* O8 Q2 v( `6 W traj["coord_speed"] = traj["dist_array"] / traj["time_array"] 2 j' f- n5 Y" k1 s
# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点
' r- x% d( J, k: d0 c' B5 | is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) : |1 _) O; R& |$ c; ^+ Z0 a1 c
is_anomaly = is_anomaly | is_anomaly_tmp
/ F# G# ^6 ]/ z1 d/ A4 O, J' F' ` is_anomaly.index=traj.index & K9 z/ p" i2 E
# Condition 2: 轨迹点的3-sigma异常处理 0 j# o" z1 G% y
traj = traj[~is_anomaly].reset_index(drop=True) 1 Q8 }+ {7 X. E
is_anomaly = np.array([False] * len(traj))
8 l" K$ T3 _$ F8 s' i/ M, } if len(traj) != 0: 0 c1 c4 h% @) J Q6 C
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
/ v, Q U6 |; y' J" z( j) k lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean()
% e# J( u9 v" z0 {* i5 \ lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std
6 k7 w1 R* N: y" }2 n6 B0 \4 R* ~ lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std : e. Y( R! l! ]: U
is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) ( L$ Z" F2 n" a- H0 q
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
6 C$ B+ H% O+ ?* y! a9 K traj = traj[~is_anomaly].reset_index(drop=True) # x, S$ U% [7 ^' q x! ]
return traj, [len(is_speed_anomaly) - len(traj)] $ s3 Z: [1 S5 U! @: |! s: h
df=get_data(rC:\Users\admin\hy_round1_train_20200102,train)
! Y, c$ S1 v | #对轨迹进行异常点剔除,对nan值进行线性插值
0 Y. A9 O- m3 e4 o/ i5 h7 m ID_list=list(pd.DataFrame(df[ID].value_counts()).index) & s x4 p$ t6 N2 U
DF_NEW=[]
! ]6 E$ E* t6 m- P Anomaly_count=[]
8 \! ]6 H9 c% |8 {3 a( a* l for ID in tqdm(ID_list):
' `2 z! j- c) G, Y df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) - f# m) Y& p6 B( w, U
df_new,count=assign_traj_anomaly_points_nan(df_id)
J& {4 P1 P7 O9 V df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
: h$ Q i# b! l% Z df_new = df_new.fillna(method="bfill") : D/ H2 g4 k+ j6 ^# ?$ x. h
df_new = df_new.fillna(method="ffill") i" \ T( ]- p1 X3 T! V
df_new["speed"] = df_new["speed"].clip(0, 23) ! e: W! T, `0 e& E8 M. s
Anomaly_count.append(count)#统计每个id异常点的数量有多少 4 i3 H8 `, \7 X# I( p3 R: a
DF_NEW.append(df_new) 7 j+ S4 j6 `+ Z. @5 E
#将数据写入到pkl格式 1 Y1 }, z' h9 L, D) A2 N
load_save = Load_Save_Data() 3 Y/ {7 d" O" J4 _0 ]
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")
) l& b' @8 Y" ?" C6 ~, ? #### 三类渔船速度和方向可视化 # R3 }' m9 K' t+ A# q* v
# 把训练集的所有数据,根据类别存放到不同的数据文件中 8 h8 r1 H& Z6 X: H: s
def get_diff_data():
. w, w; H7 r7 W: J* i Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
( y; T: J {3 {7 x with open(Path,"rb") as f: 0 n/ q, h3 c6 t
total_data = pickle.load(f) ! X1 C* K* l X& u% J% a
load_save = Load_Save_Data()
) `8 u" H8 Z' y) ` kind_data = ["刺网","围网","拖网"] . K5 X6 N$ `* s8 k* O% q
file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"] 7 R% b% `4 w) U' k! B
for i,datax in enumerate(kind_data):
. i F K8 ~ p, {4 \. J data_type = [data for data in total_data if data["type"].unique()[0] == datax]
; w2 A! v5 W7 q9 {9 v load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i]) ( b6 }8 h: F1 o3 P I6 D
get_diff_data() " C6 G6 i5 K; S5 N. [
#对轨迹进行异常点剔除,对nan值进行线性插值
/ w) v9 s& C$ b3 y9 c D ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
- a4 b' _1 d% u$ L) b4 Y# X DF_NEW=[]
8 P: _+ j. T0 }$ E) Q% x/ Y Anomaly_count=[]
G$ \9 |& ]5 b8 k) X1 z9 T for ID in tqdm(ID_list):
2 c: r4 @- o, z8 c0 @* _ df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
+ J- I0 X! J" V9 W6 r, E: R df_new,count=assign_traj_anomaly_points_nan(df_id)
0 M( i- G: Z7 M+ w0 l df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
V4 J% R, W/ f% r5 Y( t df_new = df_new.fillna(method="bfill")
) m. o, c' D! W, E# o* I df_new = df_new.fillna(method="ffill")
& f4 I9 I6 e& b! w# @ C' E9 z df_new["speed"] = df_new["speed"].clip(0, 23)
! ~# s' K# e+ B3 d( ~) C7 M9 G X8 t Anomaly_count.append(count)#统计每个id异常点的数量有多少 L7 M# c/ z, Y4 m
DF_NEW.append(df_new) * f# |/ k- a8 T- ^; q5 l& C3 P+ h- d
# 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列 6 u# @! m& g+ H1 s, S* n9 ?
def visualize_three_traj_speed_direction(): 9 b5 P* C9 O( G- {: V
fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15)) 2 a. h/ Z4 }1 S7 E# H5 @
plt.subplots_adjust(wspace=0.3,hspace=0.3)
l6 w. K" m$ {) Q4 J # 随机选出刺网的三条轨迹进行可视化
6 L2 I! e* Q* U6 Y1 T( G file_types = ["ciwang_data","weiwang_data","tuowang_data"] % W3 Z+ ]) X6 }4 {" _' `! Q
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"]
; i" N. ~+ x |0 S% l' @7 W# A+ @ doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"] ; l6 B C9 l, R
colors = [pink, lightblue, lightgreen] ' b4 Q4 q4 Z3 q: X4 W
for i,file_name in tqdm(enumerate(file_types)): 6 X3 d' G6 m; R* F. P( F+ U' A
datax = get_random_one_traj(type=file_name)
5 F+ p6 c, l6 H3 h x_data = datax["速度"].loc[-1:].values
7 K- E% W; d* ? y_data = datax["方向"].loc[-1:].values ) Q! Y( A+ k4 K8 J" e% P- y( `
axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i]) 2 u5 ~4 @: `1 F8 K
axes[i][0].grid(alpha=2)
" U( M) _! P, |3 |* w8 u+ ` axes[i][0].legend(loc="best")
* _# B8 U% l% Z" S% E axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i])
6 N8 q5 s1 l4 S5 F |( \ axes[i][1].grid(alpha=2) , f# K v6 p' O* h( x& F
axes[i][1].legend(loc="best") K `; [7 v8 i" n
plt.show() ! p; o3 R/ k% P2 b! l6 p
visualize_three_traj_speed_direction()
8 }! u* e7 r! d2 o9 V5 L
% c( L9 g- S8 a5 D 作业二:相关性分析。 0 w" z% ?2 c, T* N' S# y- c
data_train.loc[data_train[type]==刺网,type_id]=1
! D7 X. W$ k" n2 R8 i7 M data_train.loc[data_train[type]==围网,type_id]=2
6 n+ p) [" @/ D: M" y" } data_train.loc[data_train[type]==拖网,type_id]=3 ! m: |( t8 @, q' \
f, ax = plt.subplots(figsize=(9, 6))
, a7 e0 [; L& } X$ m3 k0 L; s ax = sns.heatmap(np.abs(df.corr()),annot=True)
4 l1 d* C1 ~/ a plt.show() $ Y7 D+ s! d) w- ~: g" Z
9 c& W1 H0 q4 v2 }- Y) m G" z% _+ ^ |
从图中可以清楚看到,经纬度和速度跟类型相关性比较大。 1 q _, p: x* ^: k
, C5 y- x, G; S/ t0 v1 {2 v- X
, ]1 |. l; L; S( d: ^: E5 ~) y4 _( @, k8 a
2 j0 R. F6 Z& ?; O. |2 w1 a" y
|