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

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

[复制链接]
1 q% h* I0 |: R8 _' j

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

赛题:智慧海洋建设% j' N3 k1 V( L9 E! G7 M

数据分析的目的:

( b l7 B0 E. E/ x5 e, ~! ~, p 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

" j! f* c% K. U6 h2 g

2.1 学习目标

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

2.2 内容介绍

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

数据特性和特征分布

. c- ]) w) ~+ Y! P7 _

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

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

import pandas as pd

( c1 Y5 H) `# N7 r$ I; ^6 ?

import geopandas as gpd

' ?- z2 ^6 k" \; M0 s

from pyproj import Proj

3 x/ ~$ U1 ~+ i# O9 l( g

from keplergl import KeplerGl

) X9 H$ A" E; R" r( ^

from tqdm import tqdm

# g/ l8 |4 a1 V, i! H' |+ G

import os

9 k4 K+ n& }; K2 e U- ]! }7 B! Z

import matplotlib.pyplot as plt

# A$ t# w8 v9 j# m# V

import shapely

6 }6 x7 t" L: c; L" u$ N" ~

import numpy as np

+ @! K9 D6 ~1 r- u$ [

from datetime import datetime

0 G. ^$ I2 D, H6 t1 A- \' |

import warnings

' ^; ]1 E% B) ?8 c5 Y+ F6 y

warnings.filterwarnings(ignore)

2 F5 f* j& o6 N* `! ?4 M

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

- W% q# i7 I5 h# O. a& J8 M8 z) m

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

; L; j- Q9 q$ t1 `6 j7 c+ N

#获取文件夹中的数据

9 j7 @/ L; t, z6 Y4 T+ b

def get_data(file_path,model):

0 l' R: h8 w& c) A6 a7 }5 u* h6 R( [

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

) Z5 C5 i& X' |6 t

paths = os.listdir(file_path)

5 m# o. x! S. l

# print(len(paths))

" I3 ^' O1 u0 p0 @

tmp = []

: p( ?5 J( c! C$ A! }

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

+ e0 A0 v8 v. U5 H+ [+ A& s8 ?

p = paths[t]

" F: t: T/ `# F# |

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

' R6 j, a6 [( F& V* S

next(f)

; u9 N" z! n5 `" M$ w& J

for line in f.readlines():

4 D$ c" v! S% H* R7 R r/ k

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

3 u" s6 {/ ^# i- w) ~: n: N- T

tmp_df = pd.DataFrame(tmp)

9 @' l5 ?, q9 y

if model == train:

7 R! P5 W( v1 n) i6 \

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

9 Z: ^7 ^ s% d1 E

else:

, F- q( R: W! i0 X: s

tmp_df[type] = unknown

; @6 t2 D t5 Z) k2 _$ Q4 j! i0 |

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

9 ~1 I% F4 J6 m6 ~( G4 Y4 D% V

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

7 x" c/ E2 I3 O" G% }/ _ s, Q

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

& X" Z) V T% U7 ?! Z& s

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

4 C( E' Y$ w+ c6 x- u6 }) k, [

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

8 D( u* o7 T: c7 Q1 q" `

return tmp_df

2 o+ \3 w l5 J' I$ i' ]$ m

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

; s0 W9 P s2 D) m

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

1 U9 m9 x/ H; X2 A- B6 r

def transform_xy2lonlat(df):

2 K( o ?2 A+ e& C

x = df[lat].values

/ D; I1 o% }. w( q; X$ k9 b& F! {

y = df[lon].values

x! G8 m- Q: t, J5 c- i

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 )

8 T4 m: p1 v% h0 k7 V

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

$ o1 q/ F& E( T- _4 e) N( g

return df

/ ^- o1 d8 u4 H( R" |

#修改数据的时间格式

, D& J5 P/ y* s, M8 t+ f. q

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

) W4 ~2 i; I$ z6 f1 F

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

0 F+ k* j) R+ {: M! H' f

time_str_split = time_str.split(" ")

4 }# b- k3 G/ u I

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

' o) ?( t: R9 }3 {9 g

time_str_reformat = time_str_reformat + " " + time_str_split[1]

% B9 \! i! r3 l. C) m1 K8 s! r& p

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

8 c3 P9 u/ R$ J7 }/ s

return time_str_reformat

) m+ r+ m0 c! T

#计算两个点的距离

4 N, q# p( A) H

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

; A" z0 k5 R, x$ }; _ J

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

: ^% z0 L, H6 E9 O& G& @8 T6 g

dlon = lon2 - lon1

9 T* G8 f+ Q" S" O6 q

dlat = lat2 - lat1

