Skip to content

Instantly share code, notes, and snippets.

@TooTouch
Created December 9, 2020 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TooTouch/c3781d0df9e49381d4446132463c239f to your computer and use it in GitHub Desktop.
Save TooTouch/c3781d0df9e49381d4446132463c239f to your computer and use it in GitHub Desktop.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set_style("whitegrid")
from tslearn.generators import random_walks
from tslearn.clustering import TimeSeriesKMeans
import matplotlib as mpl
plt.rcParams["font.family"] = 'NanumGothicCoding'
mpl.rcParams['axes.unicode_minus'] = False
from tslearn.generators import random_walks
from tslearn.clustering import TimeSeriesKMeans
date = pd.date_range('2019-01-01','2020-06-30',freq='d')
X1 = random_walks(n_ts=14, sz=365, d=5, random_state=42)
X2 = random_walks(n_ts=14, sz=len(date)-365, d=5, random_state=42)
X = np.concatenate((X1, X2), axis=1)
print('X.shape: ',X.shape)
km = TimeSeriesKMeans(n_clusters=4, metric="euclidean", max_iter=5, random_state=0)
prediction = km.fit_predict(X)
print('km.cluster_centers_.shape: ',km.cluster_centers_.shape)
trend_k0_cat1 = pd.DataFrame({'v':km.cluster_centers_[0,:,1]}, index=date)
trend_k0_cat1 = trend_k0_cat1.resample('M').mean()
plt.figure(figsize=(8,4))
sns.lineplot(x=trend_k0_cat1.index.month, y=trend_k0_cat1.values[:,0],
hue=trend_k0_cat1.index.year, palette=['blue','red'],
linewidth=10)
plt.legend(fontsize=13)
plt.title('특성1의 2019 대비 2020년 소비트렌드 변화', fontsize=15)
plt.ylabel('군집 중심점', fontsize=13)
plt.xlabel('월(month)', fontsize=13)
plt.tight_layout()
plt.savefig('../images/sample/trend_example.jpg', dpi=300)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment