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

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

[复制链接]
' f$ {. m3 H. n; Q

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

赛题:智慧海洋建设- J0 R5 P, D& y( _2 J* J2 u! |

数据分析的目的:

3 ]! @8 X/ k! C. z% m 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

0 C5 y$ @, j) d" l' V3 A- _4 G

2.1 学习目标

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

2.2 内容介绍

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

数据特性和特征分布

) B; x4 { u+ O/ ~- F' i

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

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

import pandas as pd

7 Q6 t) Y* Q4 I- Y

import geopandas as gpd

% _& R; S" V, A: ?) ]. s

from pyproj import Proj

3 H: e# P5 \( S( {2 F

from keplergl import KeplerGl

& A, B! @9 j g7 M h1 `

from tqdm import tqdm

7 j, M \% f$ }5 l

import os

6 J9 a5 _' U- Q" t: c- s

import matplotlib.pyplot as plt

+ C/ p2 t$ w" A$ R

import shapely

* K7 |2 c" E2 w* ~; e7 H

import numpy as np

5 F" S) m6 U" Q2 I' c

from datetime import datetime

( L7 O& z0 V- D4 H L

import warnings

* [% P" n$ q) X

warnings.filterwarnings(ignore)

r) [/ ?: E5 @9 Q" f- ~

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

8 R; q$ B, R% P, m- Z

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

`" I/ y# q! \7 C5 E* c

#获取文件夹中的数据

9 C/ [" M- u# i+ T- l. r

def get_data(file_path,model):

: |. C) A6 S; u! y

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

; X4 u% k# a. \( k4 C3 ]

paths = os.listdir(file_path)

