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

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

[复制链接]
1 B$ g4 S) {; A2 E1 h

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

赛题:智慧海洋建设 ; T, G, d4 t- e# |2 ~! u

数据分析的目的:

" \+ v" E( P9 ^3 ? 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

3 t2 n( w* }7 S V" D& c& {

2.1 学习目标

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

2.2 内容介绍

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

数据特性和特征分布

8 r0 i8 z$ H! N5 g( Q7 p% l

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

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

import pandas as pd

% n$ H3 _. M( }8 Q8 R

import geopandas as gpd

$ N7 ?. v$ U9 D. o7 t! y2 U% g1 g

from pyproj import Proj

3 |* d. l# ~5 @

from keplergl import KeplerGl

9 S' B; v1 I4 h

from tqdm import tqdm

3 f% B- s0 e9 y4 ~) S/ D2 Z8 {9 z

import os

$ u2 I/ Z) B. M3 g, P: r6 Z% ^

import matplotlib.pyplot as plt

) V9 S5 T) b5 o+ z$ J! \

import shapely

- x3 t! B, k" W

import numpy as np

& q0 l6 d# `. u

from datetime import datetime

* P: y5 f; A9 P$ x5 W

import warnings

6 o( U2 W. `$ k B; B7 u- `" Z; w' n

warnings.filterwarnings(ignore)

?7 k5 P, j+ W {# [

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

. u4 j, c* H+ O7 X; p

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

, a, }1 ^5 D" c( r3 ~& n

#获取文件夹中的数据

* n) B* w- X, h) M+ z

def get_data(file_path,model):

1 T) T6 Y ^6 i: c# c/ g# A# r

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

' _0 p' F1 M7 v- l

paths = os.listdir(file_path)

U+ O) d: g( P* m3 n

# print(len(paths))

# Z- ^/ k& J/ X3 R9 L

tmp = []

8 i* ?$ B! H9 i1 a r* H

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

5 P3 H& |5 y& i$ g

p = paths[t]

& h2 k6 r, A5 {) ?8 ~" {; E

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

; u' ^1 L, M$ X8 r; K

next(f)

* b5 z7 Y/ D2 U+ K* X; _6 @

for line in f.readlines():

9 K2 A- ~" o/ Z" @3 s- P

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

7 O& y8 i& M. X

tmp_df = pd.DataFrame(tmp)

8 C& l5 y1 E) ?0 d

if model == train:

' [; d/ I8 C9 M- Y

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

6 x9 a7 W& k0 P

else:

1 k+ `0 A5 w- P

tmp_df[type] = unknown

! _% H# D) z: |1 r ~5 ]

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

. l6 B+ u% Z" y) P6 b5 ~

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

/ ], }/ x3 Z. ]$ A1 H* N& S

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

2 l8 k4 \& M0 U F

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

7 g* c; u) `& [: \1 n- G. ]% J

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

3 o2 ^* b: j2 N3 c* N8 U% o

return tmp_df

% n' X, p+ j& ?' h; ~

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

5 I0 W C1 p% ?' _

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

+ I3 f! E- N, h0 g

def transform_xy2lonlat(df):

- r p+ S% e& ]5 y( M4 ]# O% p6 c0 ?

x = df[lat].values

