python
复制代码
import tensorflow as tf
import numpy as np
from tensorflow.keras import Model
from tensorflow.keras import models
data = np.array([[-0.5, 7.7],
[1.8, 98.5],
[0.9, 57.8],
[0.4, 39.2],
[-1.4, -15.7],
[-1.4, -37.3],
[-1.8, -49.1],
[1.5, 75.6],
[0.4, 34.0],
[0.8, 62.3]])
x_data = data[:, 0]
y_data = data[:, 1]
x_train = tf.constant(x_data, dtype=tf.float32)
y_train = tf.constant(y_data, dtype=tf.float32)
dataset = tf.data.Dataset.from_tensor_slices((x_train, y_train))
dataset = dataset.shuffle(buffer_size=10)
dataset = dataset.batch(2)
dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
def linear():
input = tf.keras.layers.Input(shape=(1,), dtype=tf.float32)
y = tf.keras.layers.Dense(1)(input)
model1 = tf.keras.models.Model(inputs=input, outputs=y)
return model1
model = linear()
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
model.compile(optimizer=optimizer, loss='mean_squared_error')
epoch = 500
history = model.fit(dataset, epochs=epoch)
model.save("./model.linear.h5")
loader_model=models.load_model("model.linear.h5")
input_data=np.array([1.8])
pre=loader_model.predict(input_data)
print(f"model result :{pre[0][0]:2.3f}")