, f/ [( ^( {+ x5 C0 b( D

# print(len(paths))

* P+ u9 y, w/ H& ? Z- H) w* s

tmp = []

/ ?: `; E7 `# I/ c. a3 ^7 {! C

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

; t2 q& |' r) X

p = paths[t]

- m: `- ^9 L1 t( E0 C8 S6 e

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

i) g$ l! L2 S5 u1 _, ^

next(f)

/ V: Z: i {( ]8 D6 W* `

for line in f.readlines():

T' S3 I8 {. D" K2 {" f( h

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

0 f: L# o5 y! z, K- X5 |) v

tmp_df = pd.DataFrame(tmp)

) E6 y U* Q2 M1 B/ h( R! t% g

if model == train:

; {# b3 a' [, r% Y' c E

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

6 g: D6 A0 p& K& a$ V

else:

/ x! P. z: k8 p' I" N3 N

tmp_df[type] = unknown

" W: E3 y; B6 R6 ]$ R

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

5 u$ F; R- H: Q2 ^& t% m

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

2 l+ v: B+ S, e; N, I% O

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

7 M7 v" n; m% {2 s) ?2 E- S; Q5 C

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

9 q, o% r/ {( w& R9 C

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

, L: u" L! _9 @5 K `" J

return tmp_df

7 _5 s3 Q- Q% E- M' s) K/ F

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

5 ?" }3 |& C. q+ a8 e5 ]9 a

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

" g/ T6 W9 G0 b5 }

def transform_xy2lonlat(df):

5 F4 y/ j2 V# F$ t$ u! A) z

x = df[lat].values

( ]: b( F- h7 Z

y = df[lon].values

! M9 ~4 G% ]0 ]

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 )

" }2 g# u9 s+ Q" C- |4 u

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

$ l3 \. G( g. d% @( R+ ]& K

return df

* |. {3 a" O/ h! P0 K- K7 ]5 a

#修改数据的时间格式

/ ~+ n* w8 A/ f' A: a. \, ^

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

6 _2 L4 H8 y! ~7 |% F5 g# I& [% ~

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

$ A7 u3 g3 c- G* I# E

time_str_split = time_str.split(" ")

% y1 B4 M* @: b; F

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

7 {$ Q0 s p' Q( p

time_str_reformat = time_str_reformat + " " + time_str_split[1]

2 D- \2 m0 \5 V1 l I( L

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

* ?; q; n# I5 P# @' P# K

return time_str_reformat

# z" W( A( _3 E# w+ x/ {1 y

#计算两个点的距离

% \/ O! i6 C$ a/ [2 ~0 i2 u

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

+ Q! g8 W' @& [

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

# I+ r" G& |' h. k

dlon = lon2 - lon1

3 F! b, y' t9 u- Q2 C

dlat = lat2 - lat1

% A5 q2 s' c2 x# V

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

% S1 Q7 ^2 o" V

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

: h7 S' Z' s6 `$ w

km = 6367 * c

" k1 H8 c0 y" J/ V' v5 b4 y6 [

return km * 1000

/ B( W4 \- k3 u( m

def compute_traj_diff_time_distance(traj=None):

4 b2 M3 d! F0 |; u, A

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

, q- F! U8 t# d- v- q8 ~- g' G: r$ S7 B

# 计算时间的差值

% Q$ t! z9 ?7 E( y

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

' G& O" U1 b$ f+ z

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

7 Q N& H1 c9 ?, d- `- Y

# 计算坐标之间的距离

' G W) H. ~3 |% V7 a- i( l

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

: N% w* L) m( j, l

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

, |) o+ V5 n* p- M2 b" g, \! ^7 i

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

. w4 f# h; D9 L5 k9 x" r

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

7 J' W" Z, S! A- q, O

)

/ H" v, g: N1 U: D$ ^5 E2 U: _& j

# 填充第一个值

+ L2 B4 t; r* g; c; D* O5 N4 L; F% ~

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

7 b3 n: c' K% z

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

6 z- i6 ]$ a# \0 Y

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

5 k/ O# p6 v5 v/ c' s$ d

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

5 U, R3 r8 [# V+ E7 k$ i- f2 F2 s

return traj

0 t2 N: z* K3 T: p J

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

$ s( y/ T7 f+ W# s$ V

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

) |* e7 b" B1 d

time_interval_maximum=200,

7 b9 ^+ z0 Z4 U6 G5 v) u. e

coord_speed_maximum=700):

9 {& e+ H( H+ q3 W9 }, n

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

" `2 `' g8 U; Q% e# K" q' J

def thigma_data(data_y,n):

) T1 T. x! `# f& n

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

7 t @5 M5 O E9 y0 V( h. e0 L1 k

ymean = np.mean(data_y)

6 w8 j# k$ f7 Z# k% J

ystd = np.std(data_y)

7 g9 H" p& {+ l7 {( D6 a- E

threshold1 = ymean - n * ystd

2 q6 O. {2 r" ^- v( |0 Q* L

threshold2 = ymean + n * ystd

2 C9 F! k+ m. E1 N. y( F

judge=[]

; O/ q( r) y5 t: G0 t; j) ?

for data in data_y:

% b$ H" Z K+ F# U

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

0 m9 H' u8 N+ m3 v1 _3 c

judge.append(True)

' n$ z" t) P6 u8 G9 K1 J

else:

3 j) f3 ?1 L) j8 N/ X. g

judge.append(False)

( s! }, ^* X% c- `' g9 P: D. V. v* ]

return judge

1 s2 {6 O4 h5 m! [) |, H6 ~' a: f

# Step 1: The speed anomaly repairing

( I# v) k, n2 c5 i# F5 L

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

8 a$ H. a2 @8 _7 |4 G$ d

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

( a7 B/ ^& E, \- P; V! C u

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

& Y2 c7 I8 D% k* E7 B; ]5 T

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

7 X' f/ k3 ^* y G7 j. z* T5 B2 _( o

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

8 F. H& I( R5 }! y$ u X$ X

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

6 u1 y7 u6 u w5 I" X% R0 g' `

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

/ |( U3 U! J1 ?5 Z) K) K6 k

is_anomaly = is_anomaly | is_anomaly_tmp

\, h* ~( d) |* M5 r4 t5 s3 j4 C# w

is_anomaly.index=traj.index

" n" p1 q t$ O% M& l# @" p

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

# O6 \, h8 R+ _

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

( I2 W9 w& o+ r3 C9 _7 R

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

3 A( x l W! x# R. F3 G. \/ f2 X

if len(traj) != 0:

1 r3 J3 C1 }( n" a7 s0 o

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

+ {3 z9 K5 d+ t& r7 M0 \

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

8 n6 G: G: P U, S

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

" q1 K& P/ V8 J, N

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

1 O/ N4 b3 D( q1 J

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

' p+ D" D$ q2 I

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

% T5 a# t4 |0 U+ n7 I& I/ \0 A

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

7 N1 T- \, x9 N+ Y& f8 J0 K# M2 o3 R

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

+ X6 Z; W& f. a: G

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

1 R, ^9 E# V3 ^" ~+ S7 v

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

7 t# S1 T7 L* Z7 K$ l

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

/ {+ w% L _6 K( c

DF_NEW=[]

2 D9 }8 z: z& B+ l. r

Anomaly_count=[]

6 T8 o$ `8 }0 X# v6 P) ^

for ID in tqdm(ID_list):

! ~+ I8 b% ]( C( ~; f H

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

8 Z. k6 ?. Q* @, y+ a

df_new,count=assign_traj_anomaly_points_nan(df_id)

6 I' z) O8 g! f, }& K

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

; V$ t. T: x% t# h1 K

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

8 O8 W. M3 U+ {3 U% J' o9 ^+ I" Q

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

3 J. D6 U$ p: l

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

2 F) ?3 m2 R% Z7 d3 |, n

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

+ y l0 A1 v& R' j

DF_NEW.append(df_new)

9 F7 o* A, P" E$ c1 J3 M

#将数据写入到pkl格式

9 B, p5 F+ R w( e% d

load_save = Load_Save_Data()

, E! V8 ]9 x8 N2 v* D

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

. c8 l, |# P8 x. D& Z0 e7 L

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

2 C; r' [; L4 ?& q" h

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

# s# b t/ e" _( G; ^

def get_diff_data():

4 f& V) ]8 x6 a6 K) v

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

- Z# `* ~3 M9 @

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

: J) K' S% T% S5 @

total_data = pickle.load(f)

1 ?9 K) g. i# D6 A$ u. N1 t5 A! A

load_save = Load_Save_Data()

. {# ~0 h$ ?# M- H

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

# p0 W/ j5 }8 i0 H+ f0 h h$ H

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

4 O2 Z2 X; j" [9 I8 u6 f

for i,datax in enumerate(kind_data):

4 h6 w5 O5 s" {6 K0 c2 D; W

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

: J4 v$ a3 z! V# o

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

5 v% P( V% _6 o; J/ f3 C

get_diff_data()

$ N! x' m5 R' X9 ?/ z, S

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

6 k+ o7 |) d! U

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

! e; x' ]% X7 q6 k+ y+ j

DF_NEW=[]

; l" h# h0 V1 G0 |. g2 u( a

Anomaly_count=[]

9 S7 @7 L& W1 g- g( h

for ID in tqdm(ID_list):

2 I* X1 e6 y) B }( V4 z% f

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

@4 O% s& z1 U- m

df_new,count=assign_traj_anomaly_points_nan(df_id)

, z! n6 d4 ^0 y: m1 W+ B

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

$ M9 f0 u) W# ]* }# g2 f

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

1 N! T4 f4 o2 `5 k8 ~ d8 Q

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

3 \# x) u. R9 s* F0 k* U% g

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

* o- M( p3 W0 M* C3 W5 J' Q

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

( @1 l/ r7 _! D0 B

DF_NEW.append(df_new)

; _1 o6 l, P8 }9 n& K

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

$ I, \5 F! K9 a: y

def visualize_three_traj_speed_direction():

; P/ L2 \1 U1 b8 ^: R

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

$ ]2 m, b5 n% d( B/ p3 h2 b8 `

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

0 k/ o" _9 I* ^, Z

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

1 @+ E, ^. g6 n7 k- b& d! v1 {3 L, @

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

- q$ n' J8 Q4 T. X

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

) o; _- D/ T! \; P8 E) a+ Z

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

& t) ^8 g2 d3 F0 I" p

colors = [pink, lightblue, lightgreen]

* G( H& j9 Y+ a* p6 ^# j

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

. [3 t) H) @: \1 E( ~/ Y3 t

datax = get_random_one_traj(type=file_name)

: I I( o6 g# y0 t {

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

# U" c6 W$ m# T- Z

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

( L9 J: E3 ]+ Y

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

. R" R6 U1 d! L: b4 T1 w

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

1 ?( w) |. [, B, l4 `6 `4 o5 L

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

4 J# R& X& X- ?

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

V: x. M P# n9 s

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

: C1 h' x, W& L* }: C+ z' E

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

, r4 S' D( }' y5 \% Y

plt.show()

9 |) G8 Z2 }+ J, Y5 p2 y8 a

visualize_three_traj_speed_direction()

1 |0 z, C% X2 e+ s) P* c+ c3 M0 L$ v* t
" |/ ~: O5 I. z! n4 j3 ?

作业二:相关性分析。

+ T# V& I+ F0 \8 L3 @! s. h+ |

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

, {8 k+ ?( ^& A5 I) V) f

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

. ?3 x6 ^, Q. E% J" R G9 N

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

/ C. ~ O5 Y# y4 Q" Z3 H: M* O4 P

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

8 l3 W- A) v ?7 j4 r

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

1 c* X: Z- ?( @5 l5 k5 u& A9 d

plt.show()

1 Y' T! N1 ]- L5 L ~8 G ( s0 r4 t+ t( I3 i

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

3 n+ N% m! e7 Y2 q- }3 V % ]7 F+ L+ ]1 A2 D7 Y1 _4 a( D4 M# o: ]; y1 V $ ]( Q( f e9 ]8 Q ! I- N. c+ {6 y# |: A
回复

举报 使用道具

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