自学内容网 自学内容网

Pandas处理时间序列之光谱分析与聚类

import matplotlib.pylab as plt
%matplotlib inline
import numpy as np
from numpy import fft
import pandas as pd

一、光谱分析

• 将时间序列分解为许多正弦或余弦函数的总和
• 这些函数的系数应该具有不相关的值
• 对正弦函数进行回归

光谱分析应用场景

基于光谱的拟合

基于光谱的拟合是一种常见的分析方法,它通过将实际观测到的光谱数据与已知的光谱模型进行比较和匹配,来获得对未知样品的估计或预测。该方法可以用于光谱分析、化学定量分析、物质识别等领域

示例

#傅里叶外推算法
def fourierExtrapolation(x, n_predict):
    n = x.size
    n_harm = 5                     # 设置了模型中的谐波数量,即傅里叶级数中所包含的谐波数量
    t = np.arange(0, n)
    p = np.polyfit(t, x, 1)         # 利用线性回归找到了序列 x 中的线性趋势
    x_notrend = x - p[0] * t        # 通过减去线性趋势,将原始数据 x 去趋势化
    x_freqdom = fft.fft(x_notrend)  # 对去趋势化后的数据进行傅里叶变换,将数据从时域转换到频域
    f = fft.fftfreq(n)              # 生成频率数组,用于表示傅里叶变换结果中每个频率对应的频率值
    indexes = list(range(n))
    # 对频率数组进行排序,以便从低到高选择频率成分
    indexes.sort(key = lambda i: np.absolute(f[i]))
 
    t = np.arange(0, n + n_predict)
    restored_sig = np.zeros(t.size)
    for i in indexes[:1 + n_harm * 2]:
        ampli = np.absolute(x_freqdom[i]) / n   # 振幅
        phase = np.angle(x_freqdom[i])          # 相位2
        restored_sig += ampli * np.cos(2 * np.pi * f[i] * t + phase)
    return restored_sig + p[0] * t


# 利用傅立叶变换原理,通过拟合周期函数来预测时间序列的未来值
x = np.array([669, 592, 664, 1005, 699, 401, 646, 472, 598, 681, 1126, 1260, 562, 491, 714, 530, 521, 687, 776, 802, 499, 536, 871, 801, 965, 768, 381, 497, 458, 699, 549, 427, 358, 219, 635, 756, 775, 969, 598, 630, 649, 722, 835, 812, 724, 966, 778, 584, 697, 737, 777, 1059, 1218, 848, 713, 884, 879, 1056, 1273, 1848, 780, 1206, 1404, 1444, 1412, 1493, 1576, 1178, 836, 1087, 1101, 1082, 775, 698, 620, 651, 731, 906, 958, 1039, 1105, 620, 576, 707, 888, 1052, 1072, 1357, 768, 986, 816, 889, 973, 983, 1351, 1266, 1053, 1879, 2085, 2419, 1880, 2045, 2212, 1491, 1378, 1524, 1231, 1577, 2459, 1848, 1506, 1589, 1386, 1111, 1180, 1075, 1595, 1309, 2092, 1846, 2321, 2036, 3587, 1637, 1416, 1432, 1110, 1135, 1233, 1439, 894, 628, 967, 1176, 1069, 1193, 1771, 1199, 888, 1155, 1254, 1403, 1502, 1692, 1187, 1110, 1382, 1808, 2039, 1810, 1819, 1408, 803, 1568, 1227, 1270, 1268, 1535, 873, 1006, 1328, 1733, 1352, 1906, 2029, 1734, 1314, 1810, 1540, 1958, 1420, 1530, 1126, 721, 771, 874, 997, 1186, 1415, 973, 1146, 1147, 1079, 3854, 3407, 2257, 1200, 734, 1051, 1030, 1370, 2422, 1531, 1062, 530, 1030, 1061, 1249, 2080, 2251, 1190, 756, 1161, 1053, 1063, 932, 1604, 1130, 744, 930, 948, 1107, 1161, 1194, 1366, 1155, 785, 602, 903, 1142, 1410, 1256, 742, 985, 1037, 1067, 1196, 1412, 1127, 779, 911, 989, 946, 888, 1349, 1124, 761, 994, 1068, 971, 1157, 1558, 1223, 782, 2790, 1835, 1444, 1098, 1399, 1255, 950, 1110, 1345, 1224, 1092, 1446, 1210, 1122, 1259, 1181, 1035, 1325, 1481, 1278, 769, 911, 876, 877, 950, 1383, 980, 705, 888, 877, 638, 1065, 1142, 1090, 1316, 1270, 1048, 1256, 1009, 1175, 1176, 870, 856, 860])#原始时间序列数据
n_predict = 100 # 未来进行预测的数据点数目
extrapolation = fourierExtrapolation(x, n_predict) # 调用fourierExtrapolation函数,使用原始数据和预测数据点数目作为参数,得到外推的结果
# 使用Matplotlib库绘制了两条曲线,一条代表原始数据x,另一条代表外推的结果extrapolation
plt.plot(np.arange(0, x.size), x, 'b', label = 'x', linewidth = 3)
plt.plot(np.arange(0, extrapolation.size), extrapolation, 'r', label = 'extrapolation')
plt.legend()# 添加图例以便区分曲线

