神经网络代码实现
大约 1 分钟AIAI
神经网络代码实现
1 Tensorflow 安装
没有显卡的机器
pip install tensorflow
对于有显卡的机器
pip install tensorflow-gpu
2 例子: 烤咖啡豆
输入特征:烘焙温度、烘焙时间,判断咖啡豆烤的是否合适,输出是烤好了或者没烤好。

构造如下的神经网络:

2.1 构造神经网络(伪代码)
给定输入特征 x 和 标签 y:
x = np.array([[200.0, 17.0],
[120.0, 5.0],
[425.0, 20.0],
[212.0, 18.0])
y = np.array([1,0,0,1])
使用Dense函数定义神经网络中的层。
定义隐藏层:
layer_1 = Dense(units=3, activation='sigmoid')
a1 = layer_1(x)
定义输出层:
layer_2 = Dense(units=1, activation='sigmoid')
a2 = layer_2(a1)
使用Sequential方法可以将神经网络的层串联起来:
model = Sequential([layer1, layer2])
编译神经网络:
model.compile(...)
训练数据集:
model.fit(x,y)
结果判断:
if a2 >= 0.5:
yhat = 1
else:
yhat = 0
3 Tensorflow 函数
3.1 compile
在 compile
函数中可以指定代价函数 loss
,如二元交叉熵损失函数:BinaryCrossentropy
(逻辑回归中的损失函数相同)、平方差损失函数:MeanSquareError
(回归问题)
model.compile(loss=BinaryCrossentropy())
3.2 fit
fit
函数中可以指定训练的输入数据、标签、训练次数epochs等参数。
model.fit(X, y, epochs=10)