简体   繁体   中英

Can i optimize my random numbers generator using numpy?

this code np.random.rand(1000, 2) basically gives one big cluster of numbers

在此处输入图像描述

But is there a way to get those random numbers generated between 4 intervals so that i can achieve something like these 4 clusters of numbers instead?

在此处输入图像描述

Please note that the output format (list of lists) is important for me

Example of output:

np.random.rand(4, 2)

 [[0.20481852 0.39206741]
  [0.76406832 0.81779067]
  [0.94912136 0.9966882 ]
  [0.07224877 0.95471273]]

You can use sklearn's make_blobs , which randomly generates isotropic Gaussian blobs. For more control over then centers and covariances you could then look into multivariate_normal :

from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=4, centers=4, n_features=2,
                   cluster_std=0.3, random_state=0)

print(X)
array([[2.19931109, 2.35193717],
       [1.95204867, 1.30826216],
       [1.9263585 , 4.15243012],
       [2.84382807, 3.32650945]])

For instance, for a larger amount of random samples:

plt.figure(figsize=(7,7))
X, y = make_blobs(n_samples=400, centers=4, n_features=2,
                   cluster_std=0.3, random_state=0)
plt.scatter(X[:, 0], X[:, 1])
plt.show()

在此处输入图像描述

The example figure is the sum of two 2D random variables, which we can call corners and 2D uniform clusters . You can construct them using numpy primitives like this.

import numpy as np

# corner locations of 2-D uniform clusters
corners = np.random.rand(4, 2)

# scale of square 2-D uniform variates
scale = 0.3
square_rand = scale * np.random.rand(500, 2)

# select random corners for each item and add 
corner_ix = np.random.choice(4, 500)
four_clust = corners[corner_ix] + square_rand

Note the scale factor to reduce the unit-square uniform to 0.3 (measured by eyeball from your scatter plot).

四个集群

Version 2, which fits the image closer to your QPSK-looking scatter plot:

import numpy as np
import matplotlib.pyplot as plt

# scale of square 2-D uniform variates
scale = 0.3

# corner locations of 2-D uniform clusters
centers = np.array([[0.2, 0.2], [0.2, 0.8], [0.8, 0.2], [0.8, 0.8]])
corners = centers - scale/2

square_rand = scale * np.random.rand(500, 2)

# select random corners for each item and add 
corner_ix = np.random.choice(4, 500)
four_clust = corners[corner_ix] + square_rand

plt.plot(four_clust[:,0], four_clust[:,1], 'x')
plt.show()

固定角,统一变量

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM