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

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

[复制链接]
0 W& R4 y/ o" V9 F: }7 Y" {* A

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

赛题:智慧海洋建设 2 y- ? b: C0 n' p" z

数据分析的目的:

% ?9 u( I' [. Z- ] O+ e 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

# W' ^9 b* S% p& a3 B- i+ n Y" F

2.1 学习目标

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

2.2 内容介绍

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

数据特性和特征分布

( d0 g4 i3 F& L" k1 s- @

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

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

import pandas as pd

$ \# Z% I6 M! d! r5 N3 v

import geopandas as gpd

k9 }: v; {" E& _) m

from pyproj import Proj

8 o: I( @" c+ \3 A

from keplergl import KeplerGl

/ k/ ?2 g" f* G& j

from tqdm import tqdm

% s. P3 B) o: V1 K1 ^6 K

import os

1 t0 R$ `8 [6 p/ R

import matplotlib.pyplot as plt

U- t9 L# n& p

import shapely

9 ]. k _: _6 t: K* {- r

import numpy as np

# p5 S- }0 W6 p* f4 V& s. P

from datetime import datetime

0 F$ k: f# e1 t8 r: k/ {' _1 S

import warnings

n5 v9 g1 @5 t; W

warnings.filterwarnings(ignore)

( R' U, W8 B3 M

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

4 o$ }6 z) z' D9 i

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

* U' W9 {, h3 ]3 b- B; |

#获取文件夹中的数据

# u1 a* e" E# g

def get_data(file_path,model):

' Z) x8 I: l9 c& i e$ W0 A8 \1 |" Z

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

2 X% Q& V- y! i0 y' t0 h. D

paths = os.listdir(file_path)

% M, G" U+ _5 s/ O! |) W/ H

# print(len(paths))

' I( S. O3 W' O C! g

tmp = []

& m0 d# P9 L' t/ D

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

) B" W+ _, e/ h4 _, L; I

p = paths[t]

: n+ S0 {4 w' b2 n

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

& Z7 u5 Y- J8 q& S3 Q& p) a

next(f)

( }3 Z: f, r0 }$ c4 D

for line in f.readlines():

- G9 p. X3 o" A# ]+ h( k$ d4 m

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

; m4 @& ^$ b5 E! ]& X& y

tmp_df = pd.DataFrame(tmp)

# E2 s- P4 V9 a' r# U, y6 t$ D8 t

if model == train:

1 V6 X% W6 H# ?5 @! l% p9 f( {

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

- `. |4 z4 l0 m+ @5 Q5 v

else:

7 y, k- V) W/ {

tmp_df[type] = unknown

4 Z6 @2 P* H4 e+ T+ O

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

% @2 s# i7 C0 n+ f' o3 s3 V9 ?

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

. O2 f V8 r1 q# i2 a9 G

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

$ L9 T" p1 c1 [0 X$ H) o

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

2 E% ]0 I$ D: c, K

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

$ b i; l+ ?2 V, S6 g

return tmp_df

- Y8 O) L& R% e) ]9 V

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

/ ]$ p* v! x0 R) h9 Q) ~

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

- t# V* y9 @' B( I, v

def transform_xy2lonlat(df):

$ T4 Y1 v. t7 [, U

x = df[lat].values

6 D" S/ l1 S; ?/ u; _% j

y = df[lon].values

1 H1 r# S8 D- @; U: c$ p# U7 Q8 P

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 )

' z2 C: A9 \* i6 ]" N; H

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

/ Y4 k& s$ T# o# f, r2 f

return df

) U- G! t7 g) @0 N0 q/ }6 o

#修改数据的时间格式

/ P' D+ U) T+ N+ U% e

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

5 |; o- b4 a. A4 P

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

! E, a( U. g+ ~$ o1 E4 { ~ o

time_str_split = time_str.split(" ")

( L! D! d+ X2 P* Q9 r3 f( c& ?& h

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

" N' e" @; N+ y5 |0 H/ A4 v6 a

time_str_reformat = time_str_reformat + " " + time_str_split[1]

# h; ^5 B0 D1 n3 j% K7 \

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

# |. y5 m: Y6 @- j6 _2 ?" }

return time_str_reformat

" y2 F: K2 [/ {

#计算两个点的距离

2 J3 N2 T8 H- b& H8 [

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

8 x* _7 J; s. S7 ] v

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

5 M+ P) y- Z9 T# N5 ?

dlon = lon2 - lon1

' y3 {: d) a8 n- t% K8 H2 h0 d- {

dlat = lat2 - lat1

3 m' x0 L) p" o2 ?

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

' g8 W9 f+ Q) C# G4 |( f$ F

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

7 e9 d' \1 z1 ^, I0 R& V

km = 6367 * c

4 |9 C( ]/ B$ z) {; q0 ?) H/ S

return km * 1000

& W( Q$ C! f& S0 ^

def compute_traj_diff_time_distance(traj=None):

7 F" |3 S. t6 b8 p$ R6 M. |

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

: M) @3 D* D. R6 w) @8 H7 p4 F0 G

# 计算时间的差值

, ?& @3 G+ }! I3 u7 E

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

