python 离散序列 样本数伸缩(原创)
解决问题:
有一个固定长度的1维矩阵,将这个矩阵的取样点进行扩充和减少
功能函数:
1 def discrete_scale(data, num): 2 import numpy as np 3 import copy 4 """ 5 :param data: 原始一维矩阵数据 6 :param num: 设定的样本长度 7 :return d1: 目标矩阵输出 8 """ 9 len = data.shape[0] # 原始数据长度 10 11 if len < num: # 样本扩展 12 t = (len - 1) / (num - 1) # 映射差值 13 d0 = np.array(range(num)) # 序列映射 14 d0 = d0 * t 15 16 d0_1 = copy.deepcopy(d0).astype(int) # 整数部分 17 d0_0 = d0 - d0_1 # 小数部分 18 dist = data[1:] - data[:-1] # 维度减小一个数据 19 d1_1 = data[d0_1] 20 d1_0 = dist[d0_1[:-1]] 21 d1_0 = d1_0 * d0_0[:-1] 22 d1 = copy.deepcopy(d1_1[:-1] + d1_0) 23 d1 = np.hstack((d1, data[-1])) 24 25 elif len > num: # 样本压缩 26 t = (len - 1) / num # 映射差值 分成7个给值区域 27 d0 = np.array(range(num + 1)) # 序列映射 28 d0 = d0 * t 29 30 d0_1 = copy.deepcopy(d0).astype(int) # 整数部分 31 list = [] 32 for i in range(d0_1.shape[0] - 1): 33 list.append(np.mean(data[d0_1[i]:d0_1[i + 1] + 1])) 34 d1 = np.array(list) 35 36 else: # 目标长度与原始长度相同 37 d1 = data 38 return d1
实例程序:
1 import numpy as np 2 a = np.array(range(0,1000)) 3 print(a) 4 b = np.sin(a/100) 5 print(b) 6 7 num = 100 8 x1 = np.array(range(num)) 9 y1 = discrete_scale(b, num) 10 11 import matplotlib.pylab as plt 12 plt.plot(x1, y1, 'r-') 13 plt.plot(a, b, 'b-') 14 plt.show() 15 print(b)
探究未知是最大乐趣