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

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

[复制链接]
1 ]- J ]& q' O% W" g7 g8 ~

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

赛题:智慧海洋建设 4 ~4 h5 x$ ?3 H

数据分析的目的:

9 D: x1 l" z. ?( W 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* W0 r; M- j" p

2.1 学习目标

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

2.2 内容介绍

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

数据特性和特征分布

! B9 a9 w' ]1 B' l

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

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

import pandas as pd

% d5 Q' T2 i2 O. N m3 p/ X

import geopandas as gpd

' a% V# z+ J3 U

from pyproj import Proj

! ]% g* s3 Z4 F5 }5 h( J* K

from keplergl import KeplerGl

5 S4 U; U$ G9 ~6 k5 {0 h

from tqdm import tqdm

% Y" S5 [ h4 i6 G* z3 @4 h

import os

3 U) j6 o/ j3 Z' g. f

import matplotlib.pyplot as plt

' E; D* H, s2 L5 s( u' Q0 Z

import shapely

2 J9 ~% y* z0 r7 B: o! v; N

import numpy as np

/ s* o) B* }1 k. {0 Z) z0 o( y

from datetime import datetime

2 L, u0 b- I: Y* s

import warnings

" n; Y' {6 _, n

warnings.filterwarnings(ignore)

/ N- @% N3 y7 N- G8 V% v

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

7 T& x( s8 \8 h$ A4 j B

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

& u) u H2 z& ^- }

#获取文件夹中的数据

4 \$ ^- I5 X8 A4 h/ B- W# l' G

def get_data(file_path,model):

- b+ w8 G* x7 o# c

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

' G! _- z6 F- G% d

paths = os.listdir(file_path)

, Y8 s1 C. r$ |9 c' |% D2 `

# print(len(paths))

; A( b$ I+ }7 Z3 E) k

tmp = []

' f, Z- w/ q3 u; u2 [7 i9 l* L' w9 y

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

5 k; g8 h# T3 }. J' G3 a# N8 H

p = paths[t]

; |4 J$ s: f2 q' I" q* h2 o5 `

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

5 \ p% \& A3 P. T

next(f)

5 I v) C+ d( X

for line in f.readlines():

' Z7 N- d/ ], y% J

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

& l! p" D% v. i1 }# n2 b

tmp_df = pd.DataFrame(tmp)

* @. d2 ^2 v! O6 P( N

if model == train:

; \* @: Y }8 ?0 X* \

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

% T6 a5 L+ e5 H1 @: c+ U

else:

, G0 j7 b. d2 j5 @% x$ O

tmp_df[type] = unknown

0 J- I( r* h0 D8 P

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

0 S2 B/ b( X- @5 ~2 S# q

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

; g' B) p$ b6 m

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

: v8 Y' j. d* q8 S* W

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

$ N8 M- G$ x# v7 {9 n4 `2 R

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

4 Z% r+ L" x2 {; s) F4 i

return tmp_df

( {0 \- |$ y( H5 B" K' F/ q' p

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

( X) @2 A4 ]& [3 ?, F: z Y

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

4 R# {* h5 A) l7 E& ]2 z2 Y! \) @4 \

def transform_xy2lonlat(df):

$ E n5 o( B* O2 }. _1 Z: S1 @1 S

x = df[lat].values

- b* }" e5 c6 g) _$ I" J

y = df[lon].values

) ^+ J% Y5 Q7 ]3 t" H

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 )

0 B2 x" t. a- I; X1 f- n

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

9 x7 P* p7 K6 I8 f9 b$ I9 Q7 N) e2 y

return df

1 Z# n. f$ W+ d

#修改数据的时间格式

) P1 [, B, h6 ]/ O9 E

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

, E8 Z3 S) J9 k/ B9 g0 H% G

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

5 z. n4 T+ f* z. e2 Z2 e

time_str_split = time_str.split(" ")

& a3 F2 F5 g, P9 ~9 X# _ b; j

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

6 ?8 n1 ^; L$ d0 T$ d

time_str_reformat = time_str_reformat + " " + time_str_split[1]

! {" c7 F1 A2 ?+ ]4 N5 R+ a4 a% y$ A

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

A0 l0 h$ j8 \

return time_str_reformat

8 K# v( S: p1 v9 Q/ L' Z

#计算两个点的距离

/ r* d: Y( n) s1 l, G

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

) n+ V: u9 F- r1 Q: X R

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

8 O+ f+ u2 o5 v

dlon = lon2 - lon1

' u* T6 t- i& c6 ~2 K9 P$ M: T

dlat = lat2 - lat1

3 l q m0 Z5 \# x3 C, q- U! a

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

1 T, Z- T' ]) T, V' g, T

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