( q" d% V1 v4 C8 i$ t: a0 \6 |! R

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

! u2 }9 A! ]* N6 [, G

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

( E2 h i5 d# @

km = 6367 * c

* J! H7 R8 \' f8 F8 j6 i8 M" Z2 J

return km * 1000

6 V' K' i# v3 ~% X5 v/ _% w

def compute_traj_diff_time_distance(traj=None):

8 p. v. L. m. I

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

' ]! n( f. _9 S) d8 J) ~

# 计算时间的差值

W( ]- ^5 ?- k/ ], v

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

# S2 D' y! [/ R. b0 V

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

8 p; P* d- D4 L: T4 Y

# 计算坐标之间的距离

2 J4 v7 j: O% C! n

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

6 @6 Y5 }- M! p) f

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

) \7 j3 e/ b- Z4 x* a* |0 s

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

2 A5 R/ K2 a4 i. }

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

) {3 U8 Q2 o+ _+ t& r: P: U3 O

)

" W) ^$ z: h! J" o& F8 R+ | N

# 填充第一个值

3 d5 T S- |8 _7 A; \8 k

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

5 ^4 h+ l+ c, a& Z, v6 E4 J

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

/ g2 J/ ]& x7 K" H$ W

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

M; I) I) x/ u) {* r

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

/ j7 R( W3 A4 x3 Z3 Y# C* D& h6 j

return traj

+ f# z: l/ R/ \+ t: R2 l

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

A3 u4 w# `7 O' Z+ ]1 R4 l' N+ ^

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

# \$ `4 ~6 l1 m* U& T

time_interval_maximum=200,

4 c7 h: F0 x8 U$ c9 @

coord_speed_maximum=700):

* R3 D' L. S, B! U2 P3 o3 f

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

# ]( z7 R1 ?5 t, V4 e7 }7 h9 Y

def thigma_data(data_y,n):

2 S6 q1 l6 b3 }0 s

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

$ _0 x7 L* A, F/ `# ] D

ymean = np.mean(data_y)

+ i9 S6 ^' t& ^% {$ k

ystd = np.std(data_y)

, v% b% J# O' a$ H3 @) ?

threshold1 = ymean - n * ystd

3 H4 y* Z/ F3 r& o6 c; s, N+ h

threshold2 = ymean + n * ystd

& i6 m. \/ L6 P3 y, t2 h# Y

judge=[]

0 u2 \2 }2 j1 V/ F* Q

for data in data_y:

& z3 q3 V' w' X. j Y( g. D

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

4 j: G( I. s" U* i9 `

judge.append(True)

+ w! y4 o2 k- z% w K3 f4 ^

else:

% C2 ] x9 y; J; o0 n5 Z1 w4 e

judge.append(False)

$ p1 s/ O3 D0 T7 }3 E# ]+ k P; D. a

return judge

" t% A; Q3 l$ ]. m" o9 A

# Step 1: The speed anomaly repairing

) M# P! r1 I9 G( \0 p+ V8 r4 {

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

1 Z( @0 m9 k2 c4 l

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

- M; q% ^! V T- K, A

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

: | Z* q. }% f1 w* @, n+ n& e

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

! a: ~7 J% L/ F# o! p

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

+ z, |7 a l# v; d( m

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

( J& S. F& V. E, w

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

! F/ \2 u" g/ H

is_anomaly = is_anomaly | is_anomaly_tmp

2 G. O2 i: q: i$ N M+ A/ L

is_anomaly.index=traj.index

, U1 `7 [ N1 b# J1 N* ^

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

. Z% Q( F5 |7 d( A! ?) G

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

7 X9 h" `% j$ _( i M

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

8 H3 I* ?. o# \3 N! l

if len(traj) != 0:

. r, |/ v ~$ Y& N: z6 M

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

$ g( w* V+ _- r8 E/ U# |; D

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

* n; Z y2 \* u' g: O5 p. L

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

" L" g" R% Q) g- [( K" [

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

/ n6 o( a ?4 o

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

R' |1 s0 H/ J! Y% w

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

7 G" H: \+ p f+ f* Y3 a7 i. S

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

% x0 r% Z' h, r2 D

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

+ D# @- r m0 S$ A

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

* q, T5 g# L4 l( m& u/ \

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

& d) h, Q N+ p& K- _# o/ i

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

" N7 H- b* A) z" s9 s) e2 ^ U, T

DF_NEW=[]

9 i8 G2 J1 ?# |9 ? s% k( H

Anomaly_count=[]

% c; I8 c. w* i

for ID in tqdm(ID_list):

8 U% x6 p% S Y) z$ b

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

6 @9 y9 I+ J6 q- V# b

df_new,count=assign_traj_anomaly_points_nan(df_id)

8 X, \4 w7 K5 @ B5 C

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

- \9 j9 s* J6 e$ s$ O3 j

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

6 v8 m. Z. ]$ h6 W% j

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

) w2 @; V( G7 e+ A* s! L

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

" ~. ^6 m4 k* H4 N& y

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

1 Q+ W+ S# K2 C: E8 n, x: c

DF_NEW.append(df_new)

- u4 j4 \2 J- K% i# [0 \+ L' m t

#将数据写入到pkl格式

+ ~; v) L" I1 F% B

