收藏本站 劰载中...网站公告 | 吾爱海洋论坛交流QQ群:835383472

Datawhale 智慧海洋建设-Task2 数据分析

[复制链接]
7 s5 | y/ m4 Q5 f/ E

此部分为智慧海洋建设竞赛的数据分析模块,通过数据分析,可以熟悉数据,为后面的特征工程做准备,欢迎大家后续多多交流。

赛题:智慧海洋建设4 t3 M9 w+ ~' h) N6 S+ c

数据分析的目的:

1 b: R3 D4 C, L 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

+ O5 @1 C0 F% D; o2 q0 P. n

2.1 学习目标

学习如何对数据集整体概况进行分析,包括数据集的基本情况(缺失值、异常值)学习了解变量之间的相互关系、变量与预测值之间的存在关系。完成相应学习打卡任务

2.2 内容介绍

数据总体了解读取数据集并了解数据集的大小,原始特征维度;通过info了解数据类型;粗略查看数据集中各特征的基本统计量缺失值和唯一值查看数据缺失值情况查看唯一值情况

数据特性和特征分布

( G* p8 p6 _0 b) [! h, n: T, R

三类渔船轨迹的可视化坐标序列可视化三类渔船速度和方向序列可视化三类渔船速度和方向的数据分布

作业一:剔除异常点后画图

import pandas as pd

$ C5 G: I4 Q" ~# K- d* o9 A; r

import geopandas as gpd

; \3 a: x) h8 L

from pyproj import Proj

7 E1 H0 I% z& x1 y$ |8 \$ c- t: z3 C2 `

from keplergl import KeplerGl

- _6 @$ B9 Y: P1 w) v

from tqdm import tqdm

. }4 q8 |- l" |

import os

+ A% \0 b z& C3 O

import matplotlib.pyplot as plt

- `4 m" K+ }. U1 ~

import shapely

2 u6 U9 F7 T% W3 b! x7 C, A& E6 X7 K

import numpy as np

; `# q! S& p# K0 c2 l

from datetime import datetime

7 ?8 G3 Z6 z" D" X( }* ?8 w

import warnings

1 q, _; u* z9 [' e8 v

warnings.filterwarnings(ignore)

9 d3 P% {5 e6 z3 I/ i1 p

plt.rcParams[font.sans-serif] = [SimSun] # 指定默认字体为新宋体。

3 {" l3 m5 U6 u

plt.rcParams[axes.unicode_minus] = False # 解决保存图像时 负号- 显示为方块和报错的问题。

+ Y/ L1 q8 J# U- P4 X

#获取文件夹中的数据

2 O5 {2 V, s. v5 G9 f! z

def get_data(file_path,model):

/ V, a* o9 J; F$ O: ~5 I6 h

assert model in [train, test], {} Not Support this type of file.format(model)

* C/ l! A+ w" F+ `. @$ s. z

paths = os.listdir(file_path)

+ w5 e0 l' ^; }! Z* T

# print(len(paths))

! u: @, y3 ?0 w# p

tmp = []

5 D+ \8 @! W% v, K J4 D5 K" H% T

for t in tqdm(range(len(paths))):

; D) Q. u3 i; @8 h' N

p = paths[t]

0 e1 k$ G$ n! W' L3 x' U" U

with open({}/{}.format(file_path, p), encoding=utf-8) as f:

% I: W! q# N- \, L

next(f)

