简体   繁体   English

如何在 TensorFlow 中定义变量

[英]How to define a variable in TensorFlow

I am stuck in defining the variables.我一直在定义变量。

My code is:我的代码是:

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)

Until this point, the code is running smoothly, but here,到此为止,代码运行流畅,但是在这里,

scaled_train_images = scaled_train_images[..., np.newaxis]
scaled_test_images = scaled_test_images[..., np.newaxis]

I get this error:我收到此错误:

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

I wonder if inserting this code def train_model(model, scaled_train_images, train_labels): is fine.我想知道插入此代码def train_model(model, scaled_train_images, train_labels):是否可以。 But here again, I bumped into similar issues like history, frame and some other variables being not able to be defined.但在这里,我又遇到了类似的问题,比如历史、框架和其他一些无法定义的变量。

FYI: I am trying to run my code on the Coursera Course for Imperial London College: Getting Started with TensorFlow 2.仅供参考:我正在尝试在伦敦帝国学院的 Coursera 课程上运行我的代码:TensorFlow 2 入门。

I am a beginner, with no prior knowledge of Python.我是初学者,没有 Python 的先验知识。

I believe the issue is that you need to remove the line:我认为问题是您需要删除该行:

def train_model(model, scaled_train_images, train_labels):

Python is interpreting the scaled_train_images, scaled_test_images assignment as part of that function rather than outside its scope. Python 将scaled_train_images, scaled_test_images分配解释为 function 的一部分,而不是在其 scope 之外。

Here is a python notebook you can use as reference material for this course: https://github.com/ahmadmustafaanis/Getting-Started-with-Tensorflow-2/blob/master/TF.Keras%20Sequential%20API%20Basics/MNISIT.ipynb这是一个 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM