import tensorflow as tf
import numpy as np
from tensorflow import keras
model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
Dense定义一层相连的神经元,这里只有一个Dense,所以只有一层。units=1所以它是单个神经元。sequential表示是全连接层,而不是卷积层。
model.compile(optimizer='sgd', loss='mean_squared_error')
compile()函数用于编译正则表达式,返回一个正则表达式对象,compile(source, filename, mode),在这里,损失函数是均方误差mean squared error;优化器optimizer是SGD,代表随机梯度下降。
xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float)
已知数据,np.array是使用numpy的数组创建。比如:
a = np.array([2,3,4])
b = np.array([[1.0,2.0],[3.0,4.0]])
d = np.array([[1,2],[3,4]],dtype=complex) # 指定数据类型为复数
model.fit(xs, ys, epochs=500)
fit命令让其训练,epochs=500表示让其经历500次循环。
print(model.predict([10.0]))
模型完成训练之后,可用其预测。让X=10,预测Y的值。
缺点:本次训练只使用了6个点