我试图用类似于“https://stats.stackschange.com/a/324008/300170”的描述方法来编码神经网络,以乘和除两个数字。首先,我用编码模型来加和减两个数字,然后用一个数字来配置一个数字。然后,我用除法的对等法将其乘以除法如下:
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
#Models for adding and subtracting two numbers
num_train = 1000
X_train = np.random.rand(num_train, 2)
y_train_add = X_train[:, 0] + X_train[:, 1]
y_train_subtract = X_train[:, 0] - X_train[:, 1]
model_add = Sequential(
[
Dense(10),
Dense(1)
]
)
model_subtract = 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)
model_subtract.compile(loss = mse , optimizer= adam )
model_subtract.fit(X_train, y_train_subtract, batch_size=batch_size, epochs=epochs, verbose = 1)
#Model for squaring a number
x_train = np.random.random((10000,1))*100-50
y_train = np.square(x_train)
model_sqr = Sequential(
[
Dense(8, activation = relu , kernel_regularizer = regularizers.l2(0.001), input_shape = (1,)),
Dense(8, activation = relu , kernel_regularizer = regularizers.l2(0.001)),
Dense(1)
]
)
batch_size = 64
epochs = 2000
model_sqr.compile(loss = mse , optimizer= adam )
model_sqr.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose = 1)
#Code for calculating the product and quotient of two numbers using models
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 = 1/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)
乘法部分工作合理,但输入两个数字以进行除法时,出现下列错误:
Exception encountered when calling Sequential.call().
Cannot take the length of shape with unknown rank.
有人能帮我修好吗?
Ydiv=1/Y
更改为 Ydiv=np.r对等(Y)
,虽然现在没有错误出现,但是我从事的每一个分工都产生大约特定数目的结果(每次我运行程序时不同的数值)。
所以我现在想知道
< 加固> 1 : 加固> 如何修补它, 以及
<% 1 > 2: % 1> 错误是如何出现的 。