import tensorflow
import numpy as np
准备训练数据
x_train = np.array([1,2,3,4,5],dtype = np.float32)
y_train = np.array([2,4,6,8,10],dtype = np.float32)
定义模型
model = tf.keras.Sequential([tf.keras.layers.Dense(units=1,input_shape=[1])])
编译模型
训练模型
model.fit(x_train,y_train,epochs=100)
使用模型进行预测
x_test= np.array([6,7,8],dtype=np.float32)
predictions = model.predict(x_test)
打印结果
for i, x in enumerate(x_test):
# 打印输入和预测结果
# 假设预测结果是一个二维数组,predictions[i] 中的每个元素是一个预测向量
# 这里我们假设预测结果是概率分布,我们取概率最高的类别作为预测类别
predicted_class = predictions[i].argmax() # 获取概率最高的索引作为预测类别
print(f'输入: {x}, 预测结果: {predicted_class}')