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

[复制链接]
( o8 Y1 | P ~9 u

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

赛题:智慧海洋建设( k8 o0 E Y; H; _ z' K) B: l4 N, Y

数据分析的目的:

9 p: [" N: |( f" Q7 U 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

" q3 Y3 R) j$ t# z$ L2 @0 v' v

2.1 学习目标

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

2.2 内容介绍

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

数据特性和特征分布

. ~& x! I T7 Z& _" ~

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

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

import pandas as pd

: _& V' D3 U0 s+ V

import geopandas as gpd

6 E) }* t, E6 C

from pyproj import Proj

3 A B$ V" i. f

from keplergl import KeplerGl

9 D% a6 v' }2 p: i+ O4 m% h

from tqdm import tqdm

* {+ C/ X9 f+ N

import os

5 A* o- J: s8 Q- o# C5 c' A: ^

import matplotlib.pyplot as plt

6 J$ ^# V" g& W; g) k7 w

import shapely

! k6 c5 P& S' }7 u, B/ \" B, D

import numpy as np

3 j% G9 Q! A1 X# R/ T

from datetime import datetime

2 C0 u* e6 F% Y c8 D) i \

import warnings

9 D; }2 z! h$ K/ j, [

warnings.filterwarnings(ignore)

+ j; G( y7 [2 J

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

) e6 g- ~# i, ~1 E2 ?

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

' U) d1 T# Y) O& a: j

#获取文件夹中的数据

' i2 g3 o* S6 ?; N* K

def get_data(file_path,model):

. c/ I7 s# J8 o) j, f$ Q

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

: C6 |. k1 ?9 R0 _7 U4 }1 N3 g

paths = os.listdir(file_path)

0 V4 s# r# z+ a# [" k4 f' | l

# print(len(paths))

+ Q6 D' _5 ]2 S) h8 o2 X

tmp = []

' d! R# |* H X& P" v& c" P

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

& _% I \, }" ?0 s0 D: n

p = paths[t]

. @/ b' h' a. i4 T7 f

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

8 e" v$ A, o& B9 f& @% n5 W

next(f)

2 v& n B* P4 |' C

for line in f.readlines():

; y- ], V [, K

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

* _8 G5 `6 C" h/ ?4 v

tmp_df = pd.DataFrame(tmp)

- S0 G+ L/ L% o, D& u# x

if model == train:

$ a8 O/ S+ s- K2 @+ O; Z* P

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

* h: \9 P# w9 B! p9 D* T9 |

else:

! t7 M9 i+ V2 P0 _. m0 e2 h) [

tmp_df[type] = unknown

E" o5 X/ V% d" `: c+ f) Q

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

4 T" Q; w) |. X0 B' N

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

; n* X8 x" q3 x( C

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

7 P/ Y5 W! u1 |2 f

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

% e3 z0 A$ u, {1 n: Y. q3 [4 Y# r

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

2 A) p; s% n! F8 T: l- z+ I2 d

return tmp_df

, x5 H5 ?. }; P0 e3 o$ T

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

8 k) J. o' C0 ^* M

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

$ `9 [/ p( B" n! H4 r2 @

def transform_xy2lonlat(df):

8 j; f: j4 ~" J- L2 Y v3 x

x = df[lat].values

: h# X. v8 I) t9 C6 I: y" J& G, Y

y = df[lon].values

, e+ P( q8 ?5 N6 Z: R& |

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 )

+ S/ |, J! x9 s

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

9 E, {$ `& L$ w8 @' p9 ]: w: H

return df

3 Z8 o! n7 \ @2 w, }

#修改数据的时间格式

4 V9 D4 D: g) n7 D' G

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

' O8 w, B, E0 X: q$ V3 r+ v, a

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

; q4 f( S" z: t' E* B

time_str_split = time_str.split(" ")

, R- L% z0 g) k- | k9 A I7 ?; w

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

$ R g' s, S$ z) B

time_str_reformat = time_str_reformat + " " + time_str_split[1]

0 K" y0 D& j& J, Q3 @ o+ o

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

! X9 Z! t3 J" |& ^+ q: |

return time_str_reformat

0 u3 x# |2 f$ L* d8 O. C% x, N }: v

#计算两个点的距离

% w0 _$ A: Z8 Y' A8 y& `5 Z5 f" }

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

; a' ?) _3 t# O5 g$ d q* P) y

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

9 l0 p9 Q$ c$ l) U. x/ C4 S1 i

dlon = lon2 - lon1

6 l5 w6 F! _" x: a4 A

dlat = lat2 - lat1

' \. g8 P# ~4 C

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

+ A9 t- w6 l7 n2 _

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

