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

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

[复制链接]
# W0 D4 V0 W# O2 g) [7 c E6 X: h

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

赛题:智慧海洋建设4 a% Z: y1 }6 |8 K

数据分析的目的:

9 u- l' [0 A/ S+ @ 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

; B8 @3 G* D, }) m) H5 Q" y9 D! ?- E

2.1 学习目标

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

2.2 内容介绍

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

数据特性和特征分布

' G% l% \/ I' v3 {

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

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

import pandas as pd

; P1 F% G0 `3 j+ n$ n

import geopandas as gpd

1 R. P$ Y# I+ v2 d3 h0 e3 s- X

from pyproj import Proj

# L8 g3 I) k8 a8 _5 d% J/ u8 m$ o0 x

from keplergl import KeplerGl

! W0 S7 I; a4 [* {8 n; o4 j- G

from tqdm import tqdm

; H+ F7 \% ?0 ]% D& p

import os

8 T6 e9 N3 j" H1 ^

import matplotlib.pyplot as plt

- o/ e4 L5 {5 n

import shapely

; k3 o( Z6 k: h8 _' b! k2 v

import numpy as np

) s# w7 U5 c) z8 ^+ |

from datetime import datetime

# L6 u$ q9 {8 G6 h9 R% G

import warnings

; r: o# w; h7 [" A) C

warnings.filterwarnings(ignore)

' M% ?" [( m9 j$ M- Z3 ^$ B4 L+ k

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

( X/ `' N* |3 i; t; ~: A5 R* M

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

! s/ Y" m# ^- t; V7 E

#获取文件夹中的数据

/ t" ~& x1 {2 E }2 O

def get_data(file_path,model):

+ R' @* x8 e7 E2 a& D

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

$ C) j9 w5 A4 |8 ]. U+ D4 S7 @

paths = os.listdir(file_path)

2 q! N3 e6 x p6 V

# print(len(paths))

2 [9 }, s. Y9 |" q, v

tmp = []

: J1 z" k* `" {% u6 w& r

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

4 H# J' Y, h2 [6 |: m* e3 j

p = paths[t]

1 R: C& u( G# L. ` X

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

0 w6 u |$ o6 |8 `% G+ S5 `2 y

next(f)

9 M$ p* ?) x6 [( B1 m

for line in f.readlines():

. Y* y ^; y8 _, f! f+ N! d

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

' x L1 z1 q$ B

tmp_df = pd.DataFrame(tmp)

, x, p# u4 i7 _6 N7 w; P/ a

if model == train:

) i' J- ]6 `( X2 j( L9 u

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

1 ?& W6 z6 \8 d e

else:

' A- k8 k3 @; s

tmp_df[type] = unknown

8 G$ H, \$ T1 \; d) I: E1 G. f: g3 V

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

1 k! l$ B- ?6 k6 j c. t

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

; s* I+ p/ f$ U9 h% q. w

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

7 P7 }' X0 `* b! G, l$ b0 K

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

+ s# B7 p; l8 ?" H& i, ~. r

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

, T* o5 u, J7 D" Z; K" T$ ?; I' q

return tmp_df

2 D1 ~. Z* ?. G5 w% q$ T2 E

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

5 z0 q" l2 }" r% M# q5 E

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

% P" q6 V" z0 _5 I% X" @

def transform_xy2lonlat(df):

/ o1 f# {" A; c9 x# C; H. J) o( p+ m

x = df[lat].values

% R/ @7 E3 r0 q6 o" x2 v

y = df[lon].values

