Keras模型仅在尝试近似数学函数时生成一个平面

2024-03-28 09:59:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用一个隐层感知器(需要的是单层感知器)来近似函数f(x,y),方法是为x和y生成一个在[-1,1]之间的10000点网格,计算f(x,y)并向每个f(x,y)添加一些高斯分布的随机噪声来生成我的训练集、验证集和测试集。你知道吗

当我训练我的模型时,我得到了大约0.04的MSE。你知道吗

问题是,当我用我的模型来预测新的数据并将其绘制出来时,我得到了一个平面状的结构,它看起来完全不像函数。你知道吗

我已经试着调试了好几个小时,下面是我的发现:

使用网格预测所有f(x,y)(基本上是对训练、验证和测试集进行预测)得到平面结构

少时代的训练——多时代的训练似乎只会改变平面的坡度,而不会改变形状。你知道吗

这是我的密码:

num_points = 100
x = np.linspace(-1, 1, num_points)
y = np.linspace(-1, 1, num_points)
xx, yy = np.meshgrid(x, y)

def f(x,y):
    q = (np.sin(20 * ((x**2 + y**2) ** (1/2))))/(20 * ((x**2 + y**2) ** (1/2)))
    w = 1/5 * np.cos(10 * ((x**2 + y**2) ** (1/2)))
    e = y/2
    r = -.3
    return q + w + e + r
fxy = np.zeros((num_points, num_points))
for row in range(len(xx)):
    for col in range(len(xx[0])):
        fxy[row][col] = f(xx[row][col], yy[row][col])
noise = .1*np.random.normal(0, 1, fxy.shape)
fxyhat = fxy + noise

def split(xx, yy, fxy):
    num_samples = xx.size
    print(num_samples)
    num_train = int(num_samples*.7)
    num_val = int(num_samples*.15)

    all_data = []
    for row in range(len(xx)):
        for col in range(len(xx[0])):
            all_data.append((xx[row][col], yy[row][col], fxy[row][col]))

    random.shuffle(all_data)
    print(len(all_data))
    train = np.array(all_data[0:num_train])
    val = np.array(all_data[num_train:num_train + num_val])
    test = np.array(all_data[num_train+num_val:len(all_data)])

    return train, val, test

train, val, test = split(xx, yy, fxyhat)

train_x = np.array([[data[0],data[1]] for data in train])
train_y = np.array([data[2] for data in train])

val_x = np.array([[data[0],data[1]] for data in test])
val_y = np.array([data[2] for data in test])

test_x = np.array([[data[0],data[1]] for data in test])
test_y = np.array([data[2] for data in test])

all_x = np.concatenate((train_x, val_x, test_x),axis=0)
all_y = np.concatenate((train_y, val_y, test_y),axis=0)

model = Sequential()
# first layer
model.add(Dense(num_nodes, input_dim=2, activation='sigmoid',)) 
# output layer
model.add(Dense(1))

optimizer = optimizers.SGD(lr=init_learning_rate, momentum=momentum) 
model.compile(loss='mean_squared_error', optimizer=optimizer)

num_nodes = 26
epochs = 1
model.fit(train_x, train_y, epochs=epochs, batch_size=len(train_x))

带噪波的函数如下所示(训练数据): My function with noise looks like this (training data)

我的预测是这样的: and my predictions look like this

有没有人在试图生成密集网格的预测时,遇到模型只生成平面的错误?你知道吗


Tags: intestfordatalennptraincol
1条回答
网友
1楼 · 发布于 2024-03-28 09:59:55

这不是一架飞机。你用的阴谋是骗人的。散点图显示了更清晰的图像。你知道吗

enter image description here

注意边缘有点向上弯曲。你知道吗

在2000年时,边缘的曲率要明显得多,网络已经开始识别中心。你知道吗

enter image description here

在10万个时代之后,你会看到这样的画面:

enter image description here

这是训练和策划的代码。你知道吗

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def plot_preds(XY_test, z_pred):
  x = XY_test[:,0]
  y = XY_test[:,1]
  fig = plt.figure(figsize=(12, 6))
  ax = fig.gca(projection='3d')
  # Since we're centered at (0,0), these colors should emphasize the droplet
  d = np.sqrt(x**2 + y**2)
  scatter = ax.scatter(x, y, z_pred, c=d, cmap='coolwarm')
  ax.set_xlabel('x')
  ax.set_ylabel('y')
  ax.set_zlabel('z')


model = Sequential()
model.add(Dense(26, input_dim=2, activation='relu',)) 
model.add(Dense(1))
optimizer = optimizers.SGD(lr=0.1, momentum=0.9)
model.compile(loss='mean_squared_error', optimizer=optimizer)

history = model.fit(train_x, train_y, epochs=100000, batch_size=len(train_x), verbose=0)
z_pred = model.predict(test_x)
plot_preds(test_x, z_pred)

相关问题 更多 >