一、预测两组数据之间的关系
[-40,-10,0,8,15,22,38]
[-40,14,32,46,59,72,100]
二、代码:
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR) #仅仅输出错误语句
import numpy as np
celsius_q = np.array([-40,-10,0,8,15,22,38], dtype = float)#输入摄氏度值
fahrenheit_a = np.array([-40,14,32,46,59,72,100], dtype = float)#输入华氏度值
for i, c in enumerate(celsius_q):
print("{} degress Celsius = {} degrees Fahrenhet".format(c, fahrenheit_a[i]))
``
结果:
-40.0 degress Celsius = -40.0 degrees Fahrenhet
-10.0 degress Celsius = 14.0 degrees Fahrenhet
0.0 degress Celsius = 32.0 degrees Fahrenhet
8.0 degress Celsius = 46.0 degrees Fahrenhet
15.0 degress Celsius = 59.0 degrees Fahrenhet
22.0 degress Celsius = 72.0 degrees Fahrenhet
38.0 degress Celsius = 100.0 degrees Fahrenhet
创建模型:
l0 = tf.keras.layers.Dense(units = 1, input_shape=[1])
model = tf.keras.Sequential([l0])
model.compile(loss = 'mean_squared_error',optimizer = tf.keras.optimizers.Adam(0.1))
history = model.fit(celsius_q, fahrenheit_a, epochs = 500, verbose = False)
print("Finshed training the model")
结果:Finshed training the model
import matplotlib.pyplot as plt
plt.xlabel("Epoch Number")
plt.ylabel("Loss Magnitude")
plt.plot(history.history["loss"])
plt.show()
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190314152345260.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3hpYW5namlhb3Bpbnhpbmc=,size_16,color_FFFFFF,t_70)
print(model.predict([100.0]))
结果:[[211.33841]]
输出权值:
print(l0.get_weights())
[array([[1.8202447]], dtype=float32), array([29.313948], dtype=float32)]
近似等于:f = c * 1.8 + 32
三、总结:
创建一个全连接神经网络
hidden = keras.layers.Dense(units = 2, input_shape=[3])
output = keras.layers.Dense(units = 1)
model = tf.keras.layers.Sequential([hidden, output])
inputs: 该层的输入
units: 输出的大小(维数)
output:输出层
hidden:隐藏层