|
2 h/ a; }' K& H# A7 d) X 此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设
5 z( P3 Q. F/ r' Q G 数据分析的目的: $ h: C# C4 O( }. C7 t9 u
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 ! Q9 u. o( x/ x$ l
2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布
4 k1 n0 \% E& _ 三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd 1 a w6 ^$ {5 n% y7 k7 H
import geopandas as gpd
7 ? _; [* @' c' q9 B; i from pyproj import Proj B& }; Q+ T) W7 m% H9 {4 G( e5 }/ A
from keplergl import KeplerGl
8 ]7 }" \, l- a; g2 F" ~3 ? from tqdm import tqdm * M9 R" z* H+ |* A. B( ]
import os
5 T! K0 m$ u: a% `2 ~2 z, C# o- x import matplotlib.pyplot as plt
6 h1 q( [2 w) t* D/ f" O. r- M import shapely : p' v! ?# O3 X7 T; }1 |
import numpy as np : \$ Y" j5 C3 @+ \
from datetime import datetime
; ^) L+ ]: q* X import warnings
9 g7 N2 h, N4 @; v, r! L4 P warnings.filterwarnings(ignore) * X, i4 }- e; b4 r& t8 D. l: Q
plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。 : ]4 |8 ^- }% V/ O! F
plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。 3 l! e8 \- b' o0 s$ i5 ]& p1 ]
#获取文件夹中的数据
* l6 s% w+ A. p, w1 o+ e0 Q e def get_data(file_path,model):
4 P) w6 F3 S8 x assert model in [train, test], {} Not Support this type of file.format(model)
. N4 F2 u6 }+ {/ K; ~ paths = os.listdir(file_path) " @' Q- T3 i) C4 e" J1 _; S {% i
# print(len(paths))
1 O# S3 J, L# ^; f3 W" e0 l tmp = [] 6 K) ~+ S! t" L3 T! i
for t in tqdm(range(len(paths))):
. i- k& j8 q3 ` p = paths[t]
+ h2 W3 T6 C/ ^ with open({}/{}.format(file_path, p), encoding=utf-8) as f: . G; [. h- f- }3 `/ g, w
next(f)
4 f( S% ~& g$ x for line in f.readlines():
* \0 a9 v; D/ H6 l- S tmp.append(line.strip().split(,))
1 H7 A+ p) e% \6 y tmp_df = pd.DataFrame(tmp)
+ l" i) A8 u, V if model == train:
0 g; H# n6 g: L `" D* {, e/ L tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
Z, O$ Z! R9 {& t( `4 R else:
( b: I) n! I7 g/ P' U }2 t. k tmp_df[type] = unknown
4 a9 L8 \3 T! ^ tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
! k4 G6 D; t, g! V1 y tmp_df[lat] = tmp_df[lat].astype(float) , i6 R7 Z+ y6 L
tmp_df[lon] = tmp_df[lon].astype(float) 2 i. A8 h: l% W8 p+ g
tmp_df[speed] = tmp_df[speed].astype(float)
. Q7 l @ l: t3 F2 y2 q9 R tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本 . S; j2 @1 k: O; D8 |, Z
return tmp_df
, F6 d5 {$ u& M' F2 \5 W/ N' Z # 平面坐标转经纬度,供初赛数据使用
7 U3 {4 S" J+ _8 t( ?$ |! W # 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud ) J1 k5 Q- p9 u9 f! E! b
def transform_xy2lonlat(df): 9 ] H6 p0 X6 H3 p7 `8 a' w
x = df[lat].values
+ d' Q5 L4 Q! z) a y = df[lon].values
5 O1 B7 e& ~- {0 r- K g7 I 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 ) 0 H* k5 z* D# F3 o* j: m2 t1 p4 u1 x' K
df[lon], df[lat] = p(y, x, inverse=True) 3 N' g! p. U4 O
return df
' {) _. G3 ~- \% |: ]9 T, H #修改数据的时间格式 . {( ~: }' {( G; ^ w
def reformat_strtime(time_str=None, START_YEAR="2019"):
2 l# M: I2 q P$ b """Reformat the strtime with the form 08 14 to START_YEAR-08-14 """
$ j2 U$ o- r& N) O+ w time_str_split = time_str.split(" ") 8 m* m3 Z2 a1 l7 d0 M
time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] 4 G/ y& x) v5 f' g, Z. o6 W! y
time_str_reformat = time_str_reformat + " " + time_str_split[1] % n& a) @( A) j
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S)
e$ \$ s4 E/ ^3 C" k return time_str_reformat ! }/ Y6 B, m/ n0 I W) t" W6 I7 b
#计算两个点的距离 : h9 ?: T1 L/ b+ a# M
def haversine_np(lon1, lat1, lon2, lat2): ' S5 q) c' s4 S1 F0 i
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
6 m( p4 P, S! q5 C! O dlon = lon2 - lon1
( A& u( D: m; m$ m) G. b/ r" K dlat = lat2 - lat1 0 I$ S6 S4 ] O3 l5 k
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 * j9 M+ M* } y0 }5 i$ {* e
c = 2 * np.arcsin(np.sqrt(a))
8 V4 p& J% @3 N$ _+ A km = 6367 * c " m- ~& _; s& v+ S& w
return km * 1000 3 ]* J- B, }4 r7 y
def compute_traj_diff_time_distance(traj=None):
1 a V9 @+ l8 T$ V """Compute the sampling time and the coordinate distance.""" " O5 u; i- X$ o! e9 }9 x
# 计算时间的差值 / b: M2 m2 f8 _3 p
time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[ - G4 U) \- ?( A2 s% _5 ?
"time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60 8 l2 x0 V0 w* @& h
# 计算坐标之间的距离
4 b( ?% T5 ]5 {, U! S$ D2 x$ | dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0
% S" {( g- @/ R R4 i a traj["lat"].values[1:], # lat_0
) i" o1 l* w/ z/ s* g" `* e traj["lon"].values[:-1], # lon_1
0 e. |+ J; g" N traj["lat"].values[:-1] # lat_1
% ?& x& g2 ^" E4 u) B ) ) M. U) B/ V: `6 [3 y" a
# 填充第一个值 5 f+ q" n9 _# c L* U
time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist() 9 ?! C9 U @, D3 `. S( d$ s
dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
& V! i) s! A) r7 p, T ] traj.loc[list(traj.index),time_array] = time_diff_array
# J4 a* [1 S3 R+ I' u# m traj.loc[list(traj.index),dist_array] = dist_diff_array 7 p; X4 L3 M' {
return traj
5 j0 @# u6 p, u+ S1 f } ] #对轨迹进行异常点的剔除
) y- ?) r7 h: z8 G3 W! ~. w) I! X def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,
% r% F+ }# o- {. u+ P" A) k time_interval_maximum=200,
) f B% b N: m9 c5 u! v$ w coord_speed_maximum=700): & o2 W$ z# Q( B* k5 @" }4 g. f
"""Assign the anomaly points in traj to np.nan."""
+ L# W- M" P/ l( C$ f; O0 p4 @ def thigma_data(data_y,n): 1 d$ a) H: p0 w/ y/ Z$ T
data_x =[i for i in range(len(data_y))] 3 E! e: b# p& ~6 r
ymean = np.mean(data_y) / \) L) K+ t4 z- O2 }
ystd = np.std(data_y) # y# M5 G) V; e: g
threshold1 = ymean - n * ystd
! S+ |6 _. F- v threshold2 = ymean + n * ystd
- Q+ \0 H U/ ]6 `6 F2 o! z6 { judge=[] 7 ]6 h4 N) l* l4 }
for data in data_y:
( w9 u" J3 C, | if (data < threshold1)|(data> threshold2): ( h0 D% o" H: A% E
judge.append(True) & c$ F% w; f$ w/ L
else: 5 Z! R' X! N: [7 r8 r; P: S
judge.append(False) + Q. q Z# @# j# ?
return judge / g* Q) y. A+ ^! c/ R; ]
# Step 1: The speed anomaly repairing ~/ J3 m' d! R
is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0) " x% @' C& |; a7 _ z
traj["speed"][is_speed_anomaly] = np.nan
2 `- s+ Z; z$ m5 W/ X: n* Q: _ # Step 2: 根据距离和时间计算速度
9 T! a! H2 S% H! X7 l is_anomaly = np.array([False] * len(traj))
; v& V' m! v' k* }: h: ~' w# p6 K traj["coord_speed"] = traj["dist_array"] / traj["time_array"]
- i; K1 H9 G1 c8 U7 { [ # Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点
6 d S1 F) B4 I) R3 g is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) ' A1 M- Q6 y4 ~" e' v& j7 R5 i
is_anomaly = is_anomaly | is_anomaly_tmp # `- }! W- j2 l* q8 ^1 W$ D
is_anomaly.index=traj.index
$ y9 v& D! Z8 t # Condition 2: 轨迹点的3-sigma异常处理
8 a) O$ z n) v- m M traj = traj[~is_anomaly].reset_index(drop=True)
" D, }, r7 h* W# I3 N I. b* y is_anomaly = np.array([False] * len(traj))
* L! N# V, V% Y if len(traj) != 0:
9 y- X8 d% o" R, f9 {$ p( v lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
$ m6 C: I/ K9 ]- ^ lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean()
: [7 B e$ s" ?2 {/ b& e lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std
$ M/ p# D Y1 y lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std
, {% s- Q4 i2 E( ? is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) ) J5 _, h3 u( S! k; c
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
2 {+ o h- ^# z9 Z ` traj = traj[~is_anomaly].reset_index(drop=True) % y7 L) P& B; n1 e
return traj, [len(is_speed_anomaly) - len(traj)]
5 H2 d0 J6 Q6 |" `/ ~* S' q df=get_data(rC:\Users\admin\hy_round1_train_20200102,train) 4 k) ^) Z. ?8 H4 l* j
#对轨迹进行异常点剔除,对nan值进行线性插值 " Y1 J7 ^8 J6 m( I* L) Z* o$ _
ID_list=list(pd.DataFrame(df[ID].value_counts()).index) : b/ ~& K1 W' X% r8 O8 t
DF_NEW=[] ) Q) R* n( u1 Z% | N" o
Anomaly_count=[] 9 J6 a9 k% s, m3 ]" I; ?' @, y
for ID in tqdm(ID_list):
) g0 D+ I7 ~6 A df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
+ J1 w. f4 |- M df_new,count=assign_traj_anomaly_points_nan(df_id) 0 }7 c% |/ i) r- T: Q
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) ; M3 d* E: b3 N0 \5 Z
df_new = df_new.fillna(method="bfill") 3 T9 T# u+ P3 S8 p- L
df_new = df_new.fillna(method="ffill")
6 Z) k. c' S% B7 { df_new["speed"] = df_new["speed"].clip(0, 23)
0 F( @: Y0 L9 t) M Anomaly_count.append(count)#统计每个id异常点的数量有多少
2 F1 i/ [/ N9 ^ DF_NEW.append(df_new)
9 l. n. |5 m, U #将数据写入到pkl格式
# m, M- K P$ j# Z5 [ load_save = Load_Save_Data()
, S, l. O+ z, G) ~+ z8 Y load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")
+ s3 h) j3 ?0 j4 _3 H- f# S #### 三类渔船速度和方向可视化 5 U) M: s0 w/ f" Z4 M% ?6 c! q1 v) i7 T
# 把训练集的所有数据,根据类别存放到不同的数据文件中
1 @+ n2 g# f8 |- Z4 ~6 J6 d3 J def get_diff_data():
% a: y( w7 {2 q) c, U7 |. t; E8 Z$ Z Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl" |6 M: E6 O' S6 i0 K0 t0 F
with open(Path,"rb") as f: # x2 V' z. t; D. E8 Q. Z7 k
total_data = pickle.load(f)
* G# H, }! ^! l ~# r load_save = Load_Save_Data()
: h# E( Q/ S5 ?) R! r kind_data = ["刺网","围网","拖网"] $ f5 H8 e8 L! I6 y2 u+ k5 J9 R. m
file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"]
' ^/ d, z9 ]* t! F5 J for i,datax in enumerate(kind_data): - d9 n& y$ Z; _- P: ~
data_type = [data for data in total_data if data["type"].unique()[0] == datax] 2 |) a4 ]* [2 A- q+ y! [
load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
' k; h* A. B0 E get_diff_data() / k/ g {' A" w! D$ L
#对轨迹进行异常点剔除,对nan值进行线性插值
+ y+ d" y. r1 B, @9 R ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
1 p) C# M9 l7 S, T! N5 E3 Y. ] DF_NEW=[]
{' V2 M* \# ?, Y2 d+ ^* g. k Anomaly_count=[]
5 N, W, t# g; \* J. f for ID in tqdm(ID_list):
: G# x$ L, s% B% P df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
" P& b6 l+ M }7 V) I df_new,count=assign_traj_anomaly_points_nan(df_id) ( o& ^, U) s& m8 T, |. L- e
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) k( m$ a. l. L8 C1 m) L3 w' v
df_new = df_new.fillna(method="bfill") " @3 L" B2 \; A! \2 Y8 {
df_new = df_new.fillna(method="ffill") Q! u, F3 O* a' k" K( ^
df_new["speed"] = df_new["speed"].clip(0, 23)
; R& l& Q- K/ y( c9 }! B! ] Anomaly_count.append(count)#统计每个id异常点的数量有多少 , j U+ n- V, p& w" K% `- ?( a
DF_NEW.append(df_new)
- {& R1 q" |6 S5 A' ] # 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列 + g: n( k6 P1 n. i* E! l! V
def visualize_three_traj_speed_direction(): 5 y: S! b; P' I. ~4 A1 t' F& t1 \) o0 m
fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15)) ! U+ x! `2 g' R" J( m8 G ^
plt.subplots_adjust(wspace=0.3,hspace=0.3) c' Z. ^3 s- }* d. Y
# 随机选出刺网的三条轨迹进行可视化 * v: \$ {6 n$ g4 n* T' j
file_types = ["ciwang_data","weiwang_data","tuowang_data"] : J5 q5 V8 P* p6 G* ^5 F
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] 2 l& ?0 K: X7 y/ v
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"]
$ ^( n: o2 N f colors = [pink, lightblue, lightgreen]
# L& A5 v7 b4 c for i,file_name in tqdm(enumerate(file_types)):
+ ^/ P) I: z2 N- O/ c1 Q0 Y datax = get_random_one_traj(type=file_name) 5 n- P8 ?# e" u! b
x_data = datax["速度"].loc[-1:].values . F& F, B, m2 t% w3 [ ]; r
y_data = datax["方向"].loc[-1:].values
$ \0 j! L+ [" i1 [* F4 ]" ^% \ axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i])
* c/ T _0 |8 \* @' O/ k axes[i][0].grid(alpha=2)
# i8 }- z: D% g& L8 P- l axes[i][0].legend(loc="best")
$ V8 R8 ]! _0 }% n9 p) z8 t axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i])
" w5 c7 ]1 ^% T axes[i][1].grid(alpha=2) - F( z+ d. \" F8 n2 D( U) E4 @
axes[i][1].legend(loc="best") - c/ G" O6 [1 R6 Y3 F
plt.show()
- }( N: X( G0 F visualize_three_traj_speed_direction()
/ Z, E5 c/ u9 G6 j9 {7 X
/ Z# [; }% @; c- Q 作业二:相关性分析。
# H' {9 i+ U$ H! E2 y" R8 f' ` data_train.loc[data_train[type]==刺网,type_id]=1
* k( B; p' h3 R2 F2 G. `% k data_train.loc[data_train[type]==围网,type_id]=2 2 N' c T% C6 ` q: t4 c D
data_train.loc[data_train[type]==拖网,type_id]=3
+ `( Q+ f9 x; b) O: \ f, ax = plt.subplots(figsize=(9, 6)) 1 z/ w: `0 G3 n; v$ l1 J
ax = sns.heatmap(np.abs(df.corr()),annot=True)
, G$ P. |" C+ Z% F# H$ Q6 Z plt.show() 9 t( E3 I( L6 V' p- f7 Z
+ \1 @* A! y: Z, q
从图中可以清楚看到,经纬度和速度跟类型相关性比较大。 + \, Y0 @# z/ C( O2 b8 G; J
5 D8 Q! J' g, K0 M; }4 \ X
/ W% v7 h3 c( ^ t# Q) n' D/ V
' b. V3 u2 M4 A1 w/ Y( w; }
, v5 g# g. O3 s7 M6 T8 U1 L
|