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

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

[复制链接]
; \1 u' q, T2 `% H' Q, U8 J

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

赛题:智慧海洋建设+ I+ D4 `3 y( W# a7 O

数据分析的目的:

9 W$ x/ u E* \+ y- } 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; c3 ]3 q0 I |; w9 \- }) c. ~! S

2.1 学习目标

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

2.2 内容介绍

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

数据特性和特征分布

/ o; ^- ^' z( Q$ E: f

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

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

import pandas as pd

3 O3 ~* t+ i/ r. t

import geopandas as gpd

. t( R6 ]/ d! J% N! q7 T9 M' [

from pyproj import Proj

4 V9 W; m, c+ B" V

from keplergl import KeplerGl

' \ N# | ~$ q& f( S3 t

from tqdm import tqdm

1 {' G% S- w2 K: u4 F

import os

# k2 E, @6 e* o

import matplotlib.pyplot as plt

& E. K; y5 |- B9 i& |# }5 Q

import shapely

3 {; F B. Y+ i7 K. Y3 d

import numpy as np

5 ]# P/ F" B; Y9 @# Q; I8 Q

from datetime import datetime

, w+ F- y5 w& g' K

import warnings

+ O; T- S7 I3 R, h) }/ R2 b

warnings.filterwarnings(ignore)

( T: N1 {4 G, W( z, i

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

i ^# P/ q) H' l% O9 w: k

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

+ p- u/ B9 n& x7 ?! R. c% w

#获取文件夹中的数据

( I2 {( [/ [. ]! R' D5 P$ r5 V

def get_data(file_path,model):

5 u8 ]* Y: v' R( e1 z! z

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

% U3 \6 b# r. j7 _( `$ r7 v

paths = os.listdir(file_path)

. L2 C5 b, f7 R# v9 w

# print(len(paths))

8 W. w5 R4 I6 b) {& v2 @

tmp = []

! N# R. e- S. v e' {

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

* D% h( O P7 E1 q N$ D

p = paths[t]

R9 F. m# ^* x6 l3 r

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

6 B' Q$ {$ j! G' B

next(f)

( l; s! L! i3 Z u# ^# \5 n

for line in f.readlines():

E; T& L7 g; j

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

8 o& O. ?- T; l

tmp_df = pd.DataFrame(tmp)

1 ~' w! d8 g2 C% l' q) U# b

if model == train:

" ]/ k q3 Q' G

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

( F2 W7 w$ N& V2 z1 Z6 ]$ X9 r

else:

* ]" @: i: O+ [0 y# h K) n4 q' C6 l# O

tmp_df[type] = unknown

: B2 F. N2 J: V6 [$ Y' |, W6 @

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

( s9 C% f# I7 W

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

! x% @1 q4 V; \1 _) ?' X8 o4 b

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

2 K9 { N. N/ G: N( b. u

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

$ R$ A' f& Q1 D3 M. Y

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

/ Y& s- m2 \3 c4 ]

return tmp_df

" O8 O$ |) \( ?8 A8 T+ `5 G

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

& @. h/ E0 t/ C$ U2 C4 R8 Q

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

2 o+ B, M9 Z) M8 n4 B7 t U) H

def transform_xy2lonlat(df):

" D: P$ _+ W/ I; U

x = df[lat].values

. b m6 t* Q; M: O

y = df[lon].values

% w2 ?& R* j- ^6 ^ ?) g, D* Z

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 )