V; n/ ~0 y% P$ N! x0 r* Z

km = 6367 * c

, ^ Q. S) T) w6 I7 R4 G5 z

return km * 1000

/ M( S+ f/ \2 ^' c

def compute_traj_diff_time_distance(traj=None):

" o) K0 J) j2 t$ Y

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

# j1 f, }$ o0 F

# 计算时间的差值

& Q6 m8 g1 K. K7 n

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

- _+ e/ F7 d7 | y. G( X; W

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

$ a g4 q b# X. K O% i

# 计算坐标之间的距离

$ [3 }+ B# _& K' e2 x7 t( r

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

6 M* ]0 v* h! T6 {; [; Y

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

: a5 W3 }9 N# V) k& T% B

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

3 {9 n5 J5 K2 Q* d' e! Z

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

3 h& Q7 {4 h8 M9 u5 U- t8 f& u

)

9 D" i0 r4 J1 P5 x0 |9 b

# 填充第一个值

$ d+ S" R3 h3 I& W- N, a( o X- G, p7 m

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

2 i0 g8 v$ z6 l. }2 N8 P

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

) p# f8 l; F; c% p, ?5 b

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

2 w4 g+ {$ a# g+ n

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

: u8 V, M! Q% t

return traj

% I3 ^% e& D, }1 p

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

: A$ a9 ?' |2 v5 Y5 a S |

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

2 k$ j5 D; R2 n5 m7 \, N

time_interval_maximum=200,

8 G U' Z0 l. U2 ^% E

coord_speed_maximum=700):

9 j7 ]' J2 R, Y7 q5 l

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

; q" d# g" M6 d

def thigma_data(data_y,n):

# t9 o8 C1 v- M* M& D5 d8 g2 L

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

b9 W6 \2 ~& h6 |) D( S

ymean = np.mean(data_y)

0 G9 i% V' J4 G. v0 ]) _& q

ystd = np.std(data_y)

9 h) V* R3 \% X# `% d3 f

threshold1 = ymean - n * ystd

/ j1 {7 [% p, h: l) }* t

threshold2 = ymean + n * ystd

, x5 u. f* Q3 N r; v7 `7 f

judge=[]

4 A6 R K2 J% t8 a, s5 U2 L+ J

for data in data_y:

0 X0 ^" Y- B8 d5 ?6 I4 v' i% K

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

) x. ?0 h& e4 w E

judge.append(True)

- Y$ v3 a2 r$ y1 K+ u

else:

7 H+ r2 `9 [" t; A0 k- ]) B$ n

judge.append(False)

+ T9 l0 F" S7 q$ r/ \

return judge

+ F& D1 L/ O( @$ z! C$ f R

# Step 1: The speed anomaly repairing

- R9 W; Q7 g7 I8 C \

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

$ S+ B7 J. O" s7 ?2 q+ }9 Q4 a; N

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

9 ^- D: k4 v# d- B0 d6 ?5 Y

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

/ k) a/ y2 G/ Q8 g

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

) ~( n9 ]2 t8 j7 ?! G% X

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

5 ?" K3 I6 T V1 ^2 @% B

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

8 g' k) |/ h) Q) N2 C6 m

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

' b% A; X; Z3 @+ v; P2 O: t

is_anomaly = is_anomaly | is_anomaly_tmp

( h) \2 R6 X, e, p9 Q' P

is_anomaly.index=traj.index

8 L3 g& W& p9 V' }, J- _& D

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

! C W5 C# w3 Y5 P' Z' t- t; Y& J

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

+ @6 h: y4 A2 q8 c3 X; }3 Y

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

/ E: i M8 ]1 i9 a

if len(traj) != 0:

; }! r7 Q# O8 U" F. t7 A

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

/ X0 y+ g* Z4 B5 ?8 L

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

2 X( h" L. ~/ Y: {% U( u, r% j* a

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

0 b) K" e+ _% |* f& v1 f$ T

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

9 M- X2 W/ ]' h% P$ h

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

* \* J9 c, Y, t0 U6 L

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

1 t* s1 s- n7 o' S9 V, w+ o

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

4 m7 K' k6 T6 U6 |6 W

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

0 f7 G7 x2 b+ Q9 `, b# k

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

* Q- K" U# [! E, Y1 u+ A

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

0 V6 u8 }, \7 F& {+ {

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

, B/ ~# j7 E- C" k3 J

DF_NEW=[]

6 i. p0 ^% N3 H! ~& s

Anomaly_count=[]

; z8 x7 G# p0 \4 p5 u' m/ m8 h

for ID in tqdm(ID_list):

& [5 f. N( G: n3 p. t

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

0 N; E; \& y. A0 f6 ~2 h# w

df_new,count=assign_traj_anomaly_points_nan(df_id)

: q. p" T) X6 X' |0 h+ E

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

% ?, q ]3 A/ e4 E2 x! j( Q

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

4 k' ^4 h7 @7 G! Q+ d3 v

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

+ H1 S, L9 @$ K7 s

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

! H5 k/ n( ^5 a8 q% ]* L# h8 R

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

- }: l; i+ s3 h$ R# N

DF_NEW.append(df_new)

/ |; U: t$ H9 `5 b1 I9 V