load_save = Load_Save_Data()

, K: M0 Q4 F6 L

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

' u- d& v9 O# s% U( M5 L5 E m

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

7 a5 M7 K. b& U* c: g3 G7 F

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

- t, T2 d: t" E( ^9 q$ P

def get_diff_data():

' g9 \2 f' y/ [+ S% Y/ Z' h" s

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

, X* y5 y# k( M( {! j

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

0 ?% f9 ?! O7 Z# R3 Z. b

total_data = pickle.load(f)

$ J/ k5 ^+ l- H% L, K6 z

load_save = Load_Save_Data()

% E% X. X+ r) u( A( `1 E

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

9 T. a( Y* V7 D9 Q! h

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

+ t& Z3 J3 [& q- ]

for i,datax in enumerate(kind_data):

, G; |% z* r1 l8 J0 w

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

+ R+ z' E% S) p6 ]

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

/ o) K- P5 Z, s, [7 i, C5 z" i

get_diff_data()

" C- ]* w2 K5 w) K) Z

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

- W: V' @7 ~* y

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

0 n! P7 m& O: [! S2 k1 i

DF_NEW=[]

' q) t9 `* I% Y; G: c

Anomaly_count=[]

7 u$ e9 S* w/ W0 M4 c

for ID in tqdm(ID_list):

- x* |4 ]3 T& y# e9 I0 p1 x9 i

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

7 p+ w, ]9 I5 T! g: K$ B) q1 }

df_new,count=assign_traj_anomaly_points_nan(df_id)

9 A4 a. ?- ]/ w( ~

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

( I4 V; E) `5 }' f

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

) V$ d6 e* z. U& t9 _

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

2 k( h# T, d- I5 ~$ { T

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

. W- M, q4 r. Q2 h; H8 q+ _* s

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

/ i- ]% w* C1 K/ t8 i

DF_NEW.append(df_new)

Z3 N! n3 G* z5 G1 E/ i. H. \* F

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

% M0 v, [. V$ I1 X5 b( b! Z

def visualize_three_traj_speed_direction():

& I/ I9 Y( ~& i0 g

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

, D! n7 q% h* o3 L+ z/ [

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

2 l, `% q8 e. H( ?' M% p, g+ o

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

) {7 c0 m, d* F( M: _) K6 k( j0 R

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

. |1 P, p" o" u' m& F. l; M4 V

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

1 U( `8 F8 I( _9 l' }# j2 p

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

. Q% @) h; }1 ^! N* \! }( Q

colors = [pink, lightblue, lightgreen]

6 u0 [" z! R+ v* d

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

& n! p- y" @4 h: Q

datax = get_random_one_traj(type=file_name)

9 C) p9 m o8 o. B% s. m! N7 i1 B

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

& T, E7 y" E7 E+ m1 k

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

' h0 N5 n; `% d. f1 e% _

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

7 \1 V& s, _$ y/ f- x3 g# l" v

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

5 L$ \9 A- ^" {1 m: G/ L _

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

3 @0 m( m( X3 E5 X

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

9 k; p6 ?+ o7 a. C. s% r

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

* |& w" ]2 ?" r

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

6 u* ^' y& X8 }2 _6 A! t

plt.show()

: b# q- E3 k& b

visualize_three_traj_speed_direction()

- l0 r, \0 d0 o1 c1 p
# ^9 G% O" M% b" q0 A

作业二:相关性分析。

; C% @, g/ A( K$ Z; ~9 a! M

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

! V% }1 [) D- G$ p

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

2 N1 j8 T% p2 K8 Y" ^7 I- o- }9 }- P

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

8 ^: Y# _- H2 z( Q4 Y

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

: [% g4 b8 K& H* V9 g& r; v9 g

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

" L* a/ @: @* ~+ U0 G( b/ X

plt.show()

$ C5 e. M! H+ u) z % Q s0 G5 i" c# n2 i) }

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

* O: K& ?3 y/ O & r- ~& \* v3 E 7 [. t; F1 W& F6 m$ j 4 y s% F" x/ u v! F1 r6 m 1 ^5 e, u1 y- B' M
回复

举报 使用道具

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