如何在Python中使用TensorFlow定义损失函数、优化器、训练模型并在IMDB数据集上评估模型?
Tensorflow是谷歌提供的机器学习框架。它是一个开源框架,与Python结合使用,可以实现算法、深度学习应用等等。它用于研究和生产目的。
可以使用以下代码行在Windows上安装“tensorflow”包:
pip install tensorflow
“IMDB”数据集包含超过5万部电影的评论。此数据集通常与自然语言处理相关的操作一起使用。
我们使用Google Colaboratory运行以下代码。Google Colab或Colaboratory帮助在浏览器上运行Python代码,无需任何配置,并可免费访问GPU(图形处理单元)。Colaboratory构建在Jupyter Notebook之上。
以下是定义损失函数、优化器、训练模型并在IMDB数据集上评估模型的代码片段:
model.compile(loss=losses.BinaryCrossentropy(from_logits=True), optimizer='adam', metrics=tf.metrics.BinaryAccuracy(threshold=0.0)) epochs = 10 history = model.fit( train_ds, validation_data=val_ds, epochs=epochs) loss, accuracy = model.evaluate(test_ds) print("Loss is : ", loss) print("Accuracy is : ", accuracy)
代码来源 − https://tensorflowcn.cn/tutorials/keras/text_classification
输出
Epoch 1/10 625/625 [==============================] - 12s 19ms/step - loss: 0.6818 - binary_accuracy: 0.6130 - val_loss: 0.6135 - val_binary_accuracy: 0.7750 Epoch 2/10 625/625 [==============================] - 4s 7ms/step - loss: 0.5785 - binary_accuracy: 0.7853 - val_loss: 0.4971 - val_binary_accuracy: 0.8230 Epoch 3/10 625/625 [==============================] - 4s 7ms/step - loss: 0.4651 - binary_accuracy: 0.8372 - val_loss: 0.4193 - val_binary_accuracy: 0.8470 Epoch 4/10 625/625 [==============================] - 4s 7ms/step - loss: 0.3901 - binary_accuracy: 0.8635 - val_loss: 0.3732 - val_binary_accuracy: 0.8612 Epoch 5/10 625/625 [==============================] - 4s 7ms/step - loss: 0.3435 - binary_accuracy: 0.8771 - val_loss: 0.3444 - val_binary_accuracy: 0.8688 Epoch 6/10 625/625 [==============================] - 4s 7ms/step - loss: 0.3106 - binary_accuracy: 0.8877 - val_loss: 0.3255 - val_binary_accuracy: 0.8730 Epoch 7/10 625/625 [==============================] - 5s 7ms/step - loss: 0.2855 - binary_accuracy: 0.8970 - val_loss: 0.3119 - val_binary_accuracy: 0.8732 Epoch 8/10 625/625 [==============================] - 5s 7ms/step - loss: 0.2652 - binary_accuracy: 0.9048 - val_loss: 0.3027 - val_binary_accuracy: 0.8772 Epoch 9/10 625/625 [==============================] - 5s 7ms/step - loss: 0.2481 - binary_accuracy: 0.9125 - val_loss: 0.2959 - val_binary_accuracy: 0.8782 Epoch 10/10 625/625 [==============================] - 5s 7ms/step - loss: 0.2328 - binary_accuracy: 0.9161 - val_loss: 0.2913 - val_binary_accuracy: 0.8792 782/782 [==============================] - 10s 12ms/step - loss: 0.3099 - binary_accuracy: 0.8741 Loss is : 0.3099007308483124 Accuracy is : 0.8741199970245361
解释
构建模型后,使用“compile”函数对其进行编译。
此处定义的训练模型的步骤数为10。
“fit”函数用于将数据拟合到已构建的模型。
“evaluate”函数用于计算模型在测试数据集上的损失和准确率。
损失和准确率的值显示在控制台上。
广告