请写出Python深度学习基于tensorflow
时间: 2023-06-01 07:04:13 浏览: 102
的代码范例
以下是一个使用tensorflow库实现简单神经网络的代码示例:
```
import tensorflow as tf
# 定义输入和输出数据
x_train = [[0, 0], [0, 1], [1, 0], [1, 1]]
y_train = [[0], [1], [1], [0]]
# 定义神经网络结构
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(units=2, activation=tf.nn.sigmoid, input_shape=(2,)),
tf.keras.layers.Dense(units=1, activation=tf.nn.sigmoid)
])
# 编译模型
model.compile(optimizer=tf.keras.optimizers.SGD(learning_rate=0.5),
loss=tf.keras.losses.MeanSquaredError(),
metrics=['accuracy'])
# 训练模型
model.fit(x_train, y_train, epochs=10000)
# 测试模型
x_test = [[0, 0], [0, 1], [1, 0], [1, 1]]
y_test = [[0], [1], [1], [0]]
test_loss, test_acc = model.evaluate(x_test, y_test)
print('Test accuracy:', test_acc)
```
该代码实现了一个包含一个输入层、一个隐藏层和一个输出层的神经网络。输入为2维向量,输出为1维向量。使用SGD优化器和均方误差损失函数进行训练,并在测试集上进行测试。最终输出测试集的准确率。
阅读全文
相关推荐















