对数核和指数激活的非线性关系模型精度无法达到100%

问题描述 投票:0回答:1

我正在开展一个项目,需要使用神经网络对非线性关系进行建模。关系为 ( y = 3x_1^2x_2^3 )。网络设置如下:

  • 预处理:输入的自然对数
  • 网络设计:单层一个神经元
  • 激活函数:指数
  • 损失函数: MAE(平均绝对误差)
  • 优化器: Adam
  • 纪元: 50
  • 批量大小: 32

输入和预期输出:

  • 输入:([x1, x2])
  • 正确权重:([2, 3])
  • 正确偏差:(\ln 3)

尽管进行了这些设置,我仍无法达到 100% 的准确度。我尝试过随机初始化权重和偏差以及使用特定值。

这是代码:

import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam

# Generate data
x1 = np.random.randint(1, 21, size=(1000, 1))
x2 = np.random.randint(1, 21, size=(1000, 1))
y = 3 * (x1 ** 2) * (x2 ** 3)

# Preprocess data
log_x1 = np.log(x1)
log_x2 = np.log(x2)
log_inputs = np.hstack((log_x1, log_x2))

# Define model
model = Sequential()
model.add(Dense(1, input_dim=2, activation='exponential', kernel_initializer='ones', bias_initializer='zeros'))

# Compile model
model.compile(optimizer=Adam(learning_rate=0.01), loss='mae')

# Train model
model.fit(log_inputs, np.log(y), epochs=50, batch_size=32)

# Evaluate model
test_x1 = np.array([[2], [4], [5]])
test_x2 = np.array([[3], [7], [19]])
test_inputs = np.hstack((np.log(test_x1), np.log(test_x2)))
predicted = model.predict(test_inputs)
print(np.exp(predicted))

有人对如何提高该模型的准确性有建议吗?

tensorflow machine-learning keras deep-learning neural-network
1个回答
0
投票

你似乎把一些事情搞混了。该模型末尾包含指数,因此目标应该是

y
,而不是
log(y)
,或者您需要删除模型中的指数。另外,如果模型中有指数,则在
np.exp
之后使用 predict
again
是不正确的。这个版本运行良好:

import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam

# Generate data
x1 = np.random.randint(1, 21, size=(1000, 1))
x2 = np.random.randint(1, 21, size=(1000, 1))
y = 3 * (x1 ** 2) * (x2 ** 3)

# Preprocess data
log_x1 = np.log(x1)
log_x2 = np.log(x2)
log_inputs = np.hstack((log_x1, log_x2))

# Define model
model = Sequential()
model.add(Dense(1, input_dim=2, kernel_initializer='ones', bias_initializer='zeros'))

# Compile model
model.compile(optimizer=Adam(learning_rate=0.01), loss='mae')

# Train model
model.fit(log_inputs, np.log(y), epochs=100, batch_size=32)

# Evaluate model
test_x1 = np.array([[2], [4], [5]])
test_x2 = np.array([[3], [7], [19]])
test_inputs = np.hstack((np.log(test_x1), np.log(test_x2)))
predicted = model.predict(test_inputs)
print(np.exp(predicted))
© www.soinside.com 2019 - 2024. All rights reserved.