|
: {# e$ V- E$ T0 v. B" l2 w/ f
此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。 赛题:智慧海洋建设
) j1 T; ~3 X$ v8 U4 Z, X 数据分析的目的:
- K/ ?, L! o8 |; e* L e% h 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 ( A+ X8 Y$ L0 _7 }# j2 X* }
2.1 学习目标 学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务2.2 内容介绍 数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况数据特性和特征分布
I! p" w& K- G X: b 三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布 作业一:剔除异常点后画图import pandas as pd
7 ]! v% J3 k' f( b0 C1 U" e; Q& f import geopandas as gpd " r/ D G. m8 H( l$ ~# \2 o- i
from pyproj import Proj
4 [3 Y* s; L3 w. p5 B from keplergl import KeplerGl & R- g$ i' P, k" t1 U
from tqdm import tqdm
! J: \' e4 a7 s8 j2 q+ X! F import os
0 W/ ~& c5 w2 o- a9 y4 P; w A import matplotlib.pyplot as plt 8 G0 o6 n( u2 T- _
import shapely
/ b! j& A6 O, }: X, X; {# H import numpy as np
7 P) t4 M v' P( i0 _ from datetime import datetime ( F* Z* i; C& Z, b$ d8 P6 N4 C
import warnings
9 }3 H6 [: l2 G! \/ y9 c% t! ^ warnings.filterwarnings(ignore)
+ q' [/ Q, c! M plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。 ! P2 M1 ?! @+ {$ s
plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。 & ^2 T& k/ Z2 P
#获取文件夹中的数据
9 h: w; j$ o, S: y0 `) I def get_data(file_path,model):
3 c3 a: P, N& I1 C, B8 U assert model in [train, test], {} Not Support this type of file.format(model) 6 }3 p4 Y4 t4 y. u* W M% y3 x1 d
paths = os.listdir(file_path)
" c' u8 U4 e A1 K2 E1 i # print(len(paths))
! E& M3 P7 J: s tmp = []
5 P% [0 B+ d; A* w9 y9 t* k$ L, b for t in tqdm(range(len(paths))): & i2 _+ A7 f5 V& Y5 d# v& L
p = paths[t]
6 a7 C: c; q. h5 t4 \% c6 ` with open({}/{}.format(file_path, p), encoding=utf-8) as f: $ M) Q4 D7 r: x; R" p2 |
next(f) & y( z1 g! F6 T. k' K7 f: F
for line in f.readlines():
# f2 O* T C7 \; d S tmp.append(line.strip().split(,)) A2 v* d1 w3 n4 b+ j
tmp_df = pd.DataFrame(tmp)
+ u" m2 @7 x4 {; ?& G if model == train: 9 h7 A1 `+ v4 p
tmp_df.columns = [ID, lat, lon, speed, direction, time, type]
3 `- J9 D1 |1 K0 P$ B- B else:
; C& K% a- ~5 @ tmp_df[type] = unknown
; T8 A4 s1 G' H* G5 `) ~% d tmp_df.columns = [ID, lat, lon, speed, direction, time, type] ! [- ]3 c) j% m4 i) a
tmp_df[lat] = tmp_df[lat].astype(float) & Z8 V# ~* ^% @2 a4 j# T: z
tmp_df[lon] = tmp_df[lon].astype(float) 3 E6 ~& t0 ?) {- Q5 g
tmp_df[speed] = tmp_df[speed].astype(float) , H1 q# `# s7 ^0 u- N
tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本
, g5 J, I$ D0 @0 x return tmp_df 7 R% ?; H: ]* ?7 M
# 平面坐标转经纬度,供初赛数据使用
2 O7 v0 o9 D/ z6 X: x # 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud 7 L5 ?& S4 N. P* e$ V9 D
def transform_xy2lonlat(df):
2 V/ R; |6 V: e* r+ ` x = df[lat].values * x1 E) u+ i# O1 U, Y
y = df[lon].values
/ z( U9 b+ {2 W$ t 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 ) 8 A& E+ c7 e: F7 B; W) j$ E- H
df[lon], df[lat] = p(y, x, inverse=True)
, r, A# a0 e( P( d return df
& D( S% T$ m/ i2 ^9 l: k' {+ H #修改数据的时间格式 # j) q R, _0 }
def reformat_strtime(time_str=None, START_YEAR="2019"): . i8 F2 F& S3 F8 ]
"""Reformat the strtime with the form 08 14 to START_YEAR-08-14 """
5 C3 \0 g+ p( D" X4 m% | time_str_split = time_str.split(" ")
4 D& K2 b. w& o" o5 M) y time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4]
|8 C3 r4 D* x; z time_str_reformat = time_str_reformat + " " + time_str_split[1] 8 Z8 _3 Y$ f, H& r4 b9 W' ^
# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S)
) v4 Q# w( B1 D% k) ] return time_str_reformat 9 H, h4 K4 j w) z7 y3 ]
#计算两个点的距离 ' O' V+ Z! R5 m4 U+ d% [2 ?4 _
def haversine_np(lon1, lat1, lon2, lat2):
. \' [5 C: e6 q7 V7 F; Z+ z# E8 `* l lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
) [- X/ {2 Q2 J2 Z' \8 a dlon = lon2 - lon1 * x0 `7 L$ i1 u1 m9 a, [. [$ f" Y
dlat = lat2 - lat1 ! F5 r0 z# X8 L) P( N! \
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
) Q4 X& M9 ]' j) J8 s c = 2 * np.arcsin(np.sqrt(a)) 1 Q7 g! B4 f! L- @- Q
km = 6367 * c
6 n6 e0 n, @" o$ ?) \+ A0 I( s return km * 1000 / k" h0 c; F' j$ N+ d% J/ g' L
def compute_traj_diff_time_distance(traj=None):
# x- T. Z* s1 |$ ~, j2 U """Compute the sampling time and the coordinate distance."""
. a5 e/ Z" \% U1 h # 计算时间的差值
% ` r6 F5 j; \0 e time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[
* R5 H) m |2 G7 I' [8 U; `: \ "time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60
3 m- T& p5 B, H4 g! h # 计算坐标之间的距离
; i' p: z3 N) u3 E9 q4 f dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0 / l8 x/ `0 h p9 a$ M* M
traj["lat"].values[1:], # lat_0 x) W: h3 U# v" L+ v$ T+ e
traj["lon"].values[:-1], # lon_1 1 k j2 v0 S: m6 e+ Z
traj["lat"].values[:-1] # lat_1
! p7 Z* C- e1 t' u" [# r )
) h! ?0 _: r6 A3 }" W d+ ] # 填充第一个值
& Z R: Q% D. Z time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()
. M5 F1 u8 E- _# f, J$ U dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()
8 I: W' y8 Y& d% V2 i" Y: [ traj.loc[list(traj.index),time_array] = time_diff_array
4 Y$ n+ O) Y8 Z, H0 l4 U traj.loc[list(traj.index),dist_array] = dist_diff_array
: }2 s8 z( L$ ]( o6 V T0 b return traj ; c6 q1 Z2 v4 y8 z5 L5 `
#对轨迹进行异常点的剔除 ( r/ ] [1 g9 a* Q/ ?1 G* U3 ^/ k
def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23, ) |: L! X4 h8 D7 r3 K
time_interval_maximum=200,
8 B( n F" ~3 j" O; _2 J coord_speed_maximum=700): ! E( S" b# d3 m' v
"""Assign the anomaly points in traj to np.nan."""
5 u+ p0 b1 k- z/ f! S def thigma_data(data_y,n): " ` f+ [, y; d* {. E% R8 H9 }
data_x =[i for i in range(len(data_y))] ! P3 ?% J9 {) i1 {
ymean = np.mean(data_y) 2 _0 K6 j$ G% H8 G3 i5 G |
ystd = np.std(data_y) ( a7 Q1 K) i3 d" s; M3 k
threshold1 = ymean - n * ystd 1 m8 z1 n+ z8 `1 S2 X$ x: S
threshold2 = ymean + n * ystd ' b$ V+ c3 n) o* X" K5 E- J8 T
judge=[]
! i7 o; {# b+ J0 a" c+ B for data in data_y: $ r3 F9 H: K* r9 Z$ A
if (data < threshold1)|(data> threshold2): 0 k. r, ?$ E/ i3 O2 j
judge.append(True) 2 L( \ ^8 R4 w! S
else:
9 n: _4 Q- k3 y6 u judge.append(False)
! \1 W# g2 @0 n return judge 3 f2 D* P5 o3 y, L! r, G6 K6 E
# Step 1: The speed anomaly repairing
+ a& I5 \$ w8 p is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0)
" O5 P8 a5 l# }! }3 b# ^5 j traj["speed"][is_speed_anomaly] = np.nan ' a3 d H+ b: i4 F: N
# Step 2: 根据距离和时间计算速度 ; D2 g! S9 ?5 C, Y
is_anomaly = np.array([False] * len(traj)) " f. {; D# |# P. g+ A7 g
traj["coord_speed"] = traj["dist_array"] / traj["time_array"] 4 N8 m6 x& I2 w
# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点
/ z: L3 b; W, M. [1 L2 U is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3)) $ D& Q4 e* m9 M) o8 n
is_anomaly = is_anomaly | is_anomaly_tmp
/ x2 }8 c: m% H' k+ \! W is_anomaly.index=traj.index
# N. p; n* y; e: F # Condition 2: 轨迹点的3-sigma异常处理 : m0 @" u/ Y- _4 u
traj = traj[~is_anomaly].reset_index(drop=True) e# P% v- o0 F- `. s
is_anomaly = np.array([False] * len(traj)) 7 O9 v6 I' j& p6 a
if len(traj) != 0: . N2 k$ ^' B/ G+ r1 m1 h
lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()
# G9 C! N- T& w/ K% x* h1 l lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean() : }* i8 Z) q6 b% Q
lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std # N) r8 `- \, }% n
lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std ' [4 `2 }! H5 t, v3 C
is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low))
/ G; x" ]9 @% `; g" I0 O; _2 U is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))
8 a, m: K, z' m$ |& x4 [ traj = traj[~is_anomaly].reset_index(drop=True) U# ?# Q; V J I& r
return traj, [len(is_speed_anomaly) - len(traj)]
, Q% G {' B: c df=get_data(rC:\Users\admin\hy_round1_train_20200102,train) % U/ R0 X8 H. [; Q! V
#对轨迹进行异常点剔除,对nan值进行线性插值
$ d: u% D6 z7 B+ _' {9 J# [% ~1 s8 [ ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
' P' k* }# @+ j DF_NEW=[] % `" q% P+ [6 L8 A4 }
Anomaly_count=[]
g h6 N9 ^' Y9 D2 D6 Y for ID in tqdm(ID_list): + S2 P5 c, ^. s6 X
df_id=compute_traj_diff_time_distance(df[df[ID]==ID]) , \3 h4 ]1 O& M& H1 \
df_new,count=assign_traj_anomaly_points_nan(df_id)
; C3 ^+ i/ f& C# t, ^ df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0) $ d7 F9 N0 `. G
df_new = df_new.fillna(method="bfill")
+ X; C5 F/ `0 b. K df_new = df_new.fillna(method="ffill")
- |: Y! ^' G! h) w df_new["speed"] = df_new["speed"].clip(0, 23)
/ @! k( [0 N( v+ `9 D& v Anomaly_count.append(count)#统计每个id异常点的数量有多少
( r# t6 s0 ~! i: E DF_NEW.append(df_new)
/ E% g3 q0 C& A3 l7 L8 u' ]% M #将数据写入到pkl格式
8 F3 r9 m& M3 c) B5 m load_save = Load_Save_Data() z. u7 U5 s% h. r1 q1 y5 R
load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl") - U, l8 r: {$ d" c ~& X% S- J
#### 三类渔船速度和方向可视化
2 G* ~; d" ? f8 W # 把训练集的所有数据,根据类别存放到不同的数据文件中
. _4 H5 [3 j. e( w) e6 y2 u( b+ {/ {' T& U def get_diff_data():
* Z1 {5 Z7 A) Z) a; v9 [* k5 r Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"
5 ^: ?5 P/ h; k3 ], V with open(Path,"rb") as f: + t+ A/ q8 X V D; b9 }, R0 I
total_data = pickle.load(f)
# T: _$ K/ X* e5 L" } load_save = Load_Save_Data()
+ |" z; [& i( h$ O0 G9 B kind_data = ["刺网","围网","拖网"]
; N; i8 M- S# ]* i3 u file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"]
4 B) M4 m* \: v3 C* B$ k8 D5 t for i,datax in enumerate(kind_data): 0 v* g' g1 w' _6 t
data_type = [data for data in total_data if data["type"].unique()[0] == datax] + W8 m; H( S4 T/ g/ z
load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])
1 s4 W3 P0 n, W get_diff_data()
]0 a! `( o/ ^) x% u: S2 ~- o #对轨迹进行异常点剔除,对nan值进行线性插值 + [$ l" f G" G* E/ p* [
ID_list=list(pd.DataFrame(df[ID].value_counts()).index)
; W1 E T( o) J DF_NEW=[] 2 `& N6 t2 J2 A+ \" X
Anomaly_count=[]
1 f2 I) j' a# `! Z/ S for ID in tqdm(ID_list): $ ~7 M/ s( r- f# C% c
df_id=compute_traj_diff_time_distance(df[df[ID]==ID])
3 F6 x! W T" Q, m- u# I4 t df_new,count=assign_traj_anomaly_points_nan(df_id)
' e5 Q8 v- D. i df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)
; m3 e9 Y- n) o0 l6 O8 h9 j, a df_new = df_new.fillna(method="bfill")
; x" g6 }5 }( Q% g! R5 c% k, d df_new = df_new.fillna(method="ffill") . a1 E1 B3 y8 I v6 L' L! f" u
df_new["speed"] = df_new["speed"].clip(0, 23) . F0 B; G1 [3 n) z
Anomaly_count.append(count)#统计每个id异常点的数量有多少 3 m. n, k4 a# N8 S d5 y
DF_NEW.append(df_new) ' J4 p4 p2 f" J* M( t
# 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列
; V p- T- Y4 X0 } def visualize_three_traj_speed_direction():
6 {1 m0 u+ _" B fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15)) + Y- r1 `1 u/ x6 ]. A
plt.subplots_adjust(wspace=0.3,hspace=0.3)
4 e/ }- @1 G5 Z6 f" r0 ? # 随机选出刺网的三条轨迹进行可视化
/ P$ v; z- o8 b file_types = ["ciwang_data","weiwang_data","tuowang_data"] - x- `) {* E' H- E( ~/ @$ N
speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"]
! J1 z3 n$ _* z) ~* q doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"]
, b: Z% d: Y# d7 q& a+ n6 c. p colors = [pink, lightblue, lightgreen]
8 g Y3 ]* y9 g* l- @4 w for i,file_name in tqdm(enumerate(file_types)): . u$ m2 q" b" c8 s# D4 F+ _' ]. n
datax = get_random_one_traj(type=file_name)
. e2 G9 _( ~2 B8 r8 z1 P x_data = datax["速度"].loc[-1:].values
# ?& T" w( t& L% M9 ?; Z- V y_data = datax["方向"].loc[-1:].values
# W! Q8 g- O3 Z. w axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i])
' ]2 |! |1 c; s! H0 |# Y axes[i][0].grid(alpha=2) 2 ~5 d. K+ G/ P$ ~; p
axes[i][0].legend(loc="best") % ~; L6 c" m0 _ \! r: W) h
axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i])
2 Z* {* G- X5 W' x# {( }- \5 Q+ ] axes[i][1].grid(alpha=2)
! D4 t8 j2 d S' q+ W8 D) Q axes[i][1].legend(loc="best") / T" f5 ?" v A5 t
plt.show()
) |" @' b% I' u visualize_three_traj_speed_direction()
" [& X- I- N w3 A: c5 e , D! Q( ]8 ^0 E. R
作业二:相关性分析。 ! v0 J( ?2 r' M9 u/ w* \# x
data_train.loc[data_train[type]==刺网,type_id]=1
6 B* B0 k1 b' J* d7 S0 \ data_train.loc[data_train[type]==围网,type_id]=2 ; n( N8 G) r0 O" V, S; g1 ~
data_train.loc[data_train[type]==拖网,type_id]=3
8 d7 I& \ _% n2 F1 S1 M f, ax = plt.subplots(figsize=(9, 6)) 7 o' Z& S: T4 V7 p4 X0 }4 f0 W
ax = sns.heatmap(np.abs(df.corr()),annot=True) * n$ k( I& x) b. d" \
plt.show() - b$ Q V1 n& b! ^4 ?
& [* [) I" x0 f5 k- n9 M 从图中可以清楚看到,经纬度和速度跟类型相关性比较大。
2 h U% ?& G8 m* h# ?7 k% W+ p4 ]
# F9 n/ i B$ W8 j/ ]. u# K
0 G; L1 O% d# Y# C3 B8 |; v
# J3 a/ e. z p- N) k9 {$ j/ J6 R1 Z5 W) q
|