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

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

[复制链接]
" {+ [, ]$ Y3 Q. s8 \/ x7 F

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

赛题:智慧海洋建设; `4 b' b# `3 B- c

数据分析的目的:

5 J& U2 }: L/ M0 u( q/ I 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

' S! B: F3 N% w$ r

2.1 学习目标

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

2.2 内容介绍

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

数据特性和特征分布

, T+ [2 ?. d6 j/ L) T

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

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

import pandas as pd

0 @6 N1 A3 |1 g! T: s

import geopandas as gpd

) f& t# r" r' T8 o

from pyproj import Proj

$ u& e0 n' Q8 W& ~( L) C: X

from keplergl import KeplerGl

& w8 h, k7 f5 H2 a7 E! ]* ]3 D: q: S

from tqdm import tqdm

$ a$ {2 ]5 a; [4 G

import os

: x; v% l+ \& e2 Q1 x+ S

import matplotlib.pyplot as plt

# M! }4 q9 p( N

import shapely

9 h, Z- B7 Z1 V7 v' S

import numpy as np

: D& G7 \7 W2 H8 W8 {5 }- b

from datetime import datetime

" N/ i2 V# S, ?2 v

import warnings

) B% p" l8 }2 R7 t& v9 M, d3 F6 }

warnings.filterwarnings(ignore)

" {4 L. K7 f& y* s2 H

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

2 ]! s0 j# E' B, F+ W1 P5 Y

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

U( K3 K, y) I5 I: k& I6 }

#获取文件夹中的数据

3 N; B# L& G% s6 \; |2 `

def get_data(file_path,model):

, ?/ u: I. k' g. T' O( V- m

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

6 Z& C$ S! p6 l6 R# B

paths = os.listdir(file_path)

( g2 h K( [3 M9 E. m/ r3 L) q

# print(len(paths))

7 U8 W& I& Y" \* G7 o* a2 m4 B; V

tmp = []

! K: f2 y! O7 ~2 N

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

e" O8 c* G0 ^- {; Y \ T" n

p = paths[t]

# u a" X- A6 K' Z* @

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

/ b- Y8 g$ G- x) i

next(f)

' q; w# ^! z- I1 k' \& h9 v

for line in f.readlines():

3 l2 B- H9 \ \ V

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

$ v% n3 \9 b) N- E

tmp_df = pd.DataFrame(tmp)

+ E4 W- j3 c! A7 d" x

if model == train:

- X6 k1 R4 l) t$ d- j2 Z, P

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

9 G4 x1 ^+ h9 K$ h5 W, i1 U

else:

2 L+ r( b) Y: V$ R: P7 \5 Z# x

tmp_df[type] = unknown

+ E5 C+ p( B/ W6 K# J; E5 ^

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

# O9 H/ c% u0 ^1 J2 X

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

* w& d9 b y" M9 o4 Z( q2 A) n v

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

1 [ q! I& L# c

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

! E& r+ z4 {5 H5 E, S* u

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

$ r2 J, |( m( `

return tmp_df

; t: ~/ {6 t! ]

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

* ]$ r5 E* R* d& P! s% h" S4 I& s

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

( I0 v% K& {/ t0 B0 G) u* G& s

def transform_xy2lonlat(df):

1 P2 U: L5 D% R) a( q

x = df[lat].values

| a( x2 s8 O% m( f- M1 u

y = df[lon].values

1 V" H1 e; G, \' \7 g

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 )

. }" N4 Q" u6 ]

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

8 i& C; y. [' ]+ P0 b

return df

; O& K' s D! Z- {( [

#修改数据的时间格式

/ x0 o2 _6 |$ \/ e8 K7 Q! I! |3 W7 E

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

+ I9 I& h' ~+ B1 g1 E) c

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

, e5 m+ Q, x# C! w9 l) C5 v* S" x

time_str_split = time_str.split(" ")

5 d8 }4 u* @6 O4 `. ~, a, s

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

+ Q" D& @- ^) L4 {$ v

time_str_reformat = time_str_reformat + " " + time_str_split[1]

) k5 }9 F% `5 a

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

! N( S' m# i& x

return time_str_reformat

9 w+ G$ u1 w+ l' o- t; A4 V

#计算两个点的距离

& v" I' f. z8 I9 w' H2 r$ {' L

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

' n a' W. u5 q) X; o

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

6 x5 b$ C4 F5 [* L: e& D: W

dlon = lon2 - lon1

! w2 ?4 x4 N& n2 Q: d6 Z5 [: U

dlat = lat2 - lat1

% r6 V: Q) q+ `0 V: U! w

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

z1 `6 V ~- U$ I1 N; `. i8 ?

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

( w, N# v& Y5 d ? m( d

km = 6367 * c

! J& r" ^; s. T

return km * 1000

! y4 P O) C9 t

def compute_traj_diff_time_distance(traj=None):

/ ]8 B' h6 S0 T2 N

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

7 ^$ H0 {( c& x% [ o1 O: r

# 计算时间的差值

+ f- |3 @3 i6 ]4 C' A

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

. b" @2 S& x0 z: [2 \5 j. k

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

- c! @- p/ @$ J- p# a3 M8 t8 n

# 计算坐标之间的距离

* I' e+ C* r, S4 Q3 a

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

3 J- M# A c1 A# K

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

+ F+ E6 e* W4 u

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

2 b" i; g+ i$ g, W) W u5 a: {

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

" r3 ~9 K6 x1 M- _- O

)

+ T* _* q' h( x9 d+ z2 x

# 填充第一个值

4 }1 Z+ o t9 n7 }4 I0 w

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

& P1 A% d6 g- D9 V- B

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

0 S, }7 n. C5 s S

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