- @: n% W1 i( q. t5 O, u. y

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

5 c# Y/ n9 l6 D/ \- T+ o

# 计算坐标之间的距离

! R; H2 i; H) V% p: J

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

, h9 \0 @* n" h7 w+ Z2 `: f

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

" ^* @! u, o5 d

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

7 u& B g% c5 F$ }+ i

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

5 | ~* f' q1 }( ^

)

& c+ K$ N" ?2 @

# 填充第一个值

: w% A. g& B# n+ M% \/ u

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

5 }8 J0 D1 Y" q8 p1 T8 h4 b. Z0 ]

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

8 G) d0 r" `& o) q1 x

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

8 `- O8 v1 y5 u" o, w& e* ^. x" q

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

$ {3 |1 p1 r' ]6 r

return traj

) h2 i1 e3 t& ~* G; q! ?) w

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

- }; d0 p1 `9 O9 c9 m0 {% A

def assign_traj_anomaly_points_nan(traj=None, speed_maximum=23,

# p4 M4 c/ E) C" K, j

time_interval_maximum=200,

0 W2 `8 [0 h0 Q# q, X9 k8 o

coord_speed_maximum=700):

y/ M" h8 Q$ G. i2 e" {

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

6 ]3 m2 B/ N/ ^: ^$ w6 p; Z' `

def thigma_data(data_y,n):

$ P$ B4 l7 u" K& s h

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

9 ]7 p3 f8 a2 p6 l& b

ymean = np.mean(data_y)

) y3 ^! r( ~8 z( M+ q6 P4 Z

ystd = np.std(data_y)

1 J# a7 N0 V3 ?, G

threshold1 = ymean - n * ystd

8 i4 |& n7 ]+ R7 |" j8 I, R

threshold2 = ymean + n * ystd

' U. S8 B8 `# k5 u- K

judge=[]

7 \! n, n. R( s1 `/ v ]6 G/ @

for data in data_y:

( P1 y) T& x% d* Q& ?* j: ?% q

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

8 x4 p" U2 |, n5 G! u9 \

judge.append(True)

; D6 s6 x0 h9 h$ X

else:

$ z7 ?' i" k% f4 Y7 ?

judge.append(False)

, l. J, y1 B0 N" |8 A

return judge

* x$ Z, w9 e1 y2 K7 v" I) d

# Step 1: The speed anomaly repairing

l: D7 s4 g& S( Z9 d4 Q: h2 Z

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

) c( G+ [. S0 f$ A

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

9 I: |. s: h' w' G4 h- c) ^

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

$ W$ u) J& P7 w1 V( A

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

L: z9 g( ?1 o; I6 Y

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

1 L2 c' ]) _: W3 ]+ Y; K

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

# _3 _- s; m9 w& O! [: h& w, x

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

: A" E; S: n5 J8 K

is_anomaly = is_anomaly | is_anomaly_tmp

$ s% V2 `, d% `; u' b

is_anomaly.index=traj.index

2 C, E: C" h) r: k

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

1 p# V1 o( ?) U" c! i

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

0 \, `# C Y* [

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

1 M( m7 I# w8 |9 J* }0 v

if len(traj) != 0:

" v# \* a) N; ]# w" n) n

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

. V) O$ w9 R( n+ Z

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

4 C1 x8 F8 @4 n) {, W2 o( p

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

# u7 k# D. F3 X" ?& u! |

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

& i U# w' ^: _% h: Q

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

! I; [, Z' F" Q E; n6 _" I

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

8 h: O- n2 y) ~6 x9 m$ v% j( S9 n

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

7 h% `5 L- O3 v7 r. M( {

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

2 b, ]) ~2 U/ ?2 p$ o t" I

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

, l( R) [) g/ @9 J2 ~" k7 e# n

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

& ^& L G& v$ E/ \+ V9 N

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

$ ]# ~) [# E4 h' T. ^4 M8 |

DF_NEW=[]

, z9 R6 q" o. Y; n9 k+ ? M! G& t# n" m! o

Anomaly_count=[]

0 q, @# G% W8 }$ O& _. |; p

for ID in tqdm(ID_list):

, A* s2 }( Y2 o

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

- \0 S$ k; f( k1 V- F" E0 Y. x

df_new,count=assign_traj_anomaly_points_nan(df_id)

: C$ c# U8 }4 i9 w7 O3 E8 f

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

8 \2 @5 p# P2 F2 h5 \) ]4 U$ y

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

+ u( K7 ?* R+ W

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

% J. _/ G* ~$ T$ T

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

: c6 M& }( d* q* t9 B" U. f3 n

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

7 P2 F1 Z2 A' E# X3 J

DF_NEW.append(df_new)

4 y4 R# Q: m. r9 r- d! a

#将数据写入到pkl格式

# o" v, w* x, e

load_save = Load_Save_Data()

0 g7 a+ Z! O% M# X9 g, k$ n

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

, ?7 Z* L6 q; b* q4 D: z; z

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

; O H. v, y b+ P

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

( q4 ^& s" k2 s8 d7 ~$ T X

def get_diff_data():

0 L3 [! g) g9 ?6 `

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

9 D, a! m$ b! y$ Z. ?4 K

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

* `6 K: w/ K/ f

total_data = pickle.load(f)

4 q+ J& |4 l# E% H+ l8 Z9 ~( q* K& m& ^

load_save = Load_Save_Data()

' x0 ^! d- k: Z( Y* E

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

9 ~ E9 Q& A3 d( j

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

, a* F8 B" S6 ]# w3 ~' d0 H

for i,datax in enumerate(kind_data):

+ Y6 d7 Y9 q, ?* P/ Z/ y

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

9 l) ~3 D6 Z1 l( `/ |5 G4 j

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

6 `% Q# s; {) y/ r- e4 V/ d/ O

get_diff_data()

! ^/ h$ J# \+ ]) g3 w( X6 k

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

* R7 H1 m, F a3 |9 X: D8 ]8 r

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

* n7 _& | B) o, @7 t7 A

DF_NEW=[]

& \+ ~" c* _ \& S

Anomaly_count=[]

8 {2 t/ I2 l) I2 Y) Z! q8 B6 o

for ID in tqdm(ID_list):

# \7 }! ^$ }/ y' Y) o/ d' _0 t

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

5 g( f4 d! [! G

df_new,count=assign_traj_anomaly_points_nan(df_id)

! N) z7 D$ n' Y" l& T

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

* A( k' }" I9 ~/ c

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

3 O( T9 D! { [% S$ K0 I

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

# V: W! ]) T: F

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

( @5 D& T. J$ ?* R7 t. l

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

* ~' B: |: u9 b) x4 n1 Z

DF_NEW.append(df_new)

8 P( u4 i2 b1 N

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

" C7 l+ |! x1 B8 r8 \- E+ v

def visualize_three_traj_speed_direction():

6 z6 B4 N5 _ T

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

3 B9 G1 X& r% p$ n

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

. C0 N) Z. M* `: Y

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

6 |6 c3 u% S @

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

3 @5 e- a% D9 E4 ~/ a

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

1 s: i( P7 D1 z. {. o& g

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

% C' i& E. H1 I) ]( F

colors = [pink, lightblue, lightgreen]

4 `; z8 q$ {0 o% S& B, y0 m6 a' B5 ~

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

- O/ O3 F5 o. B6 q

datax = get_random_one_traj(type=file_name)

7 d1 Z" l2 Z; X! e# X

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

1 E1 S7 `9 R9 Y$ m& P

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

5 _) L# \2 c2 }9 f* g f# f* S, z

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

: g' I; S" }2 ]; V3 K1 Y ]

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

; p [5 K! e) M- j! \

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

+ [# _6 `2 U0 X- c

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

- I1 }: s& f+ Q- n

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

$ Z) t/ R6 r. E, O7 H' x

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

: @* W7 |8 h0 T0 E* N* t/ @

plt.show()

* r P8 C1 U2 T) S: b" Y

visualize_three_traj_speed_direction()

$ N5 O% e1 V3 R# U! x% k- V# X2 {
9 ~3 W5 J4 D# K R' P

作业二:相关性分析。

% k- V6 k" y8 D3 T# l/ Y/ |: @

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

0 `$ Z' X0 c* @( a

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

2 W* Z" Z: |' z/ ~ r8 |+ U& s

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

# _! f# n5 }! E' S2 Y1 t9 P6 S9 b; R

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

6 v8 }; b% o8 o' ?1 a

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

7 |& f X6 d8 m3 `

plt.show()

3 i+ d& v# f6 ~$ Y8 D - ?) A2 r6 W0 D9 k7 R/ n

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

5 B1 ?: s; l( c4 i - P6 O# a* {) R( u ' @* V0 c9 ^. ]$ f- l0 d * M* p9 A: U: I8 C" D2 @. b2 m6 z: z9 l$ I+ d+ z& G) u
回复

举报 使用道具

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