# 通过Fourier外推方法对航空乘客数量的时间序列数据进行预测,并将原始数据和预测结果可视化
air_passengers = pd.read_csv('/home/mw/input/demo2813/AirPassengers.csv') # 读取了包含航空乘客数量的时间序列数据的CSV文件
x = np.array(air_passengers['#Passengers'].values) # 将CSV文件中的乘客数量数据提取出来并转换为Numpy数组,存储在变量x中
n_predict = 300 # 定义外推预测的数据点数目
extrapolation = fourierExtrapolation(x, n_predict) # 调用fourierExtrapolation函数,使用变量x和n_predict作为参数,得到外推的结果
plt.plot(np.arange(0, x.size), x, 'b', label = 'x', linewidth = 3) # 绘制原始数据x的曲线,颜色为蓝色
plt.plot(np.arange(0, extrapolation.size), extrapolation, 'r', label = 'extrapolation') # 绘制外推结果extrapolation的曲线,颜色为红色
plt.legend() # 添加图例,用于区分原始数据和外推结果的曲线

!pip install pandas-datareader -i https://pypi.tuna.tsinghua.edu.cn/simple

!pip install tqdm -i https://pypi.tuna.tsinghua.edu.cn/simple

二、聚类和分类

距离度量

在机器学习和数据挖掘中,分类和聚类是两种常见的任务。虽然它们的目标和方法有所不同,但两者都经常涉及到数据点之间的距离度量。距离度量标准的选择对于分类和聚类的效果至关重要,因为它决定了数据点之间的相似性或差异性的计算方式

应用

基于DTW的聚类
基于DTW的最近邻分类法

import matplotlib.pylab as plt
%matplotlib inline
from matplotlib.pylab import rcParams
rcParams['figure.figsize'] = 15, 6
from pandas_datareader.data import DataReader
from datetime import datetime
from scipy.cluster.hierarchy import dendrogram, linkage
from pandas_datareader.data import DataReader
from datetime import datetime
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances
from math import sqrt
from scipy.spatial.distance import squareform
from tqdm import tqdm


#读取文件
words = pd.read_csv('/home/mw/input/demo2813/50words_TEST.csv')


#从数据框 words 中提取除第一列之外的所有数据,将其转换为矩阵形式,存储在名为 test 的变量中
test = words.ix[:, 1:].as_matrix()

'''
/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:2: DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
  
/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:2: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.
'''


test.shape
# (454, 270)


a = lambda x, y: x[0] + y[0]


