如何向nump数组的第一个索引添加噪音。

huangapple go评论134阅读模式
英文:

How to add noise to the first index in nump array

问题

a = np.array([[858,833,123],
             [323,542,927],
             [938,361,271],
             [679,272,451]])
噪声 = np.random.normal(loc=0, scale=0.1, size=1)
max_iter = 2
for i in range(max_iter):
    for j in range(len(a)):
        a[i][0] = np.clip(a[i][0] + 噪声, a_min=0.0, a_max=None)
print(a)
英文:

How to add noise to the first index of array,with the number of iterations the max number iteration is 2.

I want to add a noise in range (1, max_iterator) to rows in order, for example:

  • add 0.788 to row 1st
  • add 1.233 to row 2nd
  • add 0.788 to row 3rd
  • add 1.233 to row 4th
  • and 0.788 to row 5th
  • and so on

I've tried to use this code but it doesn't work

a = np.array([[858,833,123],
             [323,542,927],
             [938,361,271],
             [679,272,451]])
noise = np.random.normal(loc=0, scale=0.1, size=1)
max_iter = 2
for i in range(max_iter):
    for j in range(len(a)):
        a[i][0] = np.clip(a[i][0] + noise, a_min=0.0, a_max=None)
print(a)

答案1

得分: 1

# 需要将数组转换为浮点数而不是整数,以便添加其他浮点数
a = np.array([[858,833,123],
             [323,542,927],
             [938,361,271],
             [679,272,451]]).astype(float)

n = 2

# 创建 n 个随机值
noise = np.random.normal(loc=0, scale=0.1, size=n)

# 循环遍历每 n 行
for i in range(0, a.shape[0], n):
    a[i:i + n, 0] = np.clip(a[i:i + 1, 0] + noise, a_min=0.0, a_max=None)
英文:

You can do:

# you'll need to cast the array as floats rather ints to add other floats
a = np.array([[858,833,123],
             [323,542,927],
             [938,361,271],
             [679,272,451]]).astype(float)

n = 2

# create n random values
noise = np.random.normal(loc=0, scale=0.1, size=n)

# loop through rows in steps of n
for i in range(0, a.shape[0], n):
    a[i:i + n, 0] = np.clip(a[i:i + 1, 0] + noise, a_min=0.0, a_max=None)

答案2

得分: 0

我无法确定您的代码或问题是否符合您的要求:

这段代码会向第一列添加噪音。

英文:

I can't tell from your code or question if this is what you want or not:

a = np.array([[858,833,123],
             [323,542,927],
             [938,361,271],
             [679,272,451]])
a[:, 0] += np.random.normal(loc=0, scale=0.1, size=len(a))
a[:, 0] = np.clip(a[:, 0], a_min=0.0, a_max=None)

This adds noise to the first column

huangapple
  • 本文由 发表于 2023年3月8日 18:16:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671751.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定