0 [7 |5 T2 E/ h5 |1 X+ B G7 ^

km = 6367 * c

: H8 h, ^9 y$ I. s- K. }

return km * 1000

" L* e K+ m5 @" {& H" w( M

def compute_traj_diff_time_distance(traj=None):

4 l" C1 H7 \" A5 ], w( m

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

/ p9 |+ e& ]7 R

# 计算时间的差值

: K& }$ I( _, e& Q; @ Z* F

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

$ f$ N9 M X. b6 v* S4 K

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

0 M+ {4 W" z# h/ h" y1 H

# 计算坐标之间的距离

( ^+ b6 Q; o$ |1 J

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

- n8 K2 y+ K3 ^9 U, m& Y2 I

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

b* f6 x6 X' Y

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

0 I: I% ?+ F) S! v

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

+ T6 n: G- p' y4 u2 f1 \% J; m

)

7 T5 d, N# H+ N

# 填充第一个值

^9 G9 v6 U1 C7 p% M3 r

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

9 _" E. H9 n0 `8 ^ s6 ^2 s: {& v

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

. V1 e" y1 V; t# b5 w) _: @/ }

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

$ s5 i& W; ~6 s" ~4 G0 G

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

) g) s& n/ h' l$ Q: E* g

return traj

1 e# I, z4 w6 s7 [3 @: _6 z# `

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

7 ]) n/ M% ^7 J8 r3 T

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

; g; o; b3 n, U

time_interval_maximum=200,

7 A8 v" H5 c v7 n M9 K

coord_speed_maximum=700):

/ v: Y* F. v: E* o" m6 @) b A

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

