TensorFlow Specialization Course 1学习笔记 Week 1

TensorFlow Specialization Course 1学习笔记

Week 1

如何让神经网络学习y = 2 * x - 1

导入tensorflow和keras。

numpy帮助我们将数据以列表的形式使用。keras将神经网络定义为一组连续的层。

import tensorflow as tf
import numpy as np
from tensorflow import keras

下面我们创建一个只有一层,一个单元的神经网络。

model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])

计算机如何学习规律的呢?它先做一个猜测,比如y=10x+10. Loss方程将衡量这个猜测和正确答案相差多少。

它使用OPTIMIZER再猜一次,这一次基于loss方程,试着最小化这个loss。这一次,它猜y=5x+5,虽然仍然不对,但比上一次猜测更加靠近正确答案(loss更小了)。重复这样的过程。在这里loss方程为mean squared error,optimizer为stochastic gradient descent。

model.compile(optimizer='sgd', loss='mean_squared_error')

下面使用numpy创建一组数据。

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)

训练我们的神经网络。

model.fit(xs, ys, epochs=500)

使用训练好的模型对新数据进行预测。

print(model.predict([10.0]))

这里的结果你猜会是19,但你会发现预测的结果并不等于19。而是非常接近19的数字。这是因为神经网络是根据概率来判断的。

Remember that neural networks deal with probabilities, so given the data that we fed the NN with, it calculated that there is a very high probability that the relationship between X and Y is Y=2X-1, but with only 6 data points we can’t know for sure. As a result, the result for 10 is very close to 19, but not necessarily 19.

数据越多,结果会越靠近正确答案。

课程地址:https://www.coursera.org/learn/introduction-tensorflow/

猜你喜欢

转载自blog.csdn.net/JSerenity/article/details/89319594
今日推荐