我的任务是生成一个数据集,该数据集的形状为三个交错的半圆。我使用“sklearn”库中提供的 make_moons() 函数生成了 2 个半圆,但无法弄清楚如何制作三个这样的半圆。
代码:
X, y=make_moons(n_samples=(300,300),noise=0.1)
df=pd.DataFrame(dict(x=X[:,0], y=X[:,1],label=y ))
colors={0:'red', 1:'blue',2:'green'}
fig,ax=plt.subplots()
grouped=df.groupby('label')
for key, group in grouped:
group.plot(ax=ax,kind='scatter',x='x',y='y',label=key,color=colors[key
plt.show()
我尝试增加样本大小的维度,但它给出了一个错误:“n_samples 可以是 int 或二元素元组。”
最佳答案
这是一个函数,可以创建具有任意数量卫星的数据集。
您可以使用y_shift
参数指定垂直移位。
def make_many_moons(
number_of_moons,
sigma,
radius,
number_of_datapoints,
y_shift = 0.3
):
moons = []
for y in range(number_of_moons):
q = np.random.uniform(0,np.pi,size=number_of_datapoints)
if y % 2 == 0:
factor = 1
else:
factor = -1
moon = np.zeros((number_of_datapoints, 3))
moon[:,0] = (radius * np.cos(q)) + y
moon[:,1] = (radius * np.sin(q) * factor) + (factor == -1) * y_shift
moon[:,2] = y
moons.append(moon)
noise = np.random.normal(0, sigma, size=moon[:,:2].shape)
moon[:,:2] += noise
moons = np.concatenate(moons)
return moons[:,:2], moons[:,2]
X, y = make_many_moons(
number_of_moons=5,
sigma=0.1,
radius=1,
number_of_datapoints=100,
y_shift = 0.3)
plt.scatter(X[:,0], X[:,1], c=y)
关于python - 在Python中生成分布在三个交错半圆形形状的数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71733603/