. t: I ~- U s+ l& [9 `

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 )

5 H6 V k& `& d$ F* Y E

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

$ g# A3 U( W5 L; B6 J! F

return df

2 A3 y( ~+ L9 F: l8 J/ Y

#修改数据的时间格式

( V% j0 I0 L+ ^) B4 c

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

- }# Q* ~+ X- J8 p$ e' n

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

. Z- s$ A0 K; @$ F/ M! \

time_str_split = time_str.split(" ")

( K+ |" c. C" q$ ^, U9 {& D

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

* j' J- t8 ~% s( K0 r

time_str_reformat = time_str_reformat + " " + time_str_split[1]

: d. S6 W! s# `: d

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

$ V- t7 ^* v7 P' T

return time_str_reformat

5 M8 R i& G( w1 z2 c4 D

#计算两个点的距离

0 F( J/ `: H( b1 _

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

K# A+ f; a. L/ ?' F

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

# p. F9 J0 v- t. V- F

dlon = lon2 - lon1

; G) z2 o- j; m5 X% x, E) }) H

dlat = lat2 - lat1

2 c" N+ b2 t7 f- }+ O

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

/ b" p- ?* l# @# C

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

9 P0 W+ z2 M& Q+ E# J5 |" U# x1 S

km = 6367 * c

g7 T% @1 X# z/ b) z2 |

return km * 1000

& S) O, B* }3 _7 Z% r

def compute_traj_diff_time_distance(traj=None):

5 D& Z) S' _; q2 U, C; w; H. J

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

6 C* z! Y* {$ a8 O

# 计算时间的差值

, _4 v/ Q% L# i3 F4 M8 E1 X

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

- f( k' C$ g( j: d# C

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

9 D$ V& R2 i3 _/ d l, Z4 l$ ]

# 计算坐标之间的距离

2 t6 \$ I) \: q3 [. r

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

3 n! O( z4 W* P" g

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

. G6 ~9 r2 |# [3 g {8 Q$ C! p

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

% u: q! `+ s7 m# I

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

7 j9 C# u6 w" l9 X2 J: {

)

( ] I7 z; s, @6 E. x. {6 n

# 填充第一个值

+ I& n' P" @: @! C

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

6 u. N. |0 J2 [' F9 J% l

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

: P: d: W4 d3 w! k$ z% K u

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

1 G5 _- T6 f* b: Y

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

# w- R m& d0 K" l5 D- G7 d

return traj

4 }/ O+ Y% ]0 K3 a, }1 B

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

8 C* g2 Z9 _, J" j4 P9 g1 G; Q

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

8 u% H5 C+ ], B: W

time_interval_maximum=200,

$ u6 E/ m, Y9 s* C* M

coord_speed_maximum=700):

* c6 A/ P9 h7 V; L8 e- J% N3 E

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

" @ ~% P! D' C, ~7 \9 h

def thigma_data(data_y,n):

9 N" z; G: M/ v) M

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

8 p* L+ H8 P9 x" s7 i* V

ymean = np.mean(data_y)

^, p5 f, C$ B* v2 F/ W, u

ystd = np.std(data_y)

( _4 x9 N; B- ]7 v) V1 z, W3 r

threshold1 = ymean - n * ystd

* d/ L8 e) c' X8 A! z

threshold2 = ymean + n * ystd

' b$ ^% b7 r6 x. _5 J2 ~& N: ]

judge=[]

8 v8 P* C$ w* P% {7 C

for data in data_y:

: a. ^ S5 \6 n. f

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

9 k- D" B; N8 |+ ]. J+ F" M

judge.append(True)

2 g) r0 i4 P9 `9 b+ C$ P

else:

0 `: @. g3 o8 Z

judge.append(False)

% }' C1 c% |* }

return judge

) r0 s3 i: ]0 M5 r, o! l K$ k

# Step 1: The speed anomaly repairing

5 Z7 k% v, s' {1 |6 _& d

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

8 ^$ a }3 w2 ] U6 c, ~* U

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

+ E/ C% I( l' V, R

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

! n4 t; i( y. e3 T2 R

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

6 O- b s& T9 N

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

) B7 Y; ?: Y* H5 H4 r, _

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

! \( I! B9 b# H# `' H

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

. c# M" K! c+ K0 k. |

is_anomaly = is_anomaly | is_anomaly_tmp

u% j5 [: \; L2 d% S) _

is_anomaly.index=traj.index

+ v7 ^5 l( t7 M/ J

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

! O" @6 b* U- l" b' _$ P6 d& [

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

+ Y, ]# o4 } F: w4 @: g& g

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

- `6 q+ l1 `" x c( W8 X6 g6 H5 W

if len(traj) != 0:

9 L M8 k! ~. q$ V2 ]

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

* E7 G/ _6 q$ Y2 V

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

1 P6 |: a9 U3 ?5 L

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

9 }! F' }- f7 u7 Q. T

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

) w2 }* ]' \8 v- A$ o& l4 ^- f

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

0 H4 x6 I" M4 i, p e

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

8 ]9 u' W5 o- j% f

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

* e7 i3 O! [* O$ q, r/ R7 M

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

" x+ r. G/ ~" K" f8 ?1 b; j6 l

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

& I( v8 M4 L' m3 X

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

0 G# y' ^5 f' d8 _# F% y7 Q/ `" s! X' G

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

7 t# x( J' P& F2 M: W

DF_NEW=[]

1 i% H8 r- E9 R% F! ]4 q' w2 h" w3 W2 A

Anomaly_count=[]

3 _0 z8 R: _* y0 G

for ID in tqdm(ID_list):

# s" {! X$ L7 ?6 S$ ?5 E$ N

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

- y0 s1 ]4 |9 }% k2 P

df_new,count=assign_traj_anomaly_points_nan(df_id)

