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

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

[复制链接]
. R% a2 f- Y, } w& b

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

赛题:智慧海洋建设 - ]5 h& e- M; A9 N; L

数据分析的目的:

* f [+ z# W5 v$ i' A& F7 [ 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

- t- S" z2 r! C! U5 k5 v! y1 O; w

2.1 学习目标

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

2.2 内容介绍

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

数据特性和特征分布

* b! p9 Z5 l+ {9 j5 u R

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

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

import pandas as pd

* m. B4 f* x. y6 v; K& S

import geopandas as gpd

0 i6 d1 I) E; X* V" F0 m

from pyproj import Proj

: T5 z: l; e; H! N- i. Q

from keplergl import KeplerGl

- t; d4 c" l" A* U2 F _% B( o0 o

from tqdm import tqdm

2 H- H# p" _( U n/ k5 q6 Q9 ]

import os

/ |/ T9 G) k# E) n5 t- _

import matplotlib.pyplot as plt

/ ] o8 [1 [3 {$ w/ \

import shapely

# V3 U* }4 H @, r: h6 P

import numpy as np

- j; Z- b0 ?: i9 l2 ]9 T7 x# u/ R

from datetime import datetime

0 `6 r" [' b+ A- i! B! r

import warnings

$ g, d; ~' w6 a" u

warnings.filterwarnings(ignore)

# a- S! v$ ~ m" c1 s6 q

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

, w# ]( L: @. Y4 Q

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

. V$ y# E' u) }0 U/ d

#获取文件夹中的数据

; C6 P2 r; \9 U# D2 T9 ] }

def get_data(file_path,model):

! g& E# E3 v' L6 Q6 W2 t+ h

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

( H+ P1 d, ]0 M- r+ c6 M9 z

paths = os.listdir(file_path)

& Q$ j: V1 W& P( ^3 T. a

# print(len(paths))

- n( f$ J) T: X) `3 Q8 \- ~3 N4 Z

tmp = []

" Z$ o" M5 ?2 a9 D4 _, z, ]

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

* U# c$ W+ |, J! E) j6 A( U2 R- e7 I

p = paths[t]

4 l" S4 ~' f8 R, d5 V* X- |8 ]: O

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

: M' A8 f; I% ?7 {; F

next(f)

) u% q& q2 ?1 ~! P

for line in f.readlines():