" Y' k; F; j2 M" M) o

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

; z* R1 U7 v8 p4 I: ]) s

return traj

) D) c" a M7 n& Q; p/ v

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

2 S$ Y6 ]& w8 F' u- P! n

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

5 f3 M, F% g% G2 B. O

time_interval_maximum=200,

% U* \. Z; u* w+ R2 l7 Y1 C" z4 N

coord_speed_maximum=700):

/ n2 D( B. p7 y8 O1 x

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

$ u8 w2 {6 w. J

def thigma_data(data_y,n):

; h* z/ C5 U( F9 }) c; Z- v2 b

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

4 M# n3 B- v/ a8 W: A

ymean = np.mean(data_y)

8 O ^6 _6 E- A7 d7 ^

ystd = np.std(data_y)

2 ~- t- G( _& w' p. Q

threshold1 = ymean - n * ystd

1 q- V4 e0 n T9 U

threshold2 = ymean + n * ystd

8 k, \4 U/ B) E( C

judge=[]

4 k! P h+ p$ @4 `% @/ N f

for data in data_y:

# G7 C8 w1 E+ m$ m

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

0 W) l. U& [: x4 ^1 Q

judge.append(True)

" i3 d3 m/ _( S

else:

/ e3 a& C+ e' ?* u) I

judge.append(False)

: @0 J. J. w' j; K

return judge

3 T/ I* h# E9 g: c& e, _! F) w9 z

# Step 1: The speed anomaly repairing

6 t- G F8 u2 i1 K* Y0 B- q

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

* @* o# X& u: d9 s2 x

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

: p% @9 i, k) S! `5 i9 P4 M: ^

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

( y2 j* C' O' t. U8 ~

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

4 C. n6 ~6 U9 A! q: O% ]5 v

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

* Q* i% T* K4 e& Z4 }/ M. e; s

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

4 w! Y+ j. a( O

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

i. C+ Q% w4 m/ r1 j0 H+ B

is_anomaly = is_anomaly | is_anomaly_tmp

9 d, d- v9 C( n- ^

is_anomaly.index=traj.index

! V- H' J+ }: ~8 s( w* K' f1 h

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

7 e4 l& P- } z& \

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

0 D. v9 a! [6 _+ u, k0 `

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

6 ]5 u# _7 G% g

if len(traj) != 0:

( F% S6 }- T8 i% n$ N% R

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

# G' u+ a: o& X7 l L

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

0 n" p) x4 \) D

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

8 ?8 z. H% Z, g, J w

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

. u6 I3 G' x7 w( G/ o

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

$ }3 U: L d# i% T

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

3 v' X' ^& T/ b1 ]) O+ i: {) J) k

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

2 q- h% V; ~1 S' B0 {

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

% [# g! m7 Q% F8 I2 }8 ^9 V

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

, a# L ?0 u" ^, X5 e1 V4 e

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

* O' m" w- o& n& w

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

" g( J7 n% z, C! c% P/ j" [

DF_NEW=[]

5 R6 w! g6 B2 e1 v

Anomaly_count=[]

) i- ~$ n, a9 f: P) W

for ID in tqdm(ID_list):

& W( q2 X0 b1 r, u6 H+ H7 n

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

+ i, h/ O7 X# Z E' v7 @# S y

df_new,count=assign_traj_anomaly_points_nan(df_id)

0 d; } s6 D+ y

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

' z: m+ [6 G& a

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

7 F8 b6 e7 A w$ P( r

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

) |4 U8 [. P1 G# }

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

0 h4 t: N( s2 g' T, {6 p! R, f

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

" g1 ?, d7 K3 J; L

DF_NEW.append(df_new)

3 d, q' |4 l9 N6 a, u& [+ ~

#将数据写入到pkl格式

& v7 o8 w0 s) W! K5 K

load_save = Load_Save_Data()

+ B" u! S3 x, Y

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

( B1 B1 {3 d) }- X

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

) I! d: M W3 G6 c

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

0 J5 o# L( }3 ?0 I' S: ]4 }

def get_diff_data():

* N0 E7 t, d' Q* Q

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

" k: U o% Z; }; T( e$ w5 N0 K! h

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

9 I2 l- ^/ v2 N3 N$ j' r

total_data = pickle.load(f)

# g. J+ v) L* x( I# i: _( h; ` B+ K

load_save = Load_Save_Data()

8 ]3 z1 M* [! |; `

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

: F8 K& [- A& G, R5 F

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

( Y6 d3 y3 \$ e J* l$ Q; A

for i,datax in enumerate(kind_data):

; _# W' F$ K# Y& }/ \' z0 N5 ^3 I' f

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

& b6 e `+ {5 l u

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

# `( \0 \3 \9 T

get_diff_data()

; j6 u2 {1 z. }5 t

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

+ K/ e2 t- o" \" K) x

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

- S; Y+ X; H+ ]6 w5 Q2 K

DF_NEW=[]

7 g" r/ L7 g d

Anomaly_count=[]

8 u4 W9 f, W2 k6 c: Q; S

for ID in tqdm(ID_list):

" D, k& T. E4 P" N, _

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

4 X$ F* Z2 M- O/ m

df_new,count=assign_traj_anomaly_points_nan(df_id)

1 X3 C0 [( E; P2 Y$ [! l

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

5 a% s4 @' x% z

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

c3 V4 ?# C7 H+ d7 [

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

2 M! g& @" R3 J

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

' B. G/ x5 q$ }) [3 M3 x j

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

) E! T9 Z0 x/ Z, \ B8 _; U( E

DF_NEW.append(df_new)

. r- Z' Y# Y! K! B

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

9 T, G! n' E H6 \+ O) v' Q

def visualize_three_traj_speed_direction():

) Y q4 r" ^% ` C/ ~8 A G& }8 d4 O

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

5 \4 `9 v ?. W5 o" M# G& \; d

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

% K% F) Z9 ?: S) K- {

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

1 a- w+ w8 c) A/ F! t! P* F

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

3 m# @% h8 ]# O* x. T5 C0 m9 w6 ?

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

. l* Q# J; y' E2 Y/ G

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

9 x. {# s6 ^. D/ h2 A; J" N

colors = [pink, lightblue, lightgreen]

^1 `$ ?/ P7 a, K- z0 K; W

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

7 u2 W( G$ j# Y5 c

datax = get_random_one_traj(type=file_name)

4 ~- S. |: ^9 f2 X

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

`% K! |0 b7 f% G( s

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

0 P4 \. a* o/ c/ j6 p1 R+ ?

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

. F# Y) Z* o/ B5 n9 A

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

/ X2 q& }% r; n+ v8 w2 A( v

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

# E$ \+ U2 i9 i

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

& j5 A5 Y' r2 c# J( v) Y

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

/ D V' d- L2 @& j% ]6 Y, n

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

; ?' q/ k9 Q) _4 O& g* C

plt.show()

- ]" f, ]$ g6 J8 {" t1 T& a% J5 D6 F5 t

visualize_three_traj_speed_direction()

3 z9 r7 i2 a9 i
" i! c9 n q2 @6 j3 n; [

作业二:相关性分析。

4 @; d6 c4 M9 {2 R# L4 O6 }, d

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

( G ` ^ d2 Z0 t

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

+ k. a' G. \* P. i) Z4 T- l

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

6 Y$ U ]% @9 ?$ M2 O+ q) F

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

( f& \- \2 L& r7 B

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

, [5 Y% U4 N7 t+ x

plt.show()

7 O" f! n. k' g0 d 5 U# I/ L; W, w( A

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

8 x3 j% q$ \9 ?$ [+ F + m: z2 y$ ^5 q- P x5 ~7 m+ s8 `( m " K( k- p1 h* @/ ~' U6 L * o0 ~0 h6 p% K ( }8 F3 ~4 e! G2 U: c3 i
回复

举报 使用道具

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