[英]How to define a variable in TensorFlow
我一直在定義變量。
我的代碼是:
import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D
mnist_data = tf.keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist_data.load_data()``
def scale_mnist_data(train_images, test_images):
return (train_images / 255, test_images / 255)
def train_model(model, scaled_train_images, train_labels):
scaled_train_images, scaled_test_images = scale_mnist_data(train_images, test_images)
到此為止,代碼運行流暢,但是在這里,
scaled_train_images = scaled_train_images[..., np.newaxis]
scaled_test_images = scaled_test_images[..., np.newaxis]
我收到此錯誤:
NameError Traceback (most recent call last)
<ipython-input-5-7e4c845d2449> in <module>
1 # Add a dummy channel dimension
2
----> 3 scaled_train_images = scaled_train_images[..., np.newaxis]
4 scaled_test_images = scaled_test_images[..., np.newaxis]
NameError: name 'scaled_train_images' is not defined
我想知道插入此代碼def train_model(model, scaled_train_images, train_labels):
是否可以。 但在這里,我又遇到了類似的問題,比如歷史、框架和其他一些無法定義的變量。
僅供參考:我正在嘗試在倫敦帝國學院的 Coursera 課程上運行我的代碼:TensorFlow 2 入門。
我是初學者,沒有 Python 的先驗知識。
我認為問題是您需要刪除該行:
def train_model(model, scaled_train_images, train_labels):
Python 將scaled_train_images, scaled_test_images
分配解釋為 function 的一部分,而不是在其 scope 之外。
這是一個 python 筆記本,您可以用作本課程的參考資料: https://github.com/ahmadmustafaanis/Getting-Started-with-Tensorflow-2/blob/master/TF.Keras%20Sequential%20API%20ITBas .ipynb
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.