4 L5 F3 [; v( w7 u9 e5 s7 E* D- v8 G b

for line in f.readlines():

3 R! S$ |3 y" q9 H

tmp.append(line.strip().split(,))

7 Q& k$ @! a% Z% L& c

tmp_df = pd.DataFrame(tmp)

( L0 F e- W4 B9 }% N+ U1 |5 p

if model == train:

; b' J. ]. }0 B

tmp_df.columns = [ID, lat, lon, speed, direction, time, type]

8 [" j9 u3 W3 e" I6 B, |

else:

* J+ @* }( r% |

tmp_df[type] = unknown

$ i# }; T- z5 m

tmp_df.columns = [ID, lat, lon, speed, direction, time, type]

; ~8 F+ y1 _8 B% \5 c

tmp_df[lat] = tmp_df[lat].astype(float)

( k6 W* _( q$ X u: }, E# q5 B

tmp_df[lon] = tmp_df[lon].astype(float)

, O6 G8 K8 ^( d. r

tmp_df[speed] = tmp_df[speed].astype(float)

: n. h% g$ P/ r ~! W

tmp_df[direction] = tmp_df[direction].astype(int)#如果该行代码运行失败,请尝试更新pandas的版本

' t, k5 d9 c$ c* G! j# V

return tmp_df

8 s5 F- r: [7 a1 Y* T

# 平面坐标转经纬度,供初赛数据使用

# E8 c. \% q6 V, ?+ u, V) |) t! x

# 选择标准为NAD83 / California zone 6 (ftUS) (EPSG:2230),查询链接:CS2CS - Transform Coordinates On-line - MyGeodata Cloud

# k0 G& B6 S/ I; s1 |; @$ A

def transform_xy2lonlat(df):

# ?3 r2 g# z1 l& \8 ^# q5 j

x = df[lat].values

* e2 m7 v6 A* L# f& J

y = df[lon].values

N _0 l: y; B+ [5 ^# u- U* n4 p

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 )

( B, _6 [( S1 }1 B3 Q$ X

df[lon], df[lat] = p(y, x, inverse=True)

! u, y0 H* N' F: ]

return df

1 p0 d: [4 F* G7 y& V8 H; | A

#修改数据的时间格式

$ }9 A) B& I9 Q6 c# f2 x- i

def reformat_strtime(time_str=None, START_YEAR="2019"):

) U5 O. C, ?( Q/ ^# b

"""Reformat the strtime with the form 08 14 to START_YEAR-08-14 """

6 U' O, @9 r) g3 z

time_str_split = time_str.split(" ")

% [/ t/ K0 o0 w: N( z

time_str_reformat = START_YEAR + "-" + time_str_split[0][:2] + "-" + time_str_split[0][2:4]

0 p& i% z. O# Q8 r

time_str_reformat = time_str_reformat + " " + time_str_split[1]

# k+ b5 s5 K H# n

# time_reformat=datetime.strptime(time_str_reformat,%Y-%m-%d %H:%M:%S)

$ S3 h& Y6 Q8 W( Q

return time_str_reformat

4 A6 r# e& E! {, _ T; G; E8 P# ` q

#计算两个点的距离

; K8 d5 d+ P! A

def haversine_np(lon1, lat1, lon2, lat2):

" L7 }" `) v2 R

lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])

( P6 o5 i0 m, {0 ]4 g

dlon = lon2 - lon1

2 t* e! b$ W, p/ q$ B

dlat = lat2 - lat1

- x5 \- z- d3 `, N1 {1 f5 d7 H

a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2

8 ] i1 `* O1 X# A

c = 2 * np.arcsin(np.sqrt(a))

) x5 q6 Y* E) M' {0 L$ O

km = 6367 * c

: w+ I) g9 g/ W( B

return km * 1000

8 i! ]6 I' O2 L3 G3 }' t: J

def compute_traj_diff_time_distance(traj=None):

- f2 Y# Z% ^) Q b- j

"""Compute the sampling time and the coordinate distance."""

m$ i5 ?! W2 M* N7 J0 `' U

# 计算时间的差值

2 @* R3 ~( O; f! W

time_diff_array = (traj["time"].iloc[1:].reset_index(drop=True) - traj[

8 d0 n2 |& n( s" X$ W# `. B. Z

"time"].iloc[:-1].reset_index(drop=True)).dt.total_seconds() / 60

& o6 j( a- s% m! e% P" |

# 计算坐标之间的距离

8 n+ Y+ ?* s/ I

dist_diff_array = haversine_np(traj["lon"].values[1:], # lon_0

1 D& y. i$ W- `( z) ^

traj["lat"].values[1:], # lat_0

, }0 u1 I+ u8 M

traj["lon"].values[:-1], # lon_1

5 B. A: b3 x+ L

traj["lat"].values[:-1] # lat_1

! m4 |( ^. X) O: g$ |

)

6 c, _( d8 Z+ T2 M# y

# 填充第一个值

9 S- _( l/ G) j1 `* W

time_diff_array = [time_diff_array.mean()] + time_diff_array.tolist()

0 m' r" J+ O1 Q( E* \

dist_diff_array = [dist_diff_array.mean()] + dist_diff_array.tolist()

) `/ o& @% s2 o3 s5 k9 [8 ]* W

traj.loc[list(traj.index),time_array] = time_diff_array

: Q5 l5 T; ]6 r- W9 X

traj.loc[list(traj.index),dist_array] = dist_diff_array

o+ U. `9 z+ o& R) c+ V

return traj

1 @8 ^4 T2 u' X9 U2 p$ ]

#对轨迹进行异常点的剔除

7 B) |3 Q+ }# g6 |

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

2 G, @0 F. ]/ {! F! v' C

time_interval_maximum=200,

+ y0 A. V; X3 w- U; T

coord_speed_maximum=700):

% ]* Q# I1 _1 f' v

"""Assign the anomaly points in traj to np.nan."""

^) y8 l" Q# Q

def thigma_data(data_y,n):

- F5 f' w. m* L- m! C- J

data_x =[i for i in range(len(data_y))]

8 p8 }3 R7 @7 g+ R6 F& w: |6 Q

ymean = np.mean(data_y)

0 }, x$ Q% N+ W, \( K9 n

ystd = np.std(data_y)

8 l+ c% ~9 N3 C/ z: t

threshold1 = ymean - n * ystd

6 d* k: Q0 v2 c7 ?; I G

threshold2 = ymean + n * ystd

& M9 P5 R% O, E

judge=[]

. b: g" g$ ] d; {3 X! s

for data in data_y:

; d# _& c2 V" p( j- e

if (data < threshold1)|(data> threshold2):

% @2 l9 Z" Q3 @/ u( m& u

judge.append(True)

9 N( B- u" s# t5 x# U- g8 s* N/ u

else:

- z, E" G. w5 j% a# D

judge.append(False)

; Z3 _+ F5 m' x( s9 C

return judge

/ {& | T/ Q b

# Step 1: The speed anomaly repairing

1 _ B6 ?) z+ X

is_speed_anomaly = (traj["speed"] > speed_maximum) | (traj["speed"] < 0)

: o0 i' P W5 y% |# ~0 Q

traj["speed"][is_speed_anomaly] = np.nan

- P0 @- F$ [+ V& }5 G

# Step 2: 根据距离和时间计算速度

9 R( C) q0 X, ^/ G2 v6 N* Y, k

is_anomaly = np.array([False] * len(traj))

& [# S2 Q5 X! Q( r4 B E) m

traj["coord_speed"] = traj["dist_array"] / traj["time_array"]

9 y; f4 `/ r& l3 {0 C, `

# Condition 1: 根据3-sigma算法剔除coord speed以及较大时间间隔的点

! K5 Z5 c% B) i) P9 ~! y9 g

is_anomaly_tmp = pd.Series(thigma_data(traj["time_array"],3)) | pd.Series(thigma_data(traj["coord_speed"],3))

+ D7 N. h/ B! @ K7 k/ {: N$ c

is_anomaly = is_anomaly | is_anomaly_tmp

5 R7 G- l4 S! [* o2 y

is_anomaly.index=traj.index

) J8 s0 b& E+ Z( i2 R# ^1 B# E

# Condition 2: 轨迹点的3-sigma异常处理

& F/ N2 a# W4 X" q

traj = traj[~is_anomaly].reset_index(drop=True)

# S7 ^; h V! j ~( _

is_anomaly = np.array([False] * len(traj))

) I: V* `* S/ {% g; A$ b7 E

if len(traj) != 0:

6 x. B- R2 W( F% x. i/ Q

lon_std, lon_mean = traj["lon"].std(), traj["lon"].mean()

7 D8 Z T" X9 W# V! }

lat_std, lat_mean = traj["lat"].std(), traj["lat"].mean()

3 y Y: z6 O, I# S# u

lon_low, lon_high = lon_mean - 3 * lon_std, lon_mean + 3 * lon_std

+ b7 k2 P) r* G% r& \; P5 k B

lat_low, lat_high = lat_mean - 3 * lat_std, lat_mean + 3 * lat_std

1 U: D$ E. @2 M* m0 L

is_anomaly = is_anomaly | (traj["lon"] > lon_high) | ((traj["lon"] < lon_low))

3 U$ t, Q2 c7 u" @! U) }- \% F

is_anomaly = is_anomaly | (traj["lat"] > lat_high) | ((traj["lat"] < lat_low))

, o9 p D9 g- I! r

traj = traj[~is_anomaly].reset_index(drop=True)

' z+ }$ w5 I9 y/ w {

return traj, [len(is_speed_anomaly) - len(traj)]

1 h7 _( R" e" }9 s" K! ]

df=get_data(rC:\Users\admin\hy_round1_train_20200102,train)

" X# M# u* u/ w. i: m; n

#对轨迹进行异常点剔除,对nan值进行线性插值

7 Y# f0 h$ p* E# u3 Z9 ?/ f3 g) X

ID_list=list(pd.DataFrame(df[ID].value_counts()).index)

. n* j/ S; G# R4 O

DF_NEW=[]

6 ]' y3 \2 `) ?6 D. N% k# X

Anomaly_count=[]

; O5 R! c, c% U( f$ w0 P0 F/ v

for ID in tqdm(ID_list):

) Q6 {5 o8 p% X- [' h# P g

df_id=compute_traj_diff_time_distance(df[df[ID]==ID])

# V7 L ^) N0 ]- W7 Z/ Q

df_new,count=assign_traj_anomaly_points_nan(df_id)

2 d' Y X& I4 S5 B5 |' {2 q

df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)

! H2 X/ R* S& S6 w5 O

df_new = df_new.fillna(method="bfill")

" o0 Y* [2 ^4 \3 {# _$ E3 n2 {

df_new = df_new.fillna(method="ffill")

) ?1 O1 v' x4 T; c8 i0 q) h2 D

df_new["speed"] = df_new["speed"].clip(0, 23)

+ X$ v9 { u* U% B3 _6 `- l$ M

Anomaly_count.append(count)#统计每个id异常点的数量有多少

$ N# _2 P) _8 s% q4 f

DF_NEW.append(df_new)

7 h) G b/ X( E8 I* j& m% |. V

#将数据写入到pkl格式

+ R- l F9 D% R, O% i

load_save = Load_Save_Data()

2 D6 D' }9 t$ m8 E; V3 ~4 n. `+ z

load_save.save_data(DF_NEW,"C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl")

4 I1 Z# F8 q6 Q

#### 三类渔船速度和方向可视化

+ r2 O9 k$ N: X. A. X) F

# 把训练集的所有数据,根据类别存放到不同的数据文件中

! O7 e5 o2 o* V3 Y% X B

def get_diff_data():

$ m- N4 J4 k. b9 [

Path = "C:/Users/admin/wisdomOcean/data_tmp1/total_data.pkl"

8 ?$ n- o# ]/ |

with open(Path,"rb") as f:

% v; [; Q9 R+ @: S! _7 o# {) ?* K" ~

total_data = pickle.load(f)

3 d2 b: |& `, r7 H) I' F

load_save = Load_Save_Data()

2 V( O5 G8 w" Z) F

kind_data = ["刺网","围网","拖网"]

# g" G% n& Y o. m

file_names = ["ciwang_data.pkl","weiwang_data.pkl","tuowang_data.pkl"]

; K; p# ~1 c! N

for i,datax in enumerate(kind_data):

! I' L9 {6 `8 U

data_type = [data for data in total_data if data["type"].unique()[0] == datax]

) R6 X( R$ P+ [2 m3 _5 `0 f( ~ t# m

load_save.save_data(data_type,"C:/Users/admin/wisdomOcean/data_tmp1/" + file_names[i])

5 H6 \) S% ^' S6 v! l

get_diff_data()

& L! w. b) b3 U- q: J$ J, o

#对轨迹进行异常点剔除,对nan值进行线性插值

) v8 a; G5 x" u5 T8 Q3 Y

ID_list=list(pd.DataFrame(df[ID].value_counts()).index)

- z3 `; m& f3 }$ @8 O, L1 T6 Q

DF_NEW=[]

) ?2 O3 K# e h d

Anomaly_count=[]

( k ~$ U+ u5 R5 S( u" p! c( H& U1 r

for ID in tqdm(ID_list):

! p# X2 k0 n g2 A/ e9 i# O

df_id=compute_traj_diff_time_distance(df[df[ID]==ID])

+ S7 S' ?) ^" e

df_new,count=assign_traj_anomaly_points_nan(df_id)

) q$ x$ N" d, F# ~

df_new["speed"] = df_new["speed"].interpolate(method="linear", axis=0)

3 T: B5 _/ f- e' W- _. T' F' _) D

df_new = df_new.fillna(method="bfill")

4 ?: W5 @- `2 S) Y6 ~. Y, b

df_new = df_new.fillna(method="ffill")

8 M! {1 E6 p8 e, r; c* V

df_new["speed"] = df_new["speed"].clip(0, 23)

8 |8 W! [9 s9 u, w2 h3 i

Anomaly_count.append(count)#统计每个id异常点的数量有多少

% c$ M2 n! `: @- ?

DF_NEW.append(df_new)

# e; n2 c# G( G( H [- B& n2 e

# 每类轨迹,随机选取某个渔船,可视化速度序列和方向序列

4 K, Q. J2 z0 ~, _( c

def visualize_three_traj_speed_direction():

; D$ u" |- Q1 D) z: Q& C* H

fig,axes = plt.subplots(nrows=3,ncols=2,figsize=(20,15))

0 H# b9 m) j# n7 Y# p: k% e

plt.subplots_adjust(wspace=0.3,hspace=0.3)

# y) O" W# r4 }) [

# 随机选出刺网的三条轨迹进行可视化

# B0 R! W9 {% c5 `& K8 Z' Y/ r

file_types = ["ciwang_data","weiwang_data","tuowang_data"]

* E9 h# m- R7 i) Y) C( x& ]

speed_types = ["ciwang_speed","weiwang_speed","tuowang_speed"]

6 N/ U: b2 L. f- j

doirections = ["ciwang_direction","weiwang_direction","tuowang_direction"]

3 K6 w1 x/ z# F# X n0 ^$ m

colors = [pink, lightblue, lightgreen]

" i/ F7 A: ?3 o" Z/ O! i7 c* i5 C% c

for i,file_name in tqdm(enumerate(file_types)):

' E: y5 B% ?6 ]8 {. v0 d, w% _

datax = get_random_one_traj(type=file_name)

9 P* ?6 s" C( v5 g

x_data = datax["速度"].loc[-1:].values

1 h3 Y% T4 P, a0 ]7 H0 u

y_data = datax["方向"].loc[-1:].values

$ `; l3 |2 B' v0 B5 m

axes[i][0].plot(range(len(x_data)), x_data, label=speed_types[i], color=colors[i])

7 g! I# U- r. [

axes[i][0].grid(alpha=2)

$ d- `. t& ~1 F- n

axes[i][0].legend(loc="best")

. U! ~4 U4 g# k

axes[i][1].plot(range(len(y_data)), y_data, label=doirections[i], color=colors[i])

1 Q& _- d1 E9 y# h; C" x

axes[i][1].grid(alpha=2)

4 @' @. L* |" h# a- X+ s2 R# M

axes[i][1].legend(loc="best")

/ F9 Z1 ^$ z% u/ Y$ k$ W

plt.show()

& y* K; R0 N$ V

visualize_three_traj_speed_direction()

) x8 E. W% x1 E& P+ n
% ^7 ?; z6 a6 i/ Y& v3 E% ]. r

作业二:相关性分析。

) C* }. J( I% H5 c) y1 c

data_train.loc[data_train[type]==刺网,type_id]=1

0 H. d1 g6 o$ c8 E

data_train.loc[data_train[type]==围网,type_id]=2

' S. s# \; A8 B

data_train.loc[data_train[type]==拖网,type_id]=3

2 S+ v7 V* E. K) P- b, _' r7 H

f, ax = plt.subplots(figsize=(9, 6))

& F* H, t: ~: P( ]' |& w/ z8 ]

ax = sns.heatmap(np.abs(df.corr()),annot=True)

, j% n: G) z) I, h0 d+ y- z

plt.show()

4 G7 I1 ]/ [( c ) b2 d) \7 n" h' X' E

从图中可以清楚看到,经纬度和速度跟类型相关性比较大。

/ f' w- k( H, p3 T) { " F0 O0 C7 y% o5 ~5 Y. Z, A7 b7 z) K 8 @8 a' S1 V+ e + [8 W: `7 Z3 I l2 a! W) k; j/ ~
回复

举报 使用道具

全部回帖
暂无回帖,快来参与回复吧
懒得打字?点击右侧快捷回复 【吾爱海洋论坛发文有奖】
您需要登录后才可以回帖 登录 | 立即注册
陌羡尘
活跃在2026-4-8
快速回复 返回顶部 返回列表