; g( s) v7 O& f; l. B3 {

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

: w% }) o8 h ?4 [0 I9 x, V

return df

8 a2 w3 ~& r5 t% _

#修改数据的时间格式

( J8 W Y* b8 O( U: e

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

$ i; O% q- g( L5 G+ W) {

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

8 X# [+ }5 g: B1 [- }: k7 i0 r

time_str_split = time_str.split(" ")

( X1 J4 V9 l! `& F& _7 W4 y

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

, f0 u: ^7 d! a9 Q+ s

time_str_reformat = time_str_reformat + " " + time_str_split[1]

/ n/ m% w) U H/ j* z

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

2 ~( G. ^ g, B0 l* p8 U

return time_str_reformat

# q/ E7 S; L9 U+ h

#计算两个点的距离

! P0 b$ ?. G; W1 W: a" Q! V

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

! |- K- e, S8 w$ V/ i

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

3 m9 |( t/ a( `0 d

dlon = lon2 - lon1

O% i; Y# m, e: z& o# D) ?

dlat = lat2 - lat1

- L* i" |! t0 O, D

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

; ]$ {2 C) B) ?, E' _" S7 U

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

' d/ [( H$ z& R. v) e

km = 6367 * c

4 d7 v- b# t1 d. X/ D1 r7 o

return km * 1000

' ]$ N! C+ d# t1 l

def compute_traj_diff_time_distance(traj=None):

, F+ O: l! t3 Q/ x1 V( n& `% U

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

3 I3 m/ W2 w0 ?# m2 t7 X

# 计算时间的差值

8 n* A) V$ n" D- X. z# B

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

3 g( B# x f, n' j$ Q2 E, A

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

. ?% X+ F5 G7 p! G( x

# 计算坐标之间的距离

# w- c) r4 {& y2 Y" W

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

4 l3 |& t( A5 h* t' D5 _8 X

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

( M. i0 p( A; M9 a" E

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

9 f _+ B: t( |

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

. r9 C# ]! P3 `& F( l

)

" ~0 W( Y- v% q2 f; Z5 \4 v- }

# 填充第一个值

/ O0 H( M; _( k/ C% w' f8 H" b/ J0 h

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

; S) I9 L" k7 G- ]9 q+ Q" y

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

7 c* }* `: g* S& ?

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

+ j( ]& t# X4 y* v6 w) c4 Z

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

0 L! c: P+ `& C, @: D [1 x N L4 X0 B

return traj

& X# N0 j* c# u# b/ G

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

/ K. u7 G. q* ^3 E$ s2 G+ N' p

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

+ l9 O: K8 f5 t R

time_interval_maximum=200,

9 z) ?) x" k8 g0 v J

coord_speed_maximum=700):

7 W0 v- U; ?- g9 u# H$ m! R3 M

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

* t2 v3 m5 g8 c+ B

def thigma_data(data_y,n):

2 ^. `! g& x2 |& V7 ^

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

& ]$ |, x5 ? Q6 ?( ~) s. ?* r

ymean = np.mean(data_y)

. A! P+ G2 K m: _7 Q+ d9 s

ystd = np.std(data_y)

0 B: m# n8 h$ A \1 n; B# ^

threshold1 = ymean - n * ystd

+ l. Z6 S5 s) {6 l; X

threshold2 = ymean + n * ystd

4 U: E: T6 g5 _4 Z, p. N/ ~- X+ v

judge=[]

% \: t5 d1 _5 w2 O* ^5 H

for data in data_y:

0 Z; V: O2 x/ ?# Z; t# ?- B

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

N" [' M t8 @/ V# ~/ e( X- q

judge.append(True)

5 L- {( y9 v4 ^% e) a- K I

else:

7 j* a1 @% Q; [+ T: d5 n2 A

judge.append(False)

4 |8 `. t5 m' |) }$ _

return judge

) O# l4 d; Z8 k1 B0 |

# Step 1: The speed anomaly repairing

; D" [4 W- j. _5 Z, C& c& f* \

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

- ~" h# ?: j2 L4 U1 t5 I# \

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

8 Y q* Y3 l* u4 V8 T2 |

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

& w: U8 B w7 u; J( x6 r2 Y

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

) N3 D$ E& O8 B) k0 ]

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

6 Y8 f: C: \. g6 l: U1 k

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

* D- r8 @( m# X2 ~+ x/ T1 M

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

" J6 a+ b% L/ q

is_anomaly = is_anomaly | is_anomaly_tmp

+ i% x- k& l4 K Z- K" Z& Q# _

is_anomaly.index=traj.index

" T1 y, T) K/ R- C

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

; }4 ~0 U& b% }: c. H. }

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

4 s# O2 I2 Y) e# U

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

4 X7 F2 W& D# D3 ^+ y5 \

if len(traj) != 0:

. s; ~# F2 `# X8 Q. p7 L

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

, Y6 }2 z6 a- L L2 w% o9 V

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

7 l. j" _- c; n$ S5 D

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