4 O. h, P+ l x4 ^9 {

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

8 `5 n- z2 S; X" I$ C

tmp_df = pd.DataFrame(tmp)

" x2 _+ H+ n. E) B5 F# G$ R

if model == train:

' ^; W0 Z; E0 N. v N

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

8 l) E- I, ^/ G w( A S3 o

else:

+ K) ~5 I* b. U+ T

tmp_df[type] = unknown

2 R( O3 |# k4 l' u$ ^; L

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

+ K; F1 L9 ]1 _' N* v2 n

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

! v0 M; Y8 s7 U: V3 V& T

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

: `; h% F6 I; k; J7 V

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

" s* C0 W- D" k8 _8 S q

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

: N4 A- ?9 H/ z" F- |) E3 z

return tmp_df

4 D# z( p2 J5 F/ V

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

7 k# W8 y# w% A2 e+ W

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

1 T5 X( ^1 L; p, _( ~- N( m

def transform_xy2lonlat(df):

7 ]8 m& n! n# H* ?1 d+ V

x = df[lat].values

9 U3 w! R( s P1 M

y = df[lon].values

% j3 o3 w- W4 ?/ ]7 V

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 )

7 m0 ^8 C. P& ~' F7 _2 c3 q; V

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

( M4 A+ J& D+ p+ `" K: M1 y T

return df

5 J& B/ j+ R' y7 R/ B- U

#修改数据的时间格式

! @& N. l+ T& f

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

( W5 g5 i% x4 \# t

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

/ R3 @4 r# ]+ Z4 j- Y$ V

time_str_split = time_str.split(" ")

~7 F( ]( v3 F& H ]" U2 }. c

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

9 u/ j* b0 p* [/ G |/ R2 t

time_str_reformat = time_str_reformat + " " + time_str_split[1]

+ }- H$ R% m" j$ ?( E( {

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

' v( @% I9 h& z0 @

return time_str_reformat

1 L8 o( L) G5 F8 f( ]/ P

#计算两个点的距离

( p) h, m: J4 ?: A% f+ D8 V

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

2 J/ }5 c! y6 i4 w7 M) S$ k

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

1 v x& z/ n( ^) Z

dlon = lon2 - lon1

$ T! E* v6 ?) R6 h( R

dlat = lat2 - lat1

# r2 m9 U4 f g& p5 J

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

9 l6 c+ R9 G# h2 ~

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

2 M: S! h [. R g! v" E

km = 6367 * c

5 [* w% r' B `7 P+ Y: R

return km * 1000

+ v' x8 ?1 o' s8 V8 c1 s% k# S- W

def compute_traj_diff_time_distance(traj=None):

: h: T3 i; c4 D2 X

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

7 p- R- u- c* v7 ^6 X

# 计算时间的差值

5 k2 V* }- { O" n

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

0 D5 `) m) Z4 c# i8 P9 j

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

* M+ I, H& K1 s, n. u% I

# 计算坐标之间的距离

4 {! t% \8 L# h# Y) j, M7 @

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

! q; A* g9 V6 I+ _9 e7 H5 ]

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

, r+ Q. p" w) L* P$ z

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

4 A3 ~# S* T7 N p

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

4 O2 l8 [2 j. J; f

)

4 \3 H# a/ M" _* S. S

# 填充第一个值

; O+ s% y# D6 e% r. C( x0 Q

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

/ }' k! O4 l6 E5 h, r

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

$ T+ I6 S# P/ c

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

/ w- {% g ^5 a( O* F, ~+ u" m

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

* N: J: \' j1 s; y! u- ~

return traj

% K7 A% F" E, O

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

% U k7 J( o- }

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

$ [ R2 t7 h! j3 R

time_interval_maximum=200,

; p" s: x, U) g3 d

coord_speed_maximum=700):

6 x8 w5 r5 G' w

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

' b% Q, _0 O/ s# V4 L: G. C2 e

def thigma_data(data_y,n):

6 e9 f( m0 N, `3 t( d! @

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

' c1 B4 K' U! i$ f, R

ymean = np.mean(data_y)

5 g, w2 b. [! }2 w- _9 w# \5 ^

ystd = np.std(data_y)

1 n4 |( V3 `+ Y T& P

threshold1 = ymean - n * ystd

9 y% w5 z7 i: H2 u" F5 x0 ^

threshold2 = ymean + n * ystd

/ X0 O) b& ~, S+ ]" Y2 q8 I

judge=[]

5 x Z+ l+ i( z& p# h2 ]

for data in data_y:

I; v# ]: z* P5 W) g' Z+ B) i

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

( S% r8 w* _7 R. X5 {/ d2 Y

judge.append(True)

! S7 j5 U* w- ^( W* B; `" l

else:

5 k, C6 _1 ?) k0 p

judge.append(False)

( V9 a( l6 t( P. b* b# `1 q

return judge

4 I/ _$ j/ Q0 s. q, J! h# S4 b

# Step 1: The speed anomaly repairing

) V6 b/ }# `) y) j/ S

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

9 x4 W: C6 W& B7 d P9 O9 h

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

5 k& ^# D/ [2 p' F/ _

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

0 F2 V& |2 d+ r9 a4 p9 G

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

6 y9 e) n9 h/ ]

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

_7 d9 y% l- {# g0 B

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

7 J! \6 T6 S1 ]0 {8 C# o7 Y, y( x

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

( k" I' M8 a: I, C1 H

is_anomaly = is_anomaly | is_anomaly_tmp

: D. M) q# b, `9 V

is_anomaly.index=traj.index

5 B% a' q0 ^* j

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

' |2 x5 n: Q+ ?$ M3 p; b! P$ Q% K

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

% | x1 e( \ O% T6 w, |3 }7 Q3 l

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

/ J) S6 S. X+ ? M

if len(traj) != 0:

, J' `' d e3 o( S: k+ f; ^

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

* n, l4 b4 r7 I& x' l0 M! A

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

4 {( Y' h. X3 [+ a9 l

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

4 j' b& J9 @' S/ e0 n

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

# l- x% m! G, e! ^+ c7 M& r

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

% B# x' l W6 s

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

: g0 i9 i" B H% V4 ?4 K) K2 I

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

8 A$ p( D) s5 Q& t

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

, U. d6 e9 i- V" e6 L" p+ d* R

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

4 ]& D& J6 W! Z2 ?' X9 q# F

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

% d& H& P3 x( |2 a& e( \

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

' E- t! c" r. _0 F

DF_NEW=[]

0 B* O7 ]7 Z$ A. B& y! e( h

Anomaly_count=[]

0 i( ]. t8 d4 s

for ID in tqdm(ID_list):

/ p( r8 p/ i( @! u! b& C

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

' |7 U! `& U2 w k# e7 ~6 |

df_new,count=assign_traj_anomaly_points_nan(df_id)

1 \9 y' r' W, g# a0 K/ I& e6 N7 K2 j

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

& f" ?0 Q0 V5 ^8 }) r- j1 c

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

2 ~2 C( C" J9 s. p! v, H

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

- m% B) f( [4 N

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

, y: m: M* K: l4 _

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

7 y* @# c: Q- V7 E M- h+ s

DF_NEW.append(df_new)

: m" s& A+ x+ f/ m8 m& i, G

#将数据写入到pkl格式

3 ^1 o& M- ~+ i# f

load_save = Load_Save_Data()

8 a7 h1 T( Y, z$ R% `

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

$ R( v8 c. L( b* l- K/ _" ~# ?" ~, b

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

( Z; i3 B0 h! i) o! M" Y7 R) ^2 X! d- C0 V

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

: F% t9 c% C7 z5 O' j/ ^4 g( K0 y! `

def get_diff_data():

* O8 l0 J- H+ c, i5 Z

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

7 q Z: A5 {. P6 z3 O) Q

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

6 o8 `: E& ~6 w4 j+ l

total_data = pickle.load(f)

. S7 a% l* Y! u8 q4 y

load_save = Load_Save_Data()

; I5 i; e5 [- s! ~4 j3 I

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

: g9 J; G5 c. V

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

8 t# i+ x' N5 O' P

for i,datax in enumerate(kind_data):

0 B0 I/ C+ o/ T4 D4 M

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

0 u' ^* ^& k" p8 E) k3 D, c$ z

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

& J; E' {& l' z3 D( o0 t

get_diff_data()

3 o: x9 L+ h. I* k

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

; G7 k/ ]6 Q$ [, x

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

3 D: n( _$ I6 T% d5 |2 m

DF_NEW=[]

6 ~" g5 x" H& ?1 k( w

Anomaly_count=[]

0 ]9 y$ [% O% A4 v2 m

for ID in tqdm(ID_list):

4 s/ g8 J9 U, O$ `5 L2 k

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

2 l$ p$ ~+ l: m) N( V0 t0 s

df_new,count=assign_traj_anomaly_points_nan(df_id)

) [3 X0 o# ?5 O/ \

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

+ y4 }. z& p& @* e, I- D! ?7 K' V

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

+ H0 @. h( [) x2 {8 v+ s

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

3 T6 D7 Q% ?4 k5 H4 f6 U9 j" k& j4 @

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

/ S; I/ }. M- z% g) j- h: o

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

0 o. {- j4 y, f& r7 W: E

DF_NEW.append(df_new)

" M5 Q8 _7 z E: _

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

7 f; U J8 F$ F+ ]3 u$ F7 d

def visualize_three_traj_speed_direction():

' |5 m' [& c. I3 m2 p

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

* I& _4 Y4 M: D7 w( h( j

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

$ i- A- o- K2 `! W: ]$ F

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

# f5 \$ _8 T& N: P

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

2 U' }4 V+ V& Q+ | @- D

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

* {' j! O c- ` W$ X% l/ C; k! w

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

1 H2 }, i6 R+ t3 J

colors = [pink, lightblue, lightgreen]

& w% }( y ?1 t! p) V8 F

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

9 E) Z# [' ]8 s$ k6 G7 H- F/ ?

datax = get_random_one_traj(type=file_name)

" z$ `" ~7 a0 @: l* ~. O

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

- K! F( b l- @. O! E

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

( D9 C( R& G) Q# }# v/ v7 x8 }

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

8 t D4 ]1 c8 d

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

/ h+ i% L: a, L! F( f

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

7 V5 P& a4 f5 a+ F3 A$ b) k+ n

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

$ S( }/ S& n. x. t

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

5 @ J- v# k7 l; D

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

! K* v! p, u' J5 _. N8 k9 A

plt.show()

8 [$ J5 n7 J. n0 w m

visualize_three_traj_speed_direction()

: C: g K* B3 {# Q, t6 [1 B x- E
$ D8 ~% C+ {( a& _

作业二:相关性分析。

. a) k, X7 @: F. y7 A- ^% ?* X" r

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

3 d, g5 e( o' }# Y* h" @: G

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

A9 c6 Q# G( ^, I2 \

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

6 V* f9 U1 K/ v

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

7 t1 P1 U# K8 Q) F8 @2 @

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

8 u3 k2 ~- F+ O( C8 O y9 e j

plt.show()

- h; i9 h! N) g3 F) h6 n' k + J4 B5 k8 z0 L- a1 ^

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

' |# c7 B% S" D. u/ Q: Y 7 W/ V) a% g1 @7 \) i# S' O! u2 P' w. T0 @1 ` 8 K. C6 {3 e- L4 W4 e . e, t0 }0 n2 I. v1 h# Y
回复

举报 使用道具

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