简体   繁体   中英

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. 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.

I am a beginner, with no prior knowledge of 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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