#将数据写入到pkl格式

2 }( s2 i; [; e( H" H+ i8 K7 f/ A

load_save = Load_Save_Data()

( V& p1 O: w$ I3 p. m

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

; }7 y& J2 A8 }1 O) z

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

+ \' r- V; W' i o6 J

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

H9 }( Q' s. x" R% M

def get_diff_data():

6 Y5 D" n4 ]9 F( ?+ |

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

~/ g7 D" z: ^/ Q. Z6 s

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

* f- |8 n8 r5 i' p$ W

total_data = pickle.load(f)

" R/ X6 w; c3 L7 j0 v: C

load_save = Load_Save_Data()

! v1 ~6 p3 {, ?

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

8 x# N' X6 o' \, @# r- n1 b s

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

- R7 K0 T2 N2 a h$ S$ j

for i,datax in enumerate(kind_data):

: U9 Q7 P T- o. K4 n8 c

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

, J: A7 I5 d# @- ^

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

+ f0 `/ `5 |) R( B" m5 g# o2 V3 d

get_diff_data()

0 y; S+ w5 _: U

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

9 P" e5 I7 B5 F3 {' I- k

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

+ c8 a: f/ D0 }- [, x

DF_NEW=[]

+ r3 H; @7 z" d. l

Anomaly_count=[]

& O9 C7 b1 D2 M/ r

for ID in tqdm(ID_list):

0 D4 `2 L3 v) R7 G; p

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

0 k" `" x$ |5 G; M& T F3 B! A, h

df_new,count=assign_traj_anomaly_points_nan(df_id)

2 U& a v- _5 s m* l4 B' x& g

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

6 m9 Q9 v6 m( C- A' U

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

* k' U0 i& x5 O0 N

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

: g" m0 v& d) v) W

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

( a6 l. E) s3 P0 {' D3 _: p

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

8 H' B, r$ N: a3 R) m- e+ \% P

DF_NEW.append(df_new)

$ j; C( }4 L) m5 {. v: m: l

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

" E1 I/ P# x1 o0 b6 v0 e( z

def visualize_three_traj_speed_direction():

+ C4 |0 l! v7 l4 z4 f5 A. u

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

9 h- M5 m: {% D

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

3 K/ A7 y; k5 \

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

& s# x$ ]. x% }% B9 W; P3 S

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

- c7 B5 j' h) `; I

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

: w5 {% N9 ^8 ^' g2 K8 j* [

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

5 P% y& R W2 j2 x3 k+ W' d" w7 ?, W

colors = [pink, lightblue, lightgreen]

3 G* |; x' \. g e

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

4 K; w0 U$ Z0 U* {

datax = get_random_one_traj(type=file_name)

* G8 Y8 v8 z2 p& e4 B& v# l

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

( R d% h/ |3 k q A

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

4 O. @( U6 y9 M- M

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

" n" C9 U% o( [4 R* e

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

6 w) C. y: T3 ]% Q6 M% m

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

- s% |* W0 T7 d6 j! \

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

8 p3 o x! U+ d- M9 [6 F1 V

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

4 ]/ ]0 c/ i' S* X3 m- ?

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

) b+ C. u) ]+ S" [

plt.show()

I5 v: [% {. K5 ?: h+ g

visualize_three_traj_speed_direction()

: V1 A! [+ Z) o7 P# N8 q
g6 D3 V5 R/ ^0 a y2 m* d

作业二:相关性分析。

0 |; [8 G( H, j8 D3 e

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

) |8 a0 I$ C+ [' u

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

- o k+ K/ q& x+ L

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

/ i& N9 K; j& G( N5 u8 N

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

# D9 H: X1 k* I8 F5 b

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

4 u) L6 l( r0 X. p; e" `; B

plt.show()

$ g. u, P! w8 }2 F8 Z( Y, Z* p& g 9 S3 X/ s" Q7 A- I

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

2 F9 @/ H# B( T( P e7 Y: S" }# r5 i+ ~1 r! N+ _+ { 4 J2 [/ H+ q8 B* Y8 z : n+ P1 P# s5 Z1 X5 P5 p % B; `1 ]8 I9 R! B
回复

举报 使用道具

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