; K( m1 b$ S( I, H) ^/ h2 u; G9 k

y = df[lon].values

& V( {- n3 v7 R& z- u- F# U( q

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 )

( U3 ~" l" T9 ~; Q9 X/ f( m

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

/ \- D+ t) ` u3 [7 p. g2 l% A& C

return df

: |0 k$ z2 w* i, A7 B( g

#修改数据的时间格式

9 h8 }. G) p; D% \* J5 a" e

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

2 [2 i. M* }$ q) L7 C

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

% U+ `( H. i5 |, b

time_str_split = time_str.split(" ")

& p; `% r. H8 H6 g- V

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

6 a: c3 y n; D) N4 @1 K

time_str_reformat = time_str_reformat + " " + time_str_split[1]

, A( X+ F1 {( B% t7 b) @1 h: q1 A. {0 ~

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

, w7 a+ q- t: `

return time_str_reformat

" L- i& B) t- E5 J

#计算两个点的距离

& f$ t$ R& ?% @+ ^

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

/ L8 ^# F" i3 ^

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

0 V" ^' a4 T# ?3 t* `5 q

dlon = lon2 - lon1

& y& _; ?+ C3 O6 \5 ]* U

dlat = lat2 - lat1

4 c8 W5 ^# V' i4 ^: d1 j5 o9 X

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

2 A W X2 o7 d2 R

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

w+ Z) q% i: T! }! m; s2 A' Q

km = 6367 * c

4 t9 u" {# R4 }

return km * 1000

: z8 \7 U/ C. ?$ S' o0 c! F' R

def compute_traj_diff_time_distance(traj=None):

0 }8 H5 d1 {/ A G. m

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

* u* R$ D- ~( ?5 @

# 计算时间的差值

( Y% r3 K1 _% V+ x# G; u$ E& }

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

8 ^! u, Y! X; N2 h* y7 U8 R

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

1 b9 U- p/ [+ `7 f: B7 t: K8 Z

# 计算坐标之间的距离

* {/ }7 t6 R* z% _, n

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

) P/ `2 u7 _3 P* H( `

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

+ {, h4 Y( q& A0 p7 R

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

+ I( h9 R6 v4 x3 y" a9 G2 z

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

( r( d U e2 D; d* {' S) `: x

)

) r1 I% s8 @; @2 u

# 填充第一个值

8 [' B. x1 z& \$ L: h6 I# ?

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

7 G, R6 [" E$ l

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

' K e( b* V2 S/ R+ K" }

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

; t' m1 k( A9 u4 g

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

a5 o' P7 u8 M' @

return traj

9 P8 o- Z0 g# h& w% @+ q) Q; O6 {" z

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

+ e2 O' X4 T( ?3 j+ T

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

* K/ |( E, q, s5 M- C! o

time_interval_maximum=200,

8 i9 l) V' y3 ~# Y8 I

coord_speed_maximum=700):

! g1 r. s1 w9 y# m" b

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

; y- d+ T/ F! \+ m+ C- D* J# L

def thigma_data(data_y,n):

) Q! k5 ^9 d, O7 C3 c, v

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

. W# X0 w, _; |' W0 A

ymean = np.mean(data_y)

9 l+ D$ V. k% E. }2 j

ystd = np.std(data_y)

% d! A/ ?: Y$ D8 V+ M" E2 I) b

threshold1 = ymean - n * ystd

* A' X7 Z. a& N2 w1 j

threshold2 = ymean + n * ystd

% T. c5 S2 W5 m) h) p( G

judge=[]

' Z5 V* ^, {% H5 ^6 {

for data in data_y:

; }) I# y! Q" m+ L

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

# N8 W- N1 f2 p3 H& e7 R r

judge.append(True)

) W! k( Q+ e$ T# J

else:

& j+ |& F2 y4 s: M

judge.append(False)

H7 o: b8 w8 P' z8 J6 g. N

return judge

! d2 x& }7 r& c% j% } P) b! D

# Step 1: The speed anomaly repairing

: `# K+ C( M# G$ g4 U

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

/ e* g ~6 Y5 s

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

% W9 ]" ^3 S; k3 G# j2 F

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

' _* A$ k5 e e* X, _

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

; c* t9 V% Q/ s4 d( C

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

/ n% ~' i3 D, Y5 t2 J b

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

d: R! L& s% t2 M9 Z' f4 M% [

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

( g; S6 K, U+ u9 s

is_anomaly = is_anomaly | is_anomaly_tmp

& C% z+ @5 A( }; _4 t2 x& L8 w V

is_anomaly.index=traj.index

! z' K) x6 X9 o- [, B

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

' h" }1 z3 ]* B* i% k2 L% J& E

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

~* }0 ^, o$ g# W5 g

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

+ V( q! }) }2 G2 {1 [

if len(traj) != 0:

- U" u( m+ Q& P* _- ]; z& r. w

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

& R4 D! ]6 @5 Y- l9 Z1 _( g

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

& y9 l$ p$ r; a8 l1 C8 ?+ t5 R

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

: x- r8 ^; X0 Z" f# \

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

" W* g/ r, O, \1 p7 Y. e. F4 @

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

9 j& }3 R. t" t: x' Z

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

% v) I. e' u/ `6 v

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

) s U% v3 K0 i* V

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

# L0 c1 Z8 d) @4 W

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

% z# `) s0 A1 o, {

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

. g: _ T q: v0 S

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

, h" c9 b4 [5 H+ j1 V. U: m

DF_NEW=[]

1 T% q) L2 N* h" i/ `# Q

Anomaly_count=[]

1 t9 T) z f7 ~1 H: ]& E3 t

for ID in tqdm(ID_list):

5 y6 A5 f e' p/ K1 N" `8 U

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

u# `! e. d9 l, N7 Z

df_new,count=assign_traj_anomaly_points_nan(df_id)

