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

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

[复制链接]
( K/ v" r- Q# {/ ~5 _

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

赛题:智慧海洋建设 # z$ T1 k- i0 u5 W5 O# {3 t

数据分析的目的:

1 s* w9 i: s4 U0 q; X 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

9 R8 W2 O+ I% m% s P

2.1 学习目标

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

2.2 内容介绍

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

数据特性和特征分布

q& v5 S7 m! G# {

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

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

import pandas as pd

. S1 @; M% T6 a; o% F

import geopandas as gpd

# n) T6 a) K5 k6 P( Q2 o5 ]4 ^

from pyproj import Proj

6 M/ T' G9 x! O8 ^* z4 h

from keplergl import KeplerGl

5 P6 x5 y* }1 {( c3 ^% c' f$ g- n6 L' K

from tqdm import tqdm

2 m+ W* s, r0 [6 W; O6 w' u

import os

' r' s3 Y* ]2 Z+ o- j

import matplotlib.pyplot as plt

4 m$ @2 Y& S( e7 l; T7 o

import shapely

( c3 v& @4 d5 }

import numpy as np

6 b. Q' N3 r- u) I1 ^4 E( @

from datetime import datetime

# U! I" J& s X

import warnings

9 w( Y- T/ }1 _

warnings.filterwarnings(ignore)

9 w2 F! z$ u* j/ c

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

# l- R( P- R U+ l; u! u: B6 |( R, D& P

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

* |1 z$ f# S, b2 B

#获取文件夹中的数据

5 _5 V- e' r) T1 H. ?" o8 _

def get_data(file_path,model):

- I: Q5 @' I; u" ~8 }

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

! p# J- }6 p. }! @+ k

paths = os.listdir(file_path)

2 i5 n1 V- y! u$ Y5 d* W% k4 K

# print(len(paths))

+ a& F" a' q6 m. f& H) [

tmp = []

( y S# b, [ y: a# j; \+ g( x `2 o

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

2 q6 Z0 |" v. b+ X/ O

p = paths[t]

( g1 u1 K( N# |$ W( y7 m

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

- A3 _6 h0 ?' B$ u/ X6 A

next(f)

' m' f( w7 \& F9 E6 a% d

for line in f.readlines():

1 q* h \$ R. Y8 c( t# m& q0 h

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

* U1 F& i1 @& q: x2 c( z% e3 e

tmp_df = pd.DataFrame(tmp)

) F. b5 a+ {# P

if model == train:

" C' h, W& P9 Q# A5 J

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

( g/ x6 m$ z7 h, u2 K4 Z/ A& x

else:

" V" q+ ^* ]' K- r/ L& [4 U1 r! J

tmp_df[type] = unknown

2 R3 ^1 \0 c4 ]& T6 g/ u

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

. [) A `9 d$ i: i

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

& b; }" a1 H' f5 d" p2 s. n

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

- ^) E. Z3 F9 C! y0 \3 B% @; F

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

1 C; i. t* w: T; @

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

3 Y! S7 J+ r/ M8 u, E

return tmp_df

" K2 m* x8 L) g- a5 n7 S5 D% f: q. K

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

- ~4 R9 U/ V! f) u2 X5 s

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

4 ~7 u) y1 q2 W& ^! z+ D

def transform_xy2lonlat(df):

% k& I8 h& N0 K" C

x = df[lat].values

7 X4 n R' z; d: e4 ?+ |* U

y = df[lon].values

% C W2 |% O: F- G; X _

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 )

' `+ K& |# N: d" M

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

# i8 ~- `) v4 ~7 x3 q( A; i& Z

return df

1 A/ C" Q8 h; m2 d" V

#修改数据的时间格式

0 }: I6 p" C) M

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

0 g, }4 n+ P' p1 p1 p d

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

) B- s1 Z% Z; X7 ]

time_str_split = time_str.split(" ")

8 m* F& j2 b2 t# x

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

* x! ]) b" W3 N! I4 s4 P+ S

time_str_reformat = time_str_reformat + " " + time_str_split[1]

+ o( \# J: G, u6 C

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

8 ^5 _! i! B# N6 z

return time_str_reformat

& ?! R( y: f/ o; `- C' W

#计算两个点的距离

1 Z! P% |; ~5 R( N

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

1 g3 r% l1 J; }

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

3 m; P; U3 P% {: `

dlon = lon2 - lon1

4 i/ Y1 ~7 y$ |/ U1 Y

dlat = lat2 - lat1

5 f' ]0 Q# x. ^* ?1 G g6 R: b% B

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

# b5 d" a4 H0 H: z9 K/ Z3 s# e

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

* W x8 ]% g0 ?

km = 6367 * c

) V1 @# e r3 e3 u0 O2 {

return km * 1000

( w+ p- k0 R7 e% ^8 d

def compute_traj_diff_time_distance(traj=None):

0 K' e Y# \# ]$ @% j% }

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

9 ]- L( N, `9 n6 w

# 计算时间的差值

o6 ?0 p% }5 m

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

I- Q2 i( [. W7 n' _, Z( O

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

1 Q% f9 y! m9 H, C, U$ O; U

# 计算坐标之间的距离

1 _2 Z8 c4 E0 x7 Z2 V& A

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

$ i O9 {/ e2 a- ]

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

! c2 V; V* o, e, m( h

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

" ]+ v" G/ d/ S

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

( Q: Z/ Z$ Q- J5 T

)

3 d6 R1 j8 @. g

# 填充第一个值

$ j4 m Y Z3 v9 K* t% b/ v5 c

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

; e4 b( j' q. J. ~

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

* R$ I- X* p/ y: i; f1 O8 W8 m

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

% U1 S1 m( A# M F, `% w$ @

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

% v$ ^) ?! _% N7 U. z8 o7 W

return traj

; p8 Z* y& r7 `% k! }

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

# S/ m/ Q# ]$ X0 [, r e

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

! \5 ]4 W0 D8 ]' {( j

time_interval_maximum=200,

9 A1 I! J7 y5 W

coord_speed_maximum=700):

* W! i4 D# {$ z) ]$ Q

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

, b1 a' {& G( b3 s5 B: k e. w" f5 Y

def thigma_data(data_y,n):

9 V% d1 S ]8 H7 I

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

6 T' z3 ~4 `0 A* m7 n

ymean = np.mean(data_y)

. A, P8 I K- {: M" }7 ^) o; x

ystd = np.std(data_y)

. W3 w' d1 ^: S. X+ m- ]6 q

threshold1 = ymean - n * ystd

) G% X3 k1 R. g9 s+ w" M

threshold2 = ymean + n * ystd

0 l* w1 n0 Q( J" o

judge=[]

2 T% M, S2 g. o" D; Y

for data in data_y:

* o7 w/ [ x+ I/ z9 m: J+ K& F% \

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

# W) X0 g" {: V4 G3 h, E2 U

judge.append(True)

5 `* s' e: J* b) Z' t1 m+ t

else:

4 L7 w+ K. R! {6 V

judge.append(False)

$ T- I( h0 S% Q; X* C. |

return judge

. |, {/ Z8 ~* [2 X: K7 P. F

# Step 1: The speed anomaly repairing

# d" p! Y( m9 h2 z( \3 i+ y Q

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

) _0 ^3 n' J/ l( w, o( U: x

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

/ g% A4 w4 |) x, u8 f

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

3 W, m) Z$ K' K R2 p J1 L

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

& d. z. q) H' r: s

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

$ ?( n) D# w4 z. T

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

) s6 |. ? a2 I4 i

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

/ n/ r: W, m2 o$ o }0 `

is_anomaly = is_anomaly | is_anomaly_tmp

, R. z( _4 b+ q8 n: K1 e

is_anomaly.index=traj.index

/ m1 s$ X$ {7 s0 f: ]' n

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

! r4 C4 M& z5 x8 a9 }

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

( p/ E/ h( K0 k$ u T. x

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

! `. ?8 ^! l1 `) {; ?# u

if len(traj) != 0:

. ?" ]* U9 W8 y

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

* o, g& V e$ d+ M; V# z' n

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

( G( y' @9 \6 c; S0 @1 l& G; J

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

( X7 ? j& N; ], A2 C) s7 B( ]

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

' L! c7 ^* i, x- {

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

5 n, ]$ `! I; c: _' h% k

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

' `. V% F+ \5 [! Y' u0 S+ h' _

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

/ s% D5 p) n: \: [" A2 ]9 W. I* ?

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

) i4 V" V$ A, ~6 r

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

0 R1 O" W( N" l' g

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

" a4 l; H3 V- {, l0 _) F

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

" R( E5 {$ L. u/ ]8 A2 {& G5 }7 n7 _

DF_NEW=[]

: m0 A" }# z0 ~+ L/ ^ S

Anomaly_count=[]

0 Z p6 G3 F T; I3 h

for ID in tqdm(ID_list):

" T6 `" `) u# s- X

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

7 t- p: f4 J/ j7 U+ A! h

df_new,count=assign_traj_anomaly_points_nan(df_id)

! t. S: Z8 h; O9 C( x

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

/ o/ Q; q1 P# d5 E7 r

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

/ W' B3 y0 X' E" C3 o8 Q7 a

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

0 h8 [0 q8 \1 X: v" i' a$ u1 x

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

' _2 x! |) y0 o- l: i+ N" V

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

! F; k2 i% ?, _) ]& n4 Z- g6 S

DF_NEW.append(df_new)

, `, d8 e% I' N% Z6 ]8 l; A, C

#将数据写入到pkl格式

+ V5 v. H3 t5 S7 J; A, b

load_save = Load_Save_Data()

4 I- X7 o, p/ r3 I- P

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

6 f4 H' r' \4 C, X, H4 g

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

( h; c# W; G- t' w" z. o

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

9 l" n$ J, ~: d; |% T

def get_diff_data():

( H( Q7 J& j0 @: {

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

. B7 p5 k/ [* t4 n

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

- [. t2 j6 u) I g5 {0 }# Y

total_data = pickle.load(f)

( c8 \ P5 r) }" U- A/ ?

load_save = Load_Save_Data()

, t4 c4 K( P9 P; I. u

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

4 Y m1 ^$ S' O

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

: O" O# ^+ [1 `0 P' B D$ B: Z

for i,datax in enumerate(kind_data):

# h& u/ L8 O- x. ]* N1 D" b

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

9 p( h P( V6 N5 M

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

: X; y4 d3 s6 E- ?

get_diff_data()

- c# A, U. K0 }- B2 R7 I* _ S9 C( H

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

5 Q; H: v2 F H! w

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

& q) R- O3 o: f: D% l5 R4 n

DF_NEW=[]

6 c) N+ e) }* D+ S% _8 S

Anomaly_count=[]

. q) T; c$ o* u* }

for ID in tqdm(ID_list):

- ~* O- U4 T( n

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

+ j g9 R- {% r y2 B

df_new,count=assign_traj_anomaly_points_nan(df_id)

2 Y7 y4 r4 G# C( h- [

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

y+ [ E% t% b

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

0 o! b3 C! n% e+ l! \: q& ?

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

G# d0 }4 G% g: ?/ @4 r* d

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

/ j- r4 k) e [' n

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

6 Z/ I/ x& ?% q" T& g" f

DF_NEW.append(df_new)

+ s8 u& U# x1 i, a1 h% _

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

, R3 T @% E8 y9 c: t

def visualize_three_traj_speed_direction():

! m; }% J" b) F! n% a+ A

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

7 Z1 C: N9 t& _2 K! s

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

, y1 }+ r9 Q+ p$ H: D) S% Q/ h

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

; m& a& E2 p& I$ ~

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

* n" W, h P$ L' n, X$ n3 G7 a" G

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

) f N2 D2 S% m3 d# n8 T, ^7 x0 r* ^

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

1 j! Q0 M6 Q& E3 D6 k

colors = [pink, lightblue, lightgreen]

! _( f I% N" Q4 [& N5 }

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

: p$ L8 f Y3 F

datax = get_random_one_traj(type=file_name)

0 F, ]3 H) s$ s/ N8 w6 V

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

* _4 W; ~6 B# i3 m& Y

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

1 X: T( Y: E: X# w: V: f6 v/ m

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

* H! _) t6 s( d% J

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

, p- y9 g( c& c$ |

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

' e, j3 H5 N M5 s

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

9 X) r" T' l& }

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

- w% f; G& ]9 R

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

6 X/ t: c1 P/ Z5 j. a9 y" \/ I, u) E3 d

plt.show()

1 A5 F, k8 h# r8 i+ j

visualize_three_traj_speed_direction()

. r5 S( A. N+ m+ ]" Q; r0 @' L
4 n$ [9 b q' c5 |* t& L

作业二:相关性分析。

$ W. v: j; |: |4 ^

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

+ l1 Q3 K# t) e' s, ?2 X" t5 r

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

2 ]9 |! g8 Q$ q; g, c/ l

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

, [0 T( N& \0 i _8 @ z

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

- h* u0 W; i/ ?( N; r/ T) {

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

' `( `; r8 I0 g

plt.show()

# C- l( Y2 v9 j . w* V( Z8 V3 T* q& h' J. y3 ~

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

' p+ ~' H8 E, C3 ] ! _) j5 W2 k4 D; C8 c6 _ # ]/ G3 m6 ?5 j7 K+ x9 b0 w0 m- X 2 h" r8 |3 |2 h0 ^ % R4 ?. C) H, s0 ? \
回复

举报 使用道具

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