通过神经网络划分;每次产生固定值

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

我正在尝试开发一个神经网络,使用 this 方法来乘除两个数字。乘法部分进展顺利,但除法则不然 - 每次运行程序时,对于每对输入,都会获得一个小的近固定值(每次运行程序时固定)作为输出。在我问的上一个问题的答案的帮助下(我建议回去阅读所有内容,以避免混淆),我取得了一些进展,但仍然遇到了问题,并且我认为最好提出一个新问题。我的神经网络的代码是:

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

num_train = 1000

X_train = np.random.rand(num_train, 2)
y_train_add = X_train[:, 0] + X_train[:, 1]

model_add = Sequential(
        [
            Dense(10),
            Dense(1)
            ]
        )

batch_size = 32
epochs = 100

model_add.compile(loss = 'mse', optimizer='adam')
model_add.fit(X_train, y_train_add, batch_size=batch_size, epochs=epochs, verbose = 1)

a = np.random.random((2000000,1))*100-50
b = np.random.random((100000,1))*10
x_train = np.append(a, b)
#This is because previously there had been severe inaccuracies near 0, which led to problems during division, so I increased the training data near zero
y_train = np.square(x_train)

model_sqr = Sequential(
        [
            Dense(8, activation = 'elu', kernel_regularizer = regularizers.l2(0.001), input_shape = (1,)),
            Dense(8, activation = 'elu', kernel_regularizer = regularizers.l2(0.001)),
            Dense(1)
            ]

        )

batch_size = 32
epochs = 100

model_sqr.compile(loss = 'mse', optimizer='adam')
model_sqr.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose = 1)

x = "n" 
while True:
    print("enter first num:")
    x = input()
    if x == "end":
        break

    print("Enter operation:")
    op= input()

    print("enter second num:")
    y = input()

    X = int(x)
    Y = int(y)
    Ydiv = np.reciprocal(Y)

    if op == "*":
        predicted_product = model_sqr.predict(model_add.predict(np.array([[X, Y]]))) - model_sqr.predict(np.array([X])) -  model_sqr.predict(np.array([Y]))
        print(predicted_product/2)
    elif op =="/":
        predicted_quot = model_sqr.predict(model_add.predict(np.array([[X, Ydiv]]))) - model_sqr.predict(np.array([X])) -  model_sqr.predict(np.array([Ydiv]))
        print(predicted_quot/2)

例如,在保存权重并运行程序时,对于使用的每对数字,每次运行都会获得大约 -0.123。

为了理解为什么会发生这种情况,我运行了 25/5,例如,将程序修改为显示 (25+(1/5))^2、25^2 和 (1/5)^ 2也。我得到的值是 623.7364、623.73645 和 0.24594116。

为了理解为什么获得这些值以及如何修复它们,我将平方函数(橙色)和我的平方神经网络模型(蓝色)绘制在一起:

enter image description here

放大接近25;

enter image description here

放大接近0;

enter image description here

问题是,我看到的从图中预测的中间值不是我打印出来的。例如,使用光标,我可以看到 25^2 预计约为 624,(25+(1/5))^2 预计约为 634,(1/5)^2 预计约为 634为 0.42。使用这些值,您会得到一个可接受的答案,但我打印出来的值是不同的。

(1): 为什么这些值不同?

(2):我怎样才能使模型做出绘图似乎做出的可接受的预测?

python numpy tensorflow keras neural-network
1个回答
0
投票

我认为问题在于,当你计算整数值 Y 的倒数时,它返回 0,因此你总是计算 X 与零的乘积。

Y = int(y)
Ydiv = np.reciprocal(Y) # Ydiv is zero because the reciprocal of a positive integer is zero

我认为这是你的程序总是返回相同结果的主要原因。

© www.soinside.com 2019 - 2024. All rights reserved.