2 [/ \9 g' _* ^' [% M

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

5 w" a% q. |5 _: [

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

) V4 o. P& k+ k* ^: F. D3 K

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

9 r5 e3 w* v4 f# U! f( Q" s

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

! y3 P: G6 A* z- h5 O1 k

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

" w3 Z( z, g R5 \# |- L

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

' D. L2 E7 s9 L `6 U

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

8 C' L t% a- J2 A8 C) c4 |

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

; p& M6 r6 S2 J# j4 ^

DF_NEW=[]

- [7 q3 E% a/ h% @1 |

Anomaly_count=[]

0 V- i7 L( j9 I( M5 h$ t

for ID in tqdm(ID_list):

- y' v9 Q6 I M: V

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

3 z2 Z) t! ]- V. i

df_new,count=assign_traj_anomaly_points_nan(df_id)

5 y( v% c$ a1 S! s0 C( F. d

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

3 _& N) G4 f/ v5 I6 W9 g

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

! m+ e# J+ b7 R# m8 h" L; u. M2 v

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

) v: P3 p! z. {. h& O( M d) K

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

" H7 {# `0 @3 V% p, y

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

: R' w+ a+ g" } G

DF_NEW.append(df_new)

6 a( R' W/ \" B

#将数据写入到pkl格式

/ L5 A5 Q5 C. X/ T5 X

load_save = Load_Save_Data()

8 }8 S4 H2 L) l9 ^

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

% U2 m' D" L5 j# [ n) e

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

2 z- w0 c& N: g o5 ]' H

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

0 Y; @* z% C5 @* n8 m

def get_diff_data():

* i. c' ^; S5 w. g

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

o9 _7 B% K3 m4 j6 I( k% D; A

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

! N e( `# ~; B: S* X

total_data = pickle.load(f)

- n# I7 I7 ~3 t; [. ~. G

load_save = Load_Save_Data()

. V. I! O# W R8 O

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

2 g3 Y: S) F' S+ K: l7 B

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

$ t7 i' C7 a: _8 X5 p/ q) l

for i,datax in enumerate(kind_data):

1 i! @+ y. C4 d4 J" a

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

z7 [, N% R. n) u+ O5 m

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

: E: H5 g# { Q6 c( t

get_diff_data()

- ^" @5 g- M, H ^+ f+ z5 W- M6 W

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

2 z- y# B" C) B7 l5 F2 V, ]

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

: x' ]" N7 S2 d; c4 X3 \9 D

DF_NEW=[]

. V2 g2 T/ Q0 d8 F

Anomaly_count=[]

6 H( g* M: \! H' v2 z6 B

for ID in tqdm(ID_list):

* y' L3 Z) I8 J

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

) ^( a" {5 N5 q N' @

df_new,count=assign_traj_anomaly_points_nan(df_id)

+ Y/ U8 {7 k" @* R2 Y

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

3 i7 G" ]& P/ Q$ H

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

) b2 u+ v: _' P8 y9 B) v

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

, ~0 F5 d; k+ y" j3 \8 S5 Y

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

, M& F5 D+ R) I

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

* ^% J {0 {4 n9 p

DF_NEW.append(df_new)

0 `6 v: c$ Y* V

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

) z, ]9 m- G! @/ i# F7 q

def visualize_three_traj_speed_direction():

; {' z- a2 f: M& e

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

" L0 t6 c C2 j4 N U# m

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

& i3 l, v9 [+ o; g/ \

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

. j( D4 f. j4 X

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

/ [8 U+ I# \( \2 P* [0 A

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

; x# l1 z( C: X& g% A% |

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

M& l; c* O. ]) }: h3 D: v) j' b

colors = [pink, lightblue, lightgreen]

, Y. I# T/ I$ ]; x) J9 _

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

$ O$ ^. P v, x7 H/ k/ x- F+ h

datax = get_random_one_traj(type=file_name)

: |' T: s' t% D2 y

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

6 X" C1 S P# C3 x1 z

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

; U- u+ s/ a4 q; Q) e# N# ^# v

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

* i o' }. ~8 ^# E) Y& P

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

, A- _( e0 I% v4 w" u! |! c' F% I6 `

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

' s# S1 ]1 Q5 C# r5 F4 p

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

U2 l7 x/ s) ]2 Q P5 n/ D

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

3 B& P* d) @8 E% }. d

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

; W4 x4 q m2 ?( E

plt.show()

9 N6 f) O0 S, s$ I" P; r8 S

visualize_three_traj_speed_direction()

1 }# W$ z$ ]% p5 M, `' o
x/ U( z3 V( z5 W1 Y) {

作业二:相关性分析。

! Z r" S) I/ V! {; V. n6 j

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

9 q$ ?! u0 {) m3 H, X

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

/ n) e ~. Y" O* a

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

2 }9 h6 B! w4 Z; o

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

8 S1 s% C+ e) i6 m5 V" x

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

: t) `) ]- S$ J) H& I

plt.show()

/ w I- n+ H" u# X2 j h; | & W, r, n2 \$ ^7 V/ p4 s5 }5 N4 k' N

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

! {, c" V* c8 v& |* a& L ; B( P j7 W4 F% d ' `( N2 n$ a* `6 X0 d/ t5 W2 }0 p) L x8 j4 f - O, m5 l; x) y% x2 E, R; r3 H
回复

举报 使用道具

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