我计算一些风速序列的相互信息。当我尝试使用cupy加速我的代码时,实际上它要慢一些
我计算numpy和cupy的相互信息,我的数据是1097 * 5000,numpy版本比cupy版本快得多。这是我第一次使用stackoverflow,仍然不知道排版问题
numpy版本 “” MutualInformation_n()类: def init (自身,数据,分数,log_base): self.data =数据 自分数=分数 self.log_base = log_base [self.ncount,self.length] = self.data.shape self.p = {}
def discretize(self):
dis_data = np.floor(self.data)
return dis_data
def mi(self):
dis_data = self.discretize()
MI = np.zeros(shape=[self.ncount, self.ncount])
values = {}
for x_index in range(self.ncount):
self.p[x_index] = {}
values_x = set(dis_data[x_index])
values[x_index] = values_x
for value_x in values_x:
px = shape(where(dis_data[x_index]==value_x))[1] / self.length
self.p[x_index][value_x] = px
for x_index in range(self.ncount):
values_x = values[x_index]
for y_index in range(x_index+1, self.ncount):
summation = 0.0
# Get uniques values of random variables
values_y = values[y_index]
# Print debug info
# For each random
for value_x in values_x:
for value_y in values_y:
px = self.p[x_index][value_x]
py = self.p[y_index][value_y]
pxy = len(where(in1d(where(dis_data[x_index]==value_x)[0],
where(dis_data[y_index]==value_y)[0])==True)[0]) / self.length
if pxy>0:
summation += pxy * math.log((pxy / (px*py)), self.log_base)
MI[x_index, y_index] = summation
MI[y_index, x_index] = summation
return MI
“”“ 丘比特版 “” def in1d_c(ar1,ar2): mask = cp.zeros(len(ar1),dtype = bool) 对于ar2: 掩码| =(ar1 == a) 返回面具
MutualInformation_c()类: def init (自身,数据,log_base): self.data =数据 self.log_base = log_base [self.ncount,self.length] = self.data.shape self.p = {}
def discretize(self):
dis_data = cp.floor(self.data)
return dis_data
def mi(self):
dis_data = self.discretize()
MI = cp.zeros(shape=[self.ncount, self.ncount])
values = {}
for x_index in range(self.ncount):
self.p[x_index] = {}
values_x = cp.unique(dis_data[x_index])
values[x_index] = values_x
for value_x in values_x:
px = len(cp.where(dis_data[x_index]==value_x)[0]) / self.length
self.p[x_index][int(value_x)] = px
for x_index in range(self.ncount):
values_x = values[x_index]
for y_index in range(x_index+1, self.ncount):
summation = 0.0
# Get uniques values of random variables
values_y = values[y_index]
# Print debug info
# For each random
for value_x in values_x:
for value_y in values_y:
px = self.p[x_index][int(value_x)]
py = self.p[y_index][int(value_y)]
pxy = len(cp.where(in1d_c(cp.where(dis_data[x_index]==value_x)[0],
cp.where(dis_data[y_index]==value_y)[0])==True)[0]) / self.length
if pxy>0:
summation += pxy * math.log((pxy / (px*py)), self.log_base)
MI[x_index, y_index] = summation
MI[y_index, x_index] = summation
return MI
“”“