【问题标题】:How to produce an array with values in a specific shape?如何生成具有特定形状值的数组?
【发布时间】:2020-02-14 06:55:11
【问题描述】:

我想创建一个值范围为 0.0 到 1.0 的数组,如下所示: weighting matrix

基本上,左侧和顶部边缘应保持接近 1.0,但在角落处缓慢衰减到 0.5。 底部和右侧边缘应保持接近 0.0 中间区域应该大部分是 0.5,并且值应该从 1.0 到 0.0 对角线衰减。

这是我尝试过的,但它并不能完全满足我的需求。

import numpy as np
import matplotlib.pyplot as plt

def sigmoid(x):
  y = np.zeros(len(x))
  for i in range(len(x)):
    y[i] = 1 / (1 + math.exp(-x[i]))
  return y

sigmoid_ = sigmoid(np.linspace(20, 2.5, 30))
temp1 = np.repeat(sigmoid_.reshape((1,len(sigmoid_))), repeats=10, axis=0)
sigmoid_ = sigmoid(np.linspace(6, 3, 10))
temp2 = np.repeat(sigmoid_.reshape((len(sigmoid_),1)), repeats=30, axis=1)
alpha1 = temp1 + temp2

sigmoid_ = sigmoid(np.linspace(-2.5, -20, 30))
temp1 = np.repeat(sigmoid_.reshape((1,len(sigmoid_))), repeats=10, axis=0)
sigmoid_ = sigmoid(np.linspace(-3, -6, 10))
temp2 = np.repeat(sigmoid_.reshape((len(sigmoid_),1)), repeats=30, axis=1)
alpha2 = temp1 + temp2

alpha = alpha1 + alpha2
alpha = alpha - np.min(alpha)
alpha = alpha / np.max(alpha)

plt.matshow(alpha)

这给了我这个:results

有人可以帮我吗?

【问题讨论】:

  • 有你想要的数学表示吗?因为有很多方法可以获得模糊的 2D sigmoidal。
  • @user633611 快速和慢速的区别?

标签: python numpy matrix


【解决方案1】:

这是我能想到的最简单的函数:

tune_me = 101    
x = np.linspace(0, 1, tune_me)
y = np.linspace(0, 1, tune_me)
xv, yv = np.meshgrid(x, y)
sig = 1/(1 + np.exp(tune_me - xv - yv))

plt.matshow(sig)

但如果你想要一些具体的东西,你可能应该在尝试实现它之前弄清楚你的数学(可能在数学堆栈交换中)。

【讨论】:

    【解决方案2】:

    如果没有其他要求,我将对加权矩阵区域的所有部分使用相同的函数。在适当的平移和缩放之后,S 型函数(在中心附近快速变化,远离中心缓慢变化)确实是合适的。对于 sigmoid 函数的参数,我会从该区域的一角选择 taxicab distance

    import math
    import numpy as np
    import matplotlib.pyplot as plt
    
    alpha = np.ndarray((10, 30))
    ymax, xmax = alpha.shape[0]-1, alpha.shape[1]-1
    for y in range(alpha.shape[0]):
        for x in range(alpha.shape[1]):
            M = x/xmax+y/ymax   # Manhattan distance, range [0;2]
            M -= 1              # make range [-1;1], so that inflection point is in the middle
            M *= 3.0            # the higher this factor, the steeper the sigmoid curve at the flex
            s = 1 / (1 + math.exp(-M))  # sigmoid function, range ]0;1[
            alpha[y, x] = 1-s   # decay from 1 to 0
    
    plt.matshow(alpha)
    plt.show()
    # show the values close to 0.5
    h = [(y, x) for y in range(alpha.shape[0])
                for x in range(alpha.shape[1]) if .4 < alpha[y, x] and alpha[y, x] < .6]
    hy, hx = zip(*h)
    plt.plot(hx, hy, 'o')
    plt.gca().invert_yaxis()
    plt.show()
    

    说明中心区域接近 0.5 的值,例如。 G。在 ]0.4;0.6[:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      • 2019-12-06
      • 2018-10-06
      • 1970-01-01
      相关资源
      最近更新 更多