# 计算两个序列之间的动态时间规整(DTW)距离的函数
# DWT是用于衡量两个序列之间相似度的方法,它可以处理序列在时间轴上的扭曲和偏移
def DTWDistance(s1, s2):
    # 将输入序列转换为NumPy数组
    s1, s2 = np.array(s1), np.array(s2)
    n, m = len(s1), len(s2)
    
    # 初始化DTW矩阵
    DTW = np.full((n+1, m+1), float('inf'))
    DTW[0, 0] = 0
    
    # 计算DTW距离
    for i in range(1, n+1):
        for j in range(1, m+1):
            dist = (s1[i-1] - s2[j-1]) ** 2
            DTW[i, j] = dist + min(DTW[i-1, j], DTW[i, j-1], DTW[i-1, j-1])
    
    return np.sqrt(DTW[n, m])


# 使用动态时间规整(DTW)距离来计算测试数据集中每对样本之间的距离
# size = test.shape[0]
# distance_matrix = np.zeros((size, size))

# for i in tqdm(range(size), desc="计算DTW距离"):
#     for j in range(i, size):
#         distance_matrix[i, j] = DTWDistance(test[i], test[j])
#         distance_matrix[j, i] = distance_matrix[i, j]


# 返回distance_matrix的行列数
# distance_matrix.shape


# 使用 linkage 函数来对距离矩阵 p 进行层次聚类,聚类方法是 Ward 方法
# z = linkage(distance_matrix, 'ward')


# z


# np.savetxt('linkage_matrix.txt', z)

'''
--------------------------------------------------------------------------------------------------------------------------
注释到这
将下面读取已经在project目录里预存好的数据的代码取消注释
'''


from scipy.cluster.hierarchy import dendrogram
# 加载链接矩阵
z = np.loadtxt('linkage_matrix.txt')  #读取预存数据
dendrogram(z)
plt.title('层次聚类树状图')
plt.xlabel('样本索引')
plt.ylabel('聚类距离')
plt.show()

#显示前几行数据
words.head()
4-0.89094-0.86099-0.82438-0.78214-0.73573-0.68691-0.63754-0.58937-0.54342...-0.86309-0.86791-0.87271-0.87846-0.88592-0.89619-0.90783-0.91942-0.93018-0.93939
012-0.78346-0.68562-0.58409-0.47946-0.37398-0.27008-0.17225-0.087463-0.019191...-0.88318-0.89189-0.90290-0.91427-0.92668-0.93966-0.95244-0.96623-0.9805-0.99178
113-1.32560-1.28430-1.21970-1.15670-1.09980-1.04960-1.01550-0.996720-0.985040...-0.83499-0.86204-0.88559-0.90454-0.93353-0.99135-1.06910-1.13680-1.1980-1.27000
223-1.09370-1.04200-0.99840-0.95997-0.93997-0.93764-0.92649-0.857090-0.693320...-0.72810-0.74512-0.76376-0.78068-0.80593-0.84350-0.89531-0.96052-1.0509-1.12830
34-0.90138-0.85228-0.80196-0.74932-0.69298-0.63316-0.57038-0.506920-0.446040...-0.95452-0.97322-0.98984-1.00520-1.01880-1.02960-1.03700-1.04110-1.0418-1.04030
413-1.24470-1.22000-1.16940-1.09130-0.98968-0.86828-0.73462-0.595370-0.457100...-0.59899-0.69078-0.78410-0.87322-0.95100-1.01550-1.07050-1.12200-1.1728-1.21670
# 创建名为 type 的新列,并将数据框 words 中第一列的数据复制到这个新列中
words['type']  = words.ix[:, 1]

'''
/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:2: DeprecationWarning: 
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing

See the documentation here:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#ix-indexer-is-deprecated
'''


# 筛选出 words 数据框中 type 列的取值小于5的行,并将这些行存储在新的数据框 w 中
w = words[words['type'] < 5]


#数据框的行列数
w.shape
# (454, 272)


# 绘制数据框 w 中第一行从第二列开始的所有数据的图表
w.ix[0, 1:].plot()

# 绘制数据框 w 中第三行从第二列开始的所有数据的图表
w.ix[2, 1:].plot()


原文地址:https://blog.csdn.net/qq_52421831/article/details/142852883

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!