& I5 d+ u8 A& G( x+ G

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

2 p# a$ Q0 D3 I# \) x

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

" h6 m3 g, W2 {: {4 D1 l

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

& }% n' S& P& ^

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

+ L5 U$ w0 e; z# X& \( h3 ~0 O4 z

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

5 u$ c. N/ i3 Z# _' w5 V

DF_NEW.append(df_new)

/ ~3 q( a2 A' E( m+ e

#将数据写入到pkl格式

+ A+ y1 i# K- r$ Q7 E

load_save = Load_Save_Data()

) E6 ^+ \ d/ a; b- t4 M/ E+ Y

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

7 o* M1 w2 z0 `& A! D* c$ w

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

% d7 d) P9 D. ~$ [! V

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

" S& K2 u/ H. C9 o) {: S+ W

def get_diff_data():

3 C6 U9 \: n; x: y

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

3 l% O( H2 Z w) [6 Z& a2 Z

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

9 m% Q9 c3 X1 t E, M

total_data = pickle.load(f)

2 @ {7 O4 |' I. l5 f7 m" f/ v: H

load_save = Load_Save_Data()

, q* l' a9 y* X1 x" I& p, ~

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

6 K. L! K/ A& m

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

1 j$ C$ N% t; T

for i,datax in enumerate(kind_data):

O: c( X5 M: o

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

4 E+ S v, M4 m. X0 c

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

4 N. [, A9 M1 o# c; I

get_diff_data()

+ R2 L. F. S+ d

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

9 H" T& F3 O% O& g' f9 G: i y

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

' x( d+ ` z* g0 `2 I" }6 z

DF_NEW=[]

) B( }" U3 |8 t* R

Anomaly_count=[]

: ^ j; F' p! M6 u1 g

for ID in tqdm(ID_list):

1 n7 n+ Y& F' w( U3 D

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

- |/ U; T1 W1 Q% @1 n3 A: [6 U

df_new,count=assign_traj_anomaly_points_nan(df_id)

2 ^6 j! n& L+ j) `; B' q A* b

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

* A7 d: ?, i" }4 I! G& U

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

; G$ T! |% X- ]6 n2 Z+ `5 t

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

) ~, w) ^. ?6 e

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

5 J3 I5 {, D Z1 d. z

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

5 }& x7 p0 K( B- F

DF_NEW.append(df_new)

( x3 j+ `9 t0 \! U4 W, c

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

; Q/ P( v6 p2 R8 G

def visualize_three_traj_speed_direction():

; ?) C' d0 k% h) Q& ?

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

2 t& b+ ?6 j+ ]/ l' }; @% G$ ^

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

! J" Q6 x" R6 O

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

. A+ v1 G9 r# b7 F

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

, t" t0 q9 y& w: ]+ i; A1 T- L

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

) l; X1 P5 H2 U* H) s

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

2 [7 p% @) e9 ^' h- ^

colors = [pink, lightblue, lightgreen]

1 j2 B9 J7 r! Q& W& C& k

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

; w- a* V7 j: S: k

datax = get_random_one_traj(type=file_name)

) v% e0 B3 ~3 r5 g- f. O

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

$ m* D1 B7 U; Q( m# F

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

( ~% o0 b6 C) x

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

: Y H/ I" I Q; J& B& p: h+ F4 O2 y

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

$ ~: s, s( m$ s7 P* v" n- U: ]

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

, Z( [+ K8 X0 w2 h! b- d$ o

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

/ y4 B, |7 c$ {0 s: G$ ?- u7 d

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

& x* z$ B# \7 W

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

: A% J: o) i; U# P3 \: E/ o. R

plt.show()

& `8 h5 O% h1 C3 P# C+ v) _5 J

visualize_three_traj_speed_direction()

, }1 \; ]& Z) o& F- f6 L" D
! O8 k0 X8 p0 A* U4 j1 y2 F: d5 U: S

作业二:相关性分析。

6 @2 K3 J: D- v

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

: g/ h6 {8 D( i" H* I2 T$ s# C" l% `

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

6 X' P8 M( r) R/ l% _

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

. c$ H3 q5 s% i4 b: K

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

9 b- k4 b; Z: N3 \* G* x9 }2 c5 S

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

8 `. d+ X& u0 y3 y/ j

plt.show()

* h+ }% k& O4 [$ b8 A9 L$ @ 9 q4 A( J3 T% U

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

1 x2 d' P# K, n( H8 C 9 c( X" Z# D' p- D' U 2 F1 q/ R; M! B0 J / c {* T) I# u. J, v + z, P5 y! x4 q0 }4 K! ]8 ^
回复

举报 使用道具

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