[英]Pytorch tutorial code error: “NameError: name 'net' is not defined”
[英]Keras Tutorial Error: NameError: name 'layers' is not defined
我正在嘗試遵循此Keras 教程,但是在使用命令python3 test.py
編譯時遇到以下錯誤:
Traceback (most recent call last):
File "test.py", line 13, in <module>
layers.Dense(64, activation='sigmoid')
NameError: name 'layers' is not defined
我的代碼如下:
import tensorflow as tf
from tensorflow import keras
model = keras.Sequential()
# Adds a densely-connected layer with 64 units to the model:
model.add(keras.layers.Dense(64, activation='relu'))
# Add another:
model.add(keras.layers.Dense(64, activation='relu'))
# Add a softmax layer with 10 output units:
model.add(keras.layers.Dense(10, activation='softmax'))
# Create a sigmoid layer:
layers.Dense(64, activation='sigmoid')
# A linear layer with L1 regularization of factor 0.01 applied to the kernel matrix:
layers.Dense(64, kernel_regularizer=keras.regularizers.l1(0.01))
# A linear layer with L2 regularization of factor 0.01 applied to the bias vector:
layers.Dense(64, bias_regularizer=keras.regularizers.l2(0.01))
# A linear layer with a kernel initialized to a random orthogonal matrix:
layers.Dense(64, kernel_initializer='orthogonal')
Python版本:3.6.6
操作系統:MacOS High Sierra
我也在命令行(tensorflow)$
環境中執行所有這些操作。
首先,python 向您發出信號,表示腳本范圍內不存在具有名稱layers
的對象。
但實際的錯誤是代碼是從TensorFlow 的 Keras 文檔中復制出來的,但在文檔中,代碼的第二部分僅用於解釋在model.add(...)
調用中實例化的model.add(...)
。
所以只需刪除所有以layers
開頭的代碼,因為它只是一個解釋。
import tensorflow as tf
from tensorflow import keras
model = keras.Sequential()
# Adds a densely-connected layer with 64 units to the model:
model.add(keras.layers.Dense(64, activation='relu'))
# Add another:
model.add(keras.layers.Dense(64, activation='relu'))
# Add a softmax layer with 10 output units:
model.add(keras.layers.Dense(10, activation='softmax'))
您應該考慮在Keras 文檔中了解Keras 。
對我來說,使用from tensorflow.keras import layers
完成了這項工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.