如何使用KNN/K-means在数据帧中聚类时间序列

gum*_*ump 6 python cluster-analysis time-series

假设一个包含1000行的数据帧.每行代表一个时间序列.

然后我构建了一个DTW算法来计算2行之间的距离.

我不知道接下来要做什么来为数据帧完成无监督的分类任务.

如何标记数据框的所有行?

hhh*_*hhh 8

定义

KNN算法 = K-最近邻分类算法

K-means =基于质心的聚类算法

DTW =动态时间扭曲时间序列的相似性测量算法

我将逐步介绍如何构建两个时间序列以及如何计算动态时间扭曲(DTW)算法.您可以使用scikit-learn构建无监督的k-means聚类,而无需指定质心数,然后scikit-learn知道使用所谓的算法auto.

构建时间序列并计算DTW

你有两个时间序列,你可以计算DTW

在此输入图像描述 在此输入图像描述

import pandas as pd
import numpy as np
import random
from dtw import dtw
from matplotlib.pyplot import plot
from matplotlib.pyplot import imshow
from matplotlib.pyplot import cm

from sklearn.cluster import KMeans
from sklearn.preprocessing import MultiLabelBinarizer 
#About classification, read the tutorial
#http://scikit-learn.org/stable/tutorial/basic/tutorial.html


def createTs(myStart, myLength):
    index = pd.date_range(myStart, periods=myLength, freq='H'); 
    values= [random.random() for _ in range(myLength)];
    series = pd.Series(values, index=index);  
    return(series)


#Time series of length 30, start from 1/1/2000 & 1/2/2000 so overlap
myStart='1/1/2000'
myLength=30
timeS1=createTs(myStart, myLength)
myStart='1/2/2000'
timeS2=createTs(myStart, myLength) 

#This could be your dataframe but unnecessary here
#myDF = pd.DataFrame([x for x in timeS1.data], [x for x in timeS2.data])#, columns=['data1', 'data2'])

x=[xxx*100 for xxx in sorted(timeS1.data)]
y=[xx for xx in timeS2.data]

choice="dtw"

if (choice="timeseries"):
    print(timeS1)
    print(timeS2)
if (choice=="drawingPlots"):
    plot(x)
    plot(y)
if (choice=="dtw"):
    #DTW with the 1st order norm
    myDiff=[xx-yy for xx,yy in zip(x,y)]
    dist, cost, acc, path = dtw(x, y, dist=lambda x, y: np.linalg.norm(myDiff, ord=1))
    imshow(acc.T, origin='lower', cmap=cm.gray, interpolation='nearest')
    plot(path[0], path[1], 'w')
Run Code Online (Sandbox Code Playgroud)

用KNN分类时间序列

关于应该贴上什么标签以及使用哪些标签的问题并不明显?所以请提供以下详细信息

  • 我们应该在数据框中标注什么?DTW算法计算的路径?
  • 哪种类型的标签?二进制?多类?

之后我们可以决定我们的分类算法,也就是所谓的KNN算法.它的工作原理是你有两个独立的数据集:训练集和测试集.通过训练集,您可以教算法标记时间序列,而测试集是一个工具,通过该工具我们可以测量模型与模型选择工具(如AUC)的工作情况.

小谜题保持开放,直到提供有关问题的详细信息

#PUZZLE
#from tutorial (#http://scikit-learn.org/stable/tutorial/basic/tutorial.html)
newX = [[1, 2], [2, 4], [4, 5], [3, 2], [3, 1]]
newY = [[0, 1], [0, 2], [1, 3], [0, 2, 3], [2, 4]]
newY = MultiLabelBinarizer().fit_transform(newY)
#Continue to the article.
Run Code Online (Sandbox Code Playgroud)

关于分类器的Scikit-learn比较文章在下面的第二个枚举项中提供.

使用K-means进行聚类(与KNN不同)

K-means是聚类算法,你可以使用它的无监督版本

#Unsupervised version "auto" of the KMeans as no assignment for the n_clusters
myClusters=KMeans(path)
#myClusters.fit(YourDataHere)
Run Code Online (Sandbox Code Playgroud)

这是一种与KNN算法截然不同的算法:这里我们不需要任何标签.我在第一个枚举项目中为您提供了有关以下主题的更多材料.

进一步阅读

  1. K-means是否包含K-最近邻算法?

  2. 关于scikit中的分类器的比较在这里学习