4 w0 E1 d! _: b 此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设# R$ B4 L6 b/ o7 L1 u) |
数据分析的目的:
3 P' ~, ] | B" i; G 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 & N) c4 f6 b7 X/ ^$ V8 J( b/ y; F
2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布 2 Z8 _6 q0 O0 D% v
三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd
& c# U3 a9 M) }6 I, k" O$ p import geopandas as gpd % t( k' E, ]. X& \0 z3 N; @8 A
from pyproj import Proj - Y0 ]2 b: N7 ]& w4 x+ N5 o/ H+ i4 U
from keplergl import KeplerGl ! R6 V+ @4 i2 ]6 `7 X! g. p
from tqdm import tqdm 0 t* R$ q2 W1 ?
import os
1 c5 o# T; f/ ]( M6 Y7 M import matplotlib.pyplot as plt
$ e+ H. B9 ], t: d' b! v import shapely $ Y- u1 N' d9 m2 E8 g! m
import numpy as np
% Q6 F) l- s# S& C/ C0 k; }; T% V( k from datetime import datetime . y/ e5 F7 m( {/ L# I0 y8 K
import warnings 1 H( y' V. }+ Y/ `
warnings.filterwarnings(ignore) $ h6 M h# G# p+ W, p
plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。
; b# i) W p" b9 B8 N3 Q plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。
|5 E j* G& K7 u #获取文件夹中的数据 ' U9 j' ~* i' j1 u `/ V
def get_data(file_path,model): 0 U7 z' b# n% g
assert model in [train, test], {} Not Support this type of file.format(model)
8 U# j: A" c5 b/ y5 ]3 @6 Z paths = os.listdir(file_path)
3 o5 p$ q* l+ i) m4 l" I' K: f # print(len(paths))
, q# F% t- j, f tmp = []
5 N/ x: S$ Q' v' n' m for t in tqdm(range(len(paths))): - O! H$ P2 t* u$ f& m
p = paths[t]
1 m3 d( \7 p7 [ with open({}/{}.format(file_path, p), encoding=utf-8) as f:
4 T( g: o% g! |5 E: h% t next(f)
5 G: |+ b" S. `2 |( P, z* Y1 ? for line in f.readlines():
. \5 s) k& z3 T0 e3 H* q1 G tmp.append(line.strip().split(,))
, _7 k7 U' H! |6 Q1 L5 X tmp_df = pd.DataFrame(tmp)
4 k; L: p; H5 v9 W4 ^$ B0 j: w if model == train:
" o& A; i, g1 ?7 \% i tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
7 t0 l0 n" F! w9 v else: ' Y+ I$ ~ Y5 \3 T& E" X6 j6 y' X
tmp_df[type] = unknown
9 S( a: Y5 c1 q/ B! ? tmp_df.columns = [ID, lat, lon, speed, direction, time, type] 5 V2 X x9 e4 }4 l/ t. x
tmp_df[lat] = tmp_df[lat].astype(float) 9 F% \- x6 b2 T- _0 ^1 f! g+ G) a* x
tmp_df[lon] = tmp_df[lon].astype(float)
0 J4 ~3 `$ B H/ b! d tmp_df[speed] = tmp_df[speed].astype(float)
+ w5 n: A: [2 r tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本 3 l: O. W) y( B2 j
return tmp_df / l4 x9 T. b2 k( n/ F
# 平面坐标转经纬度,供初赛数据使用 - `7 l' H. i1 G
# 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud ) s) e, } b8 P7 N9 j+ V M. x5 a) c t8 K
def transform_xy2lonlat(df):
9 @$ q# N* L4 Y7 w1 s- @ x = df[lat].values # ^; a8 Y' l1 }; I
y = df[lon].values
% U% }1 I/ ]+ |( 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 )
$ T3 P- M/ p# ?. Z _5 i3 n df[lon], df[lat] = p(y, x, inverse=True)
1 I* _6 ?: O* r7 l return df
; h, V8 A' E, D- a- |6 a #修改数据的时间格式 4 p, Z" N# [) }! l+ @
def reformat_strtime(time_str=None, START_YEAR="2019"): : T4 z+ R9 F8 X, ?
"""Reformat the strtime with the form 08 14 to START_YEAR-08-14 """
1 g& r+ s1 P& l; @/ a7 h4 N time_str_split = time_str.split(" ")
% g/ g- n6 t& L! ]' o% B6 l time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4] 5 k4 @& C2 v! Q* L4 n4 c# U
time_str_reformat = time_str_reformat + " " + time_str_split[1]
% m% N' b; A) S- Z # time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S)
, \* a+ z- E/ n9 R1 B$ @ return time_str_reformat % v% W0 x- L) a- c* C
#计算两个点的距离
4 |+ P$ K# V7 z J( N5 B def haversine_np(lon1, lat1, lon2, lat2): % R6 h; K+ y: u P+ c
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2]) ) I1 L5 s z" v( V- M5 `
dlon = lon2 - lon1
L* J# q! V2 o/ F. U dlat = lat2 - lat1
+ x2 J! X: K# E4 j8 Z- K a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2 6 A& @! l8 ]6 D6 A* R
c = 2 * np.arcsin(np.sqrt(a)) 5 \" L8 y, z0 v2 E6 n& C
km = 6367 * c
$ H% a* j9 @; N) E1 o( F' E& j% D return km * 1000 ' j* y' z" ?& b) v3 |9 V2 o! a; Y
def compute_traj_diff_time_distance(traj=None):
7 n$ q" R4 \; E! I """Compute the sampling time and the coordinate distance."""
X6 ?. g2 K8 O$ _ # 计算时间的差值
8 a9 J7 j& u" E# J z. i- G1 L time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[
: w' v6 ?) l' r3 C: M! E "time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60
1 c4 W) c0 v6 I# H" r% g # 计算坐标之间的距离 ' H l1 `+ N' I1 W% ]5 z
dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0
- P% ]. z3 ?- q) ?. \+ F# x5 N traj["lat"].values[1:], # lat_0
& _7 ]% _! F7 |" g$ W* O! n# H/ f traj["lon"].values[:-1], # lon_1
0 g M5 S5 `& F/ E4 y, m# F traj["lat"].values[:-1] # lat_1
{ Q; ]# V% N; M" E: e* l% Q0 m6 Z ) % g- c8 n1 P7 T" \, w* X1 x
# 填充第一个值 ) ?: S B. {1 D. E7 G
time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()
y& y' T9 K* g" {9 O3 V+ z dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist() 8 |- W" `5 M/ o& ~6 o' Z( U
traj.loc[list(traj.index),time_array] = time_diff_array
6 y& t0 l( c* z) g# v( x traj.loc[list(traj.index),dist_array] = dist_diff_array
6 g/ | U7 o: S! N! Z" z) M; p return traj
! u, d+ B/ C9 I: s #对轨迹进行异常点的剔除
* V2 V: G& t' p" J$ T. y$ E! ~ def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,
! q. e( V) j) x5 v time_interval_maximum=200, 0 Z6 g; p. b- m# B* |0 O
coord_speed_maximum=700):
/ U- K( n( F% k0 B/ t """Assign the anomaly points in traj to np.nan.""" 0 n: B$ _& c8 I* C! D0 w
def thigma_data(data_y,n): 5 i4 W1 {! x7 `% X! b. E, ?
data_x =[i for i in range(len(data_y))]
1 }: v6 t- `5 W2 u& u6 C% C ymean = np.mean(data_y) 9 ?$ ?( J" c. O8 o9 q' ?/ b7 g
ystd = np.std(data_y)
: T7 ~8 `' d$ R5 w threshold1 = ymean - n * ystd
# W K4 S3 f! c7 L7 s$ K& V' t# \ threshold2 = ymean + n * ystd $ ~( A- c; h7 F5 [
judge=[]
" @9 H2 f# B* F9 v for data in data_y:
7 \7 t, g4 b ]( }4 B7 B0 ~! j if (data < threshold1)|(data> threshold2):
3 x$ I' H4 G3 @4 u! U" \; ] judge.append(True)
4 H) \7 z- `' j! J& u& @ else: & i! [# O9 D9 X# z/ L
judge.append(False)
8 q# }4 N& L. k/ F) V) p return judge " }: a7 h2 u6 ~% [0 e3 O
# Step 1: The speed anomaly repairing
/ d+ T& B* V; B& L8 c% R8 M5 ] is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0)
) v6 q1 p. I; k( @, V$ W) r traj["speed"][is_speed_anomaly] = np.nan . o4 u3 \7 Y Z
# Step 2: 根据距离和时间计算速度 7 F) @" e) U& g6 I) A* P
is_anomaly = np.array([False] * len(traj)) 3 {) z5 h7 x$ B' ?, z
traj["coord_speed"] = traj["dist_array"] / traj["time_array"]
; J( I- ~, b8 b' h; T # Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点
5 U1 Y" B6 x& D is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) 2 B1 h* H2 E: c
is_anomaly = is_anomaly | is_anomaly_tmp
6 ~: e% e' s# ?* x; Y! o" L, ] is_anomaly.index=traj.index 2 B! r& e; o: B, ~; n
# Condition 2: 轨迹点的3-sigma异常处理
1 I" Q& m/ [$ f7 S0 B; E, R traj = traj[~is_anomaly].reset_index(drop=True) ! J: O" J# M Y5 [/ M% Z
is_anomaly = np.array([False] * len(traj))
4 z8 @8 e# l0 M0 c; I1 w2 T: C if len(traj) != 0:
0 K7 s# R8 @% q3 }" A# @6 U lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
8 x! `4 Y0 ?$ u2 g; H lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean()
7 n0 Q0 ^) {7 J J5 |: h7 a lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std
, W6 e2 Y8 `! n) z lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std
/ D% J) Y: k+ r. l& r is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low)) 0 o ~1 i! _3 V& P9 R6 @5 U
is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low)) 8 Y& w" T) ^& e q4 Z! V. s
traj = traj[~is_anomaly].reset_index(drop=True)
$ q! u7 P( {& Y return traj, [len(is_speed_anomaly) - len(traj)]
) C% \$ T$ V7 d$ M% J" A0 P4 m df=get_data(rC:\Users\admin\hy_round1_train_20200102,train) $ `6 f/ g Y9 z; i4 w1 v
#对轨迹进行异常点剔除,对nan值进行线性插值
" B2 f3 x/ n( v$ \1 A6 g ID_list=list(pd.DataFrame(df[ID].value_counts()).index) # e. ?. y {) c
DF_NEW=[]
3 N1 t7 Y4 e' d7 d5 J6 R& k$ g8 Y# a Anomaly_count=[]
5 R$ z/ p; | \4 E* V. o/ | for ID in tqdm(ID_list):
! F' s9 W& N0 c+ t W df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
0 d1 |- O5 I$ Z df_new,count=assign_traj_anomaly_points_nan(df_id) 5 ^2 w: K" v" j9 z# F8 d; F1 d
df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
- ^7 n6 @) r# o: \/ k% d df_new = df_new.fillna(method="bfill")
- ]! x1 V9 \* W df_new = df_new.fillna(method="ffill") : `5 Q! e4 [2 S% y& e+ g
df_new["speed"] = df_new["speed"].clip(0, 23)
9 t9 i3 ~; ^: D! g* ^4 w% ?7 W1 w Anomaly_count.append(count)#统计每个id异常点的数量有多少
( M$ S* D! u# P& s DF_NEW.append(df_new) $ g( T1 d9 H D: o5 E$ i
#将数据写入到pkl格式
3 k# p# r8 V- k, @/ P2 A load_save = Load_Save_Data() - k3 S. z7 O+ W
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl") 9 c0 _" ^1 f$ ^: G. f5 w
#### 三类渔船速度和方向可视化
' z+ ]* s) l3 \% T% k7 Q# H* e # 把训练集的所有数据,根据类别存放到不同的数据文件中
! M" D: { T1 L1 i; U9 B* E, L1 e def get_diff_data(): / T3 B g% ?* M# u* s3 Q$ i
Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
, f1 V: q3 K2 F; `' A0 r with open(Path,"rb") as f: 5 A9 E* R3 ~' {
total_data = pickle.load(f) 6 J% M) O' |5 B. O
load_save = Load_Save_Data()
j# ]7 z/ \6 \' U" _* O* ] kind_data = ["刺网","围网","拖网"] 8 K" y3 i# Q3 I9 l5 l
file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"]
J$ \8 a4 R# e1 R& C for i,datax in enumerate(kind_data): , W) r) S( {( C* g+ t* C4 V1 Y) N9 k
data_type = [data for data in total_data if data["type"].unique()[0] == datax]
7 A) W4 w4 H) S$ N- l. j. a, X) l) F load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
4 h0 ?# M( x" v( S9 ]6 C4 f get_diff_data()
3 t$ m7 Q }, T: r2 V* I/ F #对轨迹进行异常点剔除,对nan值进行线性插值
{5 }4 t2 J0 A ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
; `1 l" H! X; }% ]; F DF_NEW=[]
; v5 B- r! ~( n, U Anomaly_count=[]
" W' k" h- n9 Q9 _& M) ] for ID in tqdm(ID_list):
6 Z+ i x0 X& o df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) 1 j- ~$ R4 @5 Y0 v1 x
df_new,count=assign_traj_anomaly_points_nan(df_id)
* f3 N3 X5 B1 Z df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) 7 A, L% }0 ~ x0 A- V
df_new = df_new.fillna(method="bfill")
8 M. d+ q! o& J df_new = df_new.fillna(method="ffill")
! K8 |: C. [6 V df_new["speed"] = df_new["speed"].clip(0, 23) 7 a ] b; ?! w: p
Anomaly_count.append(count)#统计每个id异常点的数量有多少 ; k+ z. G6 h6 {& Q/ _
DF_NEW.append(df_new) A6 }+ G7 C; g& L5 m
# 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列
; F x1 S1 d' B% M9 ~; N def visualize_three_traj_speed_direction():
7 ? [" c% ?, j3 R fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15))
8 B! y# y/ O: H- E; H3 L0 N plt.subplots_adjust(wspace=0.3,hspace=0.3)
' H4 _4 h, E9 i' { # 随机选出刺网的三条轨迹进行可视化 / L8 J2 R, h( m) e
file_types = ["ciwang_data","weiwang_data","tuowang_data"]
$ Z5 K& p+ X& F$ }; O$ y speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"] , b+ g$ A- e+ V. E# i
doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"] 2 I" t3 a9 a" d
colors = [pink, lightblue, lightgreen]
1 Q- S2 W. b3 m& T3 f for i,file_name in tqdm(enumerate(file_types)): 1 S/ j6 p- F; L/ s' m) S
datax = get_random_one_traj(type=file_name) / c* S/ W: N3 h/ Z U; r4 {6 ^
x_data = datax["速度"].loc[-1:].values & m, } q3 q2 t' `6 z
y_data = datax["方向"].loc[-1:].values
9 }' b3 t6 r( H5 p) l axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i])
; @1 z7 P6 G+ \$ j/ P axes[i][0].grid(alpha=2) . d2 x9 \+ P! l
axes[i][0].legend(loc="best") % P/ F' x9 t8 a% [4 k0 X: I* R
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i]) * G, P* D% a2 K& E
axes[i][1].grid(alpha=2) . F' t/ @0 ?4 j( S: B, ` T: m
axes[i][1].legend(loc="best") 9 n7 p7 `" C2 y' T6 Y3 d
plt.show() % G. i. `/ @- j& @
visualize_three_traj_speed_direction() 4 _* D( I5 ~7 r9 k7 {' y
; C' {0 X+ \4 ^5 G 作业二:相关性分析。 + u( P) \2 R( e3 w' h
data_train.loc[data_train[type]==刺网,type_id]=1
( x# Z9 H5 ^" [+ u8 A9 u data_train.loc[data_train[type]==围网,type_id]=2 R* G1 m4 N( C5 `; k8 t* n
data_train.loc[data_train[type]==拖网,type_id]=3 8 c, R6 i0 R7 B% h- w
f, ax = plt.subplots(figsize=(9, 6)) 8 y$ B' |8 g/ F! q8 l
ax = sns.heatmap(np.abs(df.corr()),annot=True) / u5 m" ~( N' v5 u; g" v
plt.show()
. G5 i' g: e( i' c6 d
/ J" [& T* t+ l2 h( K5 r% S- L0 C 从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
" x! J( f. g! I/ R6 ?
3 r s+ \2 i$ l; V. f6 B# K1 K- f& r4 t4 W
2 `! ]3 I; R, O0 O! y( a7 k- u( D5 i
|