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

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

How to add noise to the first index in nump array

问题

  1. a = np.array([[858,833,123],
  2. [323,542,927],
  3. [938,361,271],
  4. [679,272,451]])
  5. 噪声 = np.random.normal(loc=0, scale=0.1, size=1)
  6. max_iter = 2
  7. for i in range(max_iter):
  8. for j in range(len(a)):
  9. a[i][0] = np.clip(a[i][0] + 噪声, a_min=0.0, a_max=None)
  10. 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

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

答案1

得分: 1

  1. # 需要将数组转换为浮点数而不是整数,以便添加其他浮点数
  2. a = np.array([[858,833,123],
  3. [323,542,927],
  4. [938,361,271],
  5. [679,272,451]]).astype(float)
  6. n = 2
  7. # 创建 n 个随机值
  8. noise = np.random.normal(loc=0, scale=0.1, size=n)
  9. # 循环遍历每 n 行
  10. for i in range(0, a.shape[0], n):
  11. a[i:i + n, 0] = np.clip(a[i:i + 1, 0] + noise, a_min=0.0, a_max=None)
英文:

You can do:

  1. # you'll need to cast the array as floats rather ints to add other floats
  2. a = np.array([[858,833,123],
  3. [323,542,927],
  4. [938,361,271],
  5. [679,272,451]]).astype(float)
  6. n = 2
  7. # create n random values
  8. noise = np.random.normal(loc=0, scale=0.1, size=n)
  9. # loop through rows in steps of n
  10. for i in range(0, a.shape[0], n):
  11. 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:

  1. a = np.array([[858,833,123],
  2. [323,542,927],
  3. [938,361,271],
  4. [679,272,451]])
  5. a[:, 0] += np.random.normal(loc=0, scale=0.1, size=len(a))
  6. 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:

确定