, R S/ f4 N/ {: ~/ a( E6 @

def thigma_data(data_y,n):

* K6 |. e: s# t; [5 B ?

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

# @2 V1 P, x% o. j) S* Z' i5 [

ymean = np.mean(data_y)

8 { T; G* {7 m! Q y

ystd = np.std(data_y)

, L E- ]1 L, ~- H

threshold1 = ymean - n * ystd

8 O+ b! Y4 S Z6 m6 C* Q

threshold2 = ymean + n * ystd

% z1 E4 n3 W: |% @0 {) C

judge=[]

! ^* p# `- i" u6 G

for data in data_y:

- M$ l Y4 @* G. B8 L% N! B

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

* e8 u3 |8 R s% h7 s& F

judge.append(True)

0 n4 V% Z& A- e% Y

else:

. K- w1 |8 Y9 V4 N; Z& T

judge.append(False)

' d5 I @% }0 |" P y! h

return judge

5 u, e* `+ ~( [ b+ m" H( |' c

# Step 1: The speed anomaly repairing

2 H& Y$ b" N" h& |& k3 X

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

4 Q# o# e0 a9 W' [! m- q/ [

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

/ [9 w' D; v6 c; C2 Y, k

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

* i0 K9 P* t! D) m. ~

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

* U* L3 u$ X2 X5 R' R

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

; E' Y, Y7 A( \$ \

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

0 g: I' w2 o _" K4 B1 i: [

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

6 H3 L- i/ N x% \) @ h

is_anomaly = is_anomaly | is_anomaly_tmp

9 A& e/ m7 W c" Q* j

is_anomaly.index=traj.index

. v0 v- b/ b. j' U% i8 E

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

2 q8 T( M: z" p! @4 d' h/ T0 K) \& `

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

5 b& H( [/ r* _( L5 h

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

, p! Y& j! j3 P8 B

if len(traj) != 0:

" F4 p2 }* A5 M, Z5 C8 e" O) U

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

3 u* t+ S0 s+ Z- @+ W- L( Q

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

0 A2 b. C5 z' ~" W8 n0 F; \

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

# |" M+ ^+ `6 h# y' V

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

1 I& d2 z K" ^( ~+ k, n. y" ]* y

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

9 |4 ^. V: L8 r. j- R& N

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

; I5 F3 l1 B$ G/ o1 Y# }

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

' W+ }9 M% E- H- ~4 b* T

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

" c$ P! l) X; j* G$ f9 D

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

5 X: V9 m# h k2 h' K

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

9 L; b' s2 T- [' C1 P8 y! K/ c

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

! G& l! J6 F) Q& J9 e

DF_NEW=[]

! c; F$ W8 m1 g

Anomaly_count=[]

5 a- R; ~/ E7 L8 K9 }

for ID in tqdm(ID_list):

/ z% X& i3 H4 P0 K/ b

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

1 S5 k& F! i- ? p. B" i& o7 f

df_new,count=assign_traj_anomaly_points_nan(df_id)

/ {. G; q8 y0 {* g% r" _

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

' d0 c& h+ W3 |5 p: s, S/ \) A

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

. v2 W5 n7 q: N$ H/ M& `

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

7 Y5 K* a0 u/ ~8 }& L. U

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

6 O9 P0 A. u% q- f8 z" X% O

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

8 I' M+ L- h: }5 ~

DF_NEW.append(df_new)

% T" ^' E* E. @, ^+ S9 c0 Z+ y

#将数据写入到pkl格式

' t4 z# { o9 k. g d

load_save = Load_Save_Data()

$ ~+ j9 C+ {% i5 e5 l3 w

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

/ `+ X2 z9 A+ N1 U% S

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

" [6 j$ R" r' u: j5 @

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

) y: g) W& A" Z E3 f

def get_diff_data():

7 Z% ~8 S1 Y+ F4 L3 |; {( e

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

) A6 r" @6 ?5 V% D- l

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

& V* R3 ?( S2 P7 Q! L. w! O% e

total_data = pickle.load(f)

& t1 Y2 E, q" g, H- d* I3 W

load_save = Load_Save_Data()

; m4 P8 N/ l- O# \

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

/ l- X4 K- O# P) L

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

4 u7 S0 R( t6 u; r0 @0 K7 F

for i,datax in enumerate(kind_data):

2 n% b B& {( J6 a% H

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

& }# V; U0 d1 Q" g+ F

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

# U+ l/ H8 m; U) u

get_diff_data()

8 p; g) G' D# h0 p0 l

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

4 Y k6 M' T4 ] P; ~) Z+ x

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

" M/ g& m$ t& e

DF_NEW=[]

8 V0 K8 a# [( @1 I* b# x$ C

Anomaly_count=[]

$ H4 M8 M2 J8 H$ c" i+ V3 |

for ID in tqdm(ID_list):

8 d7 b8 M, k4 V: K4 x, H% [

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

8 W" T4 ^1 ^; L/ w

df_new,count=assign_traj_anomaly_points_nan(df_id)

5 U$ ^4 c3 Y# o0 R' B/ R

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

4 ~2 j/ I6 z# T. {

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

+ O( o% y" A( @3 E* X; S# o( r

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

- u" U( G G. I0 o( e* | N; W$ |+ r

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

e/ A9 K5 W9 S5 C% T% {

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

1 u' J8 _7 ~. q; a

DF_NEW.append(df_new)

7 f, C) f* p& Q, L

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

+ W8 N6 w: x, Z7 y6 @+ W2 I& L

def visualize_three_traj_speed_direction():

- ^9 t' l5 j4 N4 p5 Z( w

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

% d: H' F$ ?2 O) a

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

4 N" s+ F, Q+ z

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

+ b9 X+ [- L, [* u. B

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

m1 w3 _$ J8 p, t' x

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

$ }6 {3 W. r0 J) O- [

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

0 i* P* V6 m+ B: \" M1 T

colors = [pink, lightblue, lightgreen]

- F4 X7 K! `3 \- x3 p

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

, ~: t6 B" I6 f: O6 ]

datax = get_random_one_traj(type=file_name)

7 S, c, {4 g7 P3 p5 E0 ^( i6 B

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

& h# {: B2 ]3 @ {

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

{: E! s1 j4 C. f* ?3 S- i" w

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

* @3 |" K U# e q( [8 l+ M

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

2 M Z# L; |7 o, S( A

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

8 r6 O! x, }% I& R6 q6 P3 u8 |) f

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

2 u2 K7 o! g$ \! ~+ h6 V3 {1 m

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

0 `1 t7 P) l i! `

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

+ e- d& q$ A, b/ M

plt.show()

9 S3 c& \" k3 k- e$ v# ]& V6 r7 F5 r [

visualize_three_traj_speed_direction()

! ^+ ]# `$ G7 V+ n- h* M
+ F1 Q. s; N/ v7 b9 Q9 u

作业二:相关性分析。

% v# }/ x( Y9 n

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

4 y: y: a% x5 x5 m6 S/ y5 ^5 S' G

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

. z; I+ d7 z; \5 f3 {: y4 f

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

- S2 s9 }& n6 U+ e+ P* W S" o4 o

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

j6 w1 u J- |$ s/ G6 p

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

1 S7 w2 H. s$ Z0 R/ m, l+ E( w

plt.show()

7 w; k1 \. |3 P6 y' f( _! S 0 J4 x A( }" I) p, F% w

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

( h( l6 ?% M' Y. j' i M0 T- H* H # v# K; S, ]3 I% Z2 [! D! f3 ?; h/ F8 h) M ; I* v0 p+ U1 [9 k( g4 J4 O( q ' N, s \+ F7 L! A1 i7 J( w
回复

举报 使用道具

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