5 {. u/ B; \- G. S" W

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

- ^8 M) @2 a% D/ Q4 E2 X

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

! Z* I b8 V' b* N

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

5 G" f) r# N6 o8 z; V" v1 K7 K

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

' r$ x/ _& }/ w% G9 x( C: P* _

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

/ i! p* C2 i8 K( q- ]0 `3 x! m

DF_NEW.append(df_new)

7 T9 x; c' ~, K4 ]

#将数据写入到pkl格式

" M# G; E8 r8 G& F4 C+ {9 l. m& v. {

load_save = Load_Save_Data()

4 v1 F4 P: ^; P. ]; W

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

' ?% O; I' r& s" n% }

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

) F, Q' V( ~8 q c

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

2 O) k/ D" W4 X

def get_diff_data():

. p8 \! j+ W7 ~- F; S

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

% v- x7 g" t% \ j

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

7 t0 ?7 \" l, B; e g! K

total_data = pickle.load(f)

1 P* V: G+ h$ f4 \

load_save = Load_Save_Data()

) }6 F& G0 d- q9 n( p: X3 N: `: e

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

: Q& G$ |! Y& |5 \/ j

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

+ C6 }# }5 ?- ~3 ^

for i,datax in enumerate(kind_data):

& y7 w0 ] M/ G) b9 v

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

X: o& a9 e- J5 T$ {$ u5 _8 Z+ r+ ^

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

* B6 n/ T+ |* k* h( f0 [5 |. |( g

get_diff_data()

# b$ J W; L+ l1 P; a

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

/ T9 q% v! N9 I8 Y# \- R

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

0 y" a( x+ m8 Q) q8 ^5 C& r

DF_NEW=[]

8 c/ E7 B2 C. q/ B0 r. `

Anomaly_count=[]

, s, C. K3 b/ y: c1 z; K. U

for ID in tqdm(ID_list):

1 e2 E0 ^ _3 |' K8 _$ _

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

& H5 r1 _) R2 j, P

df_new,count=assign_traj_anomaly_points_nan(df_id)

1 e6 |6 Y! o! N u) _6 o7 l

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

+ Z2 H! N, l7 Y* _. R

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

8 }! ^" ^$ [1 j# [( D; b

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

" W1 ^" T7 H1 f7 F |4 S' Z' E

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

) G" m6 |) n4 \

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

; q/ f3 j& t! M6 q5 Z- W; x+ u

DF_NEW.append(df_new)

4 d/ P6 K* Z& V4 H

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

) h" ?& G2 b) K& @

def visualize_three_traj_speed_direction():

" S$ t( d8 r) D' ^

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

; X- w# }, @5 u" O; e3 K8 r' P( E

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

* V; F* w: e. `8 V/ z

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

9 O& D% w- |% e- |; q; B8 V

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

/ Q8 P* ^3 |' Q% h3 ^ j7 d

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

8 M, U- v' r* x

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

) t* W$ C9 a! B

colors = [pink, lightblue, lightgreen]

% l% w7 w6 u% v0 y" m

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

# ^! b, O+ h5 A

datax = get_random_one_traj(type=file_name)

. {: w7 V5 x/ \: G* o* N4 _( O

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

, A5 F4 }0 ~3 L( m+ R' p3 |

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

1 j$ f' Z) F7 |1 t6 N

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

/ x H3 s( z; d# u

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

8 V0 {# E/ {- i/ w

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

8 A- ]+ r) o; A: E/ |. t/ X1 A

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

! `, ]; R+ Y9 X, _1 t3 O5 g7 Q

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

) c3 ?" [6 O+ l* p2 w$ r: M l

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

: ]& f; \; s' ^' I

plt.show()

) t2 C% O. x# d

visualize_three_traj_speed_direction()

6 \: o& K( Z& g
! I! D5 w! i5 m) K2 s

作业二:相关性分析。

. ] Q' [9 W) f1 X! a4 S

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

! h0 h6 ^/ T3 ^6 H2 T

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

+ J' n' Q B7 s( {3 R

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

. G( f1 S. T" G" u) c- _

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

a. x/ h3 h& g: n/ w& @+ o# W

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

8 B) k/ Y! I: w7 f v

plt.show()

, q, B2 X! f9 O! D; ^4 J. J* D 7 P( d ?) [$ S/ Y* E& q8 e1 h

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

0 I# e& N; k7 k& j' `' ^, t: d# A# T2 p1 E $ N" p( _; J2 o5 X, I" m9 s$ h/ O0 x5 q5 J 2 v# _+ _ ~0 d, U( j! _. M' n
回复

举报 使用道具

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