如何通过简单的深度学习(线性回归)制作 x*y

How to make x*y with simple deep learning(linear regression)

为了我以后的使用,我想测试多变量多层感知器。

为了测试,我做了一个简单的python程序。

这是代码。

import tensorflow as tf
import pandas as pd
import numpy as np
import random

input = []
result = []

for i in range(0,10000):
    x = random.random()*100
    y = random.random()*100
    input.append([x,y])
    result.append(x*y)


input = np.array(input,dtype=float)
result = np.array(result,dtype = float)

activation_func = "relu"
unit_count = 256

model = tf.keras.models.Sequential([
tf.keras.layers.Dense(1,input_dim=2),
tf.keras.layers.Dense(unit_count,activation=activation_func),
tf.keras.layers.Dense(unit_count,activation=activation_func),
tf.keras.layers.Dense(unit_count,activation=activation_func),
tf.keras.layers.Dense(unit_count,activation=activation_func),
tf.keras.layers.Dense(1)])

model.compile(optimizer="adam",loss="mse")


model.fit(input,result,epochs=10)

predict_input = np.array([[7,3],[5,4],[8,8]]);

print(model.predict(predict_input))

我试过这段代码,结果并不好。损失值似乎在某些时候不会变低。

我也试过使用较小的 x 和 y。它使模型在更大的数字下不准确。

我更改了激活函数,制作了更密集的层并增加了单元数量,但并没有变得更好。

神经网络无法自我调整(无需额外训练)以适应不同的领域,这意味着您应该在一个领域进行训练,运行 在同一领域进行推理。

在图像中,我们通常只是将输入图像从 [0,255] 缩放到 [-1,1],然后让网络从这个范围内的值中学习(并且在推理过程中,我们总是将输入值重新缩放为[-1,1] 范围)。

为了解决您的任务,您应该将问题带到一个受限的域中。

在实践中,如果您只对正数相乘训练模型感兴趣,您可以将它们压缩在 [0,1] 范围内,因为这个范围内的值相乘总是给出输出值相同的范围。

我稍微修改了你的代码,并在源代码中添加了一些注释。

import random

import numpy as np
import pandas as pd
import tensorflow as tf

input = []
result = []

# We want to train our network to work in a fixed domain
# the [0,1] range.

# Let's also increase the training set -> more data is always better
for i in range(0, 100000):
    x = random.random()
    y = random.random()
    input.append([x, y])
    result.append(x * y)
    print(input, result)
    sys.exit()


input = np.array(input, dtype=float)
result = np.array(result, dtype=float)

activation_func = "relu"
unit_count = 256

# no need for a tons of layers
model = tf.keras.models.Sequential(
    [
        tf.keras.layers.Dense(unit_count, input_dim=2, activation=activation_func),
        tf.keras.layers.Dense(unit_count, activation=activation_func),
        tf.keras.layers.Dense(1, use_bias=False),
    ]
)

model.compile(optimizer="adam", loss="mse")
model.fit(input, result, epochs=10)

# Bring our input values in the [0,1] range
max_value = 10
predict_input = np.array([[7, 3], [5, 4], [8, 8]]) / max_value
print(predict_input)

# Back to the original domain
# Multiply by max_value**2 is required since the multiplication
# for a number in [0,1] it's the same of a division
print(model.predict(predict_input) * max_value ** 2)

示例输出:

[[0.7 0.3]
 [0.5 0.4]
 [0.8 0.8]]
[[21.04468 ]
 [20.028284]
 [64.05521 ]]