|
( R$ L) E5 ]; J8 L7 N
此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设% }6 K2 {! c8 k9 I& A6 a) D
数据分析的目的:
: x+ U4 s2 E) l3 F+ O6 g9 x 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' b9 w! f0 x a# g
2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布 $ U- m2 W, D% Y. }
三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd 7 F5 s2 Q P3 `0 c
import geopandas as gpd
/ ~* M, {$ _- Q& l7 v& [ from pyproj import Proj ' t ^/ D/ {! {& @) I
from keplergl import KeplerGl
4 m4 M6 U. n/ b" ^ from tqdm import tqdm
0 I/ x+ a# d; v4 ?8 Y import os 5 a( k" M t" x3 n9 a/ b
import matplotlib.pyplot as plt $ N w) v" v* e: o5 `. C; |8 W
import shapely
9 Q' S- W. O0 e& h; v8 q3 [3 E' R) s import numpy as np
! N w5 j0 h0 K3 X/ ? from datetime import datetime $ G1 H& Y' g* J( u5 U# J
import warnings
- S6 ^! y5 L0 i- c" v) a warnings.filterwarnings(ignore) - Y0 k4 J6 ^, T, u. {
plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。
& i4 X# O. f* k! s1 y0 w plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。 ! T4 e2 R1 A1 C, B: ^
#获取文件夹中的数据
0 f# X8 \" G0 V def get_data(file_path,model): ; g7 D8 L+ s' }
assert model in [train, test], {} Not Support this type of file.format(model) 7 \" Z4 T+ E* s
paths = os.listdir(file_path) # G9 V$ y1 N" ^7 Z- L. r' F
# print(len(paths))
/ r+ ?) z6 y- j& ?! O7 Y& \7 Q tmp = [] - s1 ^# E& \. q5 D" Q1 {$ I
for t in tqdm(range(len(paths))): " y5 Z4 m9 ~! i' P) L3 h( i
p = paths[t]
* ?# N9 D0 r) D with open({}/{}.format(file_path, p), encoding=utf-8) as f:
3 C2 Y3 u, s; c( _ next(f) + S7 `# {# ?) R8 r7 V
for line in f.readlines(): " A4 g5 S$ D7 c3 G/ Y9 x `
tmp.append(line.strip().split(,)) $ W7 L5 ^. G1 a+ ]/ ?2 |
tmp_df = pd.DataFrame(tmp)
6 u5 v7 k7 f# m" n if model == train: 9 ^2 H8 C4 q" H; F _/ e# B
tmp_df.columns = [ID, lat, lon, speed, direction, time, type] " x- z/ Q- j2 V: o3 U/ o; E
else: ( x- Q4 @- z$ q* l2 x7 t! p
tmp_df[type] = unknown
% f. G3 F/ ?- K tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
6 y) B) Z% `3 }$ i! M: ?# l tmp_df[lat] = tmp_df[lat].astype(float)
6 W& `9 y6 j( m4 ?2 c% \ tmp_df[lon] = tmp_df[lon].astype(float) 9 G6 I) V" Z6 E8 W, w9 Z1 x- J
tmp_df[speed] = tmp_df[speed].astype(float)
" l* B: q- o3 P( Z' W tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本 . j8 @/ R \ x }: e
return tmp_df
' l- M4 K4 W2 E8 C" B& P # 平面坐标转经纬度,供初赛数据使用
6 d- X' T0 r. o2 J # 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud # Y& C( j+ s: k' l, w
def transform_xy2lonlat(df):
3 B9 A8 n' T! K! q" L% I$ b x = df[lat].values 6 [# c/ T j0 }
y = df[lon].values 4 M: j' m/ W! z
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 )
( |6 W8 C, v2 s. T6 e3 n, Y+ p: t df[lon], df[lat] = p(y, x, inverse=True) , q# X2 R/ J6 P" W& \& ]( i
return df
7 O5 L, c: n% [* {" r. u #修改数据的时间格式 $ ^$ J$ r9 c- ~% N! G) e; X
def reformat_strtime(time_str=None, START_YEAR="2019"): 7 c, ]% W8 v& c& s, l: w# t* s
"""Reformat the strtime with the form 08 14 to START_YEAR-08-14 """ 9 ]0 ^/ Y& `' d( J- y) J$ Y
time_str_split = time_str.split(" ")
; r; n0 Z6 |. @4 d: a: `" N time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4]
2 ^/ ?" n9 r) {; b/ N/ D% \ time_str_reformat = time_str_reformat + " " + time_str_split[1] ) R" e, u9 T! [8 p
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S) ' A) x. ~* e/ J" M& x4 u) G" `
return time_str_reformat 1 @8 u: Q$ W8 {5 H& B
#计算两个点的距离 ) B2 v0 P" k" b% _
def haversine_np(lon1, lat1, lon2, lat2):
& T7 {; p% {) H! l6 J lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
- {/ t2 ]5 f* Q& u m dlon = lon2 - lon1 $ w5 p7 r3 n$ e& Q
dlat = lat2 - lat1
+ e; ?( |* j7 k* n9 W2 f& `* V a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
Y ~% E' ?7 i c = 2 * np.arcsin(np.sqrt(a)) 0 F; ` t! z$ N1 ~& Y, B S! F6 P
km = 6367 * c ' F' D/ x( ]! ]1 ]
return km * 1000 8 o* h+ Z6 D, u% w ^
def compute_traj_diff_time_distance(traj=None): h% U& H! l2 F! l
"""Compute the sampling time and the coordinate distance."""
7 x" p5 [5 [3 \. H/ |- L! R # 计算时间的差值 4 X" {2 v, l( E0 F0 N& A
time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[ . |) x, n `# ]
"time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60
' s/ S1 r9 o. F6 i' l9 T # 计算坐标之间的距离 - m0 p/ s3 Z& L3 @
dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0
0 }+ k' z" L# y) Q traj["lat"].values[1:], # lat_0
: |( \5 p, G) k0 H5 z5 k* u) n w traj["lon"].values[:-1], # lon_1 6 o( B3 P3 G) {* [+ a5 E, E7 y" f. j+ {
traj["lat"].values[:-1] # lat_1 6 O9 m" ~- @: \1 O3 j( K
) / \) C' j# u7 Q5 n& [
# 填充第一个值
+ V, {- d! W* o5 u) s+ [ time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist() * y6 K& M8 Y$ t
dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
8 m3 Q! q: I8 T traj.loc[list(traj.index),time_array] = time_diff_array 8 P) K+ Q6 K3 T& o T: \
traj.loc[list(traj.index),dist_array] = dist_diff_array - K2 Q; s. T* ^+ b$ o7 l
return traj
- `3 r9 V/ @! p g6 }) X# l( H #对轨迹进行异常点的剔除
! n$ i& E; R4 q) P0 B. V def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23, ; h! Z% Y1 O4 m& [- w) b5 T
time_interval_maximum=200, : K' r: [7 p* @$ v P, @
coord_speed_maximum=700): ' n5 x- c- o, I3 n3 y- w
"""Assign the anomaly points in traj to np.nan."""
% {% }6 ]2 o& B. \ def thigma_data(data_y,n):
0 V% [6 U" _! B% b data_x =[i for i in range(len(data_y))] : J5 b9 S+ D; ]
ymean = np.mean(data_y)
* x9 @; B! n E. K$ g, Z1 F ystd = np.std(data_y)
2 W* ~ e" v: ] threshold1 = ymean - n * ystd " Q2 u9 K/ I- Q
threshold2 = ymean + n * ystd
7 T; J3 }1 p3 R# X judge=[] . r. o/ h+ a" Q" ]" B$ F' f
for data in data_y:
' ?1 J! I. D1 ?/ |0 p if (data < threshold1)|(data> threshold2):
! X' p$ Z6 L6 Y7 V judge.append(True) $ N( D6 S/ e* d# o A. U7 h
else:
$ }; j0 P4 K$ Z! j( S1 j' d* D( ?2 X judge.append(False)
0 r# D1 a( V6 U return judge 4 @" R) c: u7 h( G1 [4 z: W( ]
# Step 1: The speed anomaly repairing ) {: y, L k; R1 J
is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) 0 W7 K' i, B! @
traj["speed"][is_speed_anomaly] = np.nan
, m8 ~2 d+ J8 W # Step 2: 根据距离和时间计算速度 2 y" `. q1 E/ ?; Y: r
is_anomaly = np.array([False] * len(traj))
' [. A- c, i" z5 W, g F8 Z traj["coord_speed"] = traj["dist_array"] / traj["time_array"]
" K) B7 D* H. r) V$ ]# U D # Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点 " H9 u/ r+ `0 G$ L: B8 C2 n
is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) 1 q. Q) S, B% p I
is_anomaly = is_anomaly | is_anomaly_tmp
, h/ V# O2 R7 z* V* W) g5 N: m' K is_anomaly.index=traj.index 5 X# I, V2 b1 Y+ D) |( }
# Condition 2: 轨迹点的3-sigma异常处理 : T6 r4 |$ [, Q2 e
traj = traj[~is_anomaly].reset_index(drop=True)
( Q; G: Z) n4 N8 A is_anomaly = np.array([False] * len(traj)) $ q& p4 H6 i' f* z3 y7 j+ s7 l
if len(traj) != 0:
( |, ]+ N9 s# V' Q+ t* Y, t9 v lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
" k) O' e9 c6 X; L6 [. g; [4 l lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean() - S0 @9 C; v G
lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std ) B' h. x; \; `) x& J* t
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std
! x+ y, T5 l0 Q8 B is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low))
% p) j3 i' A$ q0 [- Z is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
' f4 e* h2 i; q traj = traj[~is_anomaly].reset_index(drop=True)
! ], c2 R" U4 h2 Q# X' Y" z return traj, [len(is_speed_anomaly) - len(traj)] 0 A; v3 P) f9 g! O' v
df=get_data(rC:\Users\admin\hy_round1_train_20200102,train)
! S; j/ Z! y, Z* I0 X) X #对轨迹进行异常点剔除,对nan值进行线性插值
( f9 {9 G! d+ {0 _ ID_list=list(pd.DataFrame(df[ID].value_counts()).index) . B* Y' Q( j# L' W9 s
DF_NEW=[]
- j/ d0 Z9 j: t2 L. U0 c$ L Anomaly_count=[]
% O+ q" L" k6 J2 G+ h5 O: S, a for ID in tqdm(ID_list): W; j Q2 E* l; @0 [
df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
4 \! r! t2 \2 J5 }9 M" E. O, W df_new,count=assign_traj_anomaly_points_nan(df_id)
0 X" {$ ]: f: C( X df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) ( F$ \# [+ |3 x* v
df_new = df_new.fillna(method="bfill") , @ t. W, Y- y$ Q1 I$ r
df_new = df_new.fillna(method="ffill") 1 l3 c. l7 C8 x# V$ S0 P! K0 m
df_new["speed"] = df_new["speed"].clip(0, 23) 3 T0 O: H1 E# R3 ?) [7 N& I
Anomaly_count.append(count)#统计每个id异常点的数量有多少
* P" m! N, F& C3 m DF_NEW.append(df_new)
( [% N3 J: L7 O+ `1 Y #将数据写入到pkl格式
, q! R5 @" x7 d$ I, O+ c: N$ Z' h load_save = Load_Save_Data() 9 e( I# m2 k2 I* F' m
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")
' r4 \; @5 Q0 t2 \ #### 三类渔船速度和方向可视化 1 @) A% n! Y# b* y+ n) L# F0 K
# 把训练集的所有数据,根据类别存放到不同的数据文件中 . l" B5 T8 m% z6 @/ {# B# k
def get_diff_data(): 1 e0 G; G/ q! p6 V: o1 U
Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl" : R: B5 o" V3 @
with open(Path,"rb") as f:
$ K# O" i* I. \( H! f" m total_data = pickle.load(f)
! ]% f( N2 Y$ Q load_save = Load_Save_Data() ' m6 I! ]1 P" x) K6 ]
kind_data = ["刺网","围网","拖网"] 5 w) T* H! S4 |0 [" x( ]
file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"] * E2 g w; a5 |& [: z% l
for i,datax in enumerate(kind_data): # `0 z& W/ g8 E
data_type = [data for data in total_data if data["type"].unique()[0] == datax] 7 y& h, D7 K" W' H; j' u
load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
/ T& ?- C- U; ^$ { get_diff_data()
6 Y S6 z/ p: y* \5 a #对轨迹进行异常点剔除,对nan值进行线性插值
) G7 |0 G7 K) t# P) e/ r" N+ T ID_list=list(pd.DataFrame(df[ID].value_counts()).index) ! D" g/ Z |' W/ P B$ X
DF_NEW=[] + X% [7 t* \* t: k2 ~: P" Z
Anomaly_count=[] ' \4 z2 b6 B! h6 N7 F
for ID in tqdm(ID_list): / t( ? h8 Q- [) n" k+ j
df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
6 v! b4 x5 S E. d8 s df_new,count=assign_traj_anomaly_points_nan(df_id) - T7 U# E4 ~9 x) G
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) 6 S C( G! T. U. U& e; q
df_new = df_new.fillna(method="bfill") 0 Z' G6 z- K9 t' m: a6 G
df_new = df_new.fillna(method="ffill")
\6 F2 W) ~/ I( A" e6 j4 B df_new["speed"] = df_new["speed"].clip(0, 23)
5 | y0 v5 g V/ i- @4 u3 E6 w6 E Anomaly_count.append(count)#统计每个id异常点的数量有多少 6 ?+ e7 O) T, @6 P
DF_NEW.append(df_new)
; S% {1 i& I7 i2 g: O # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列
: P& a' T; Z% N def visualize_three_traj_speed_direction(): ; f2 q7 B6 K3 r
fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15))
. S2 o, Z O1 s/ ]# O( p6 J plt.subplots_adjust(wspace=0.3,hspace=0.3) ; Z" S9 T0 r+ E! z8 Y4 w
# 随机选出刺网的三条轨迹进行可视化 " E9 K7 n3 E+ i/ q
file_types = ["ciwang_data","weiwang_data","tuowang_data"] # t8 ]! Q& O3 p; }3 @" ^% I
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] 6 u' X' ^# D8 }2 y$ R. M8 Q
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"]
8 j% e$ b2 k+ G% e2 ^1 P$ D colors = [pink, lightblue, lightgreen]
9 T' T, T$ @0 F5 z for i,file_name in tqdm(enumerate(file_types)): % S" |) @3 R: ]6 p/ ` b, L
datax = get_random_one_traj(type=file_name)
' r- z* ~3 ^# A& ~ x_data = datax["速度"].loc[-1:].values
& T) O7 V3 U4 E y_data = datax["方向"].loc[-1:].values
& n5 o* m" O7 o. c$ k) H4 y+ k axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i])
2 B3 a" I) l; f$ I) I- @ axes[i][0].grid(alpha=2)
: v( [+ r# N, n& r: M7 t8 ~ axes[i][0].legend(loc="best")
6 ^; ]* u/ c7 ^( c axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) " d |! j' S5 r; ?
axes[i][1].grid(alpha=2)
- @, G0 u k8 P) ~8 {; }( e& [. x axes[i][1].legend(loc="best") / n* y5 P8 ?* n# H
plt.show() - ~- [/ O. F b7 J8 ?* }: R
visualize_three_traj_speed_direction() . o; v4 D9 x- \& R: O8 r
5 k0 n6 |1 U' c! f: V- W2 G1 r 作业二:相关性分析。
1 l9 x4 ~. E& _$ g, C+ P data_train.loc[data_train[type]==刺网,type_id]=1
$ P& Q- D$ X9 {/ _$ { data_train.loc[data_train[type]==围网,type_id]=2
" M% u. j+ Q) s) R6 T7 o data_train.loc[data_train[type]==拖网,type_id]=3
* l6 ^2 _; z* |0 Y1 {5 k* P f, ax = plt.subplots(figsize=(9, 6))
9 W9 l2 O8 t1 ?) Y ax = sns.heatmap(np.abs(df.corr()),annot=True)
3 O# p. Q6 h3 u& o plt.show()
) h. T. [/ M( `' k$ a& B6 \) J. I$ A) { Q W& N9 {$ p( x! e
从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
# E' t: n, s& o" H7 ^
, Y8 {/ @ K4 d7 S$ {% M8 f
# j5 V3 o$ W4 g! l+ b
$ ^7 ]- R, Q) A( u" h, z0 P w- p0 @/ l( s: e9 n3 e+ k2 T& D- S
|