在本例中,您输入两个值并得到一个。
import numpy as np
import keras
from keras import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
MIN = np.random.rand(100)*500
MAX = np.random.rand(100)*500 + 500
x = np.concatenate((MIN.reshape(-1,1),MAX.reshape(-1,1)),axis = 1)
y = np.sin(x[:,0])*500 + np.cos(x[:,1])*500
x_max = x.max()
y_max = y.max()
x = x/x_max
y = (y-y.min())/(y_max-y.min())
model = Sequential()
model.add(Dense(200,input_dim = 2, activation = 'relu'))
model.add(Dense(100, activation = 'sigmoid'))
model.add(Dense(100, activation = 'sigmoid'))
model.add(Dense(1,activation = 'relu'))
opt = keras.optimizers.Adam(learning_rate=0.001, beta_1=0.6, beta_2=0.97, amsgrad=False)
model.compile(loss='mean_squared_error',optimizer=opt , metrics=['mse'])
model.fit(x, y, epochs=10000, batch_size=2)
y_hat = model.predict(x)
plt.figure(figsize=(10,5))
plt.plot(y)
plt.plot(y_hat.reshape(-1))
这是结果:
您需要对神经网络进行预处理和后处理、标准化输入和重新缩放输出。这是输入:
使用示例:
In [10]: model.predict(np.array([0.234,0.567]).reshape(-1,2))
Out[10]: array([[0.61975896]], dtype=float32)