简体   繁体   English

如何将 TensorFlow 脚本升级到 TensorFlow 2.0

[英]How to upgrade TensorFlow script to TensorFlow 2.0

I am trying to convert and run a kind of hello world script from a TensorFlow Tutorial in Version 2.0 but cannot get this to work no matter what I try:-(我正在尝试从 2.0 版的 TensorFlow 教程中转换和运行一种 hello world 脚本,但无论我尝试什么都无法让它工作:-(

I tried using the tf_upgrade_v2 script but it also leaves the python code with an error because it does not seem to be able to replace the usage of the tf.keras.Input() statements (which are tf.placeholder statements in the original code).我尝试使用 tf_upgrade_v2 脚本,但它也使 python 代码出现错误,因为它似乎无法替换 tf.keras.Input() 语句(原始代码中的 tf.placeholder 语句)的使用. So, I tried converting to 2.0 manually but that does not seem to work either as I am stuck for while finding no solution to the error shown below.因此,我尝试手动转换为 2.0,但这似乎也不起作用,因为我被困住了,同时找不到下面显示的错误的解决方案。

I am currently looking at the below code but it generates the below error message.我目前正在查看以下代码,但它会生成以下错误消息。 Does someone see a way to fix this?有人看到解决这个问题的方法吗?

Error Message错误信息


ValueError                                Traceback (most recent call last)
<ipython-input-25-27dc7c3cea56> in <module>()
      1 # 4. define a Gradient descent optimizer that will minimize the loss defined in the operation 'cost'
----> 2 optimizer = tf.optimizers.SGD(learning_rate=learning_rate, name='SGD').minimize(loss=tf_cost,var_list=[tf_size_factor, tf_price_offset])

2 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v2.py in _filter_grads(grads_and_vars)
   1269   if not filtered:
   1270     raise ValueError("No gradients provided for any variable: %s." %
-> 1271                      ([v.name for _, v in grads_and_vars],))
   1272   if vars_with_empty_grads:
   1273     logging.warning(

ValueError: No gradients provided for any variable: ['size_factor:0', 'price_offset:0']. 

Python Code Python代码

# This is a very simple prediction of house prices based on house size, implemented in TensorFlow.
#

import tensorflow as tf
import numpy as np
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation  # import animation support

# Generating house sizes between 1000 and 3500 (typical sq feet of house)
num_house = 160
np.random.seed(42)
house_size = np.random.randint(low=1000, high=3500, size=num_house)

# Generate house prizes from house size with a random noise added
np.random.seed(42)
house_price = house_size * 100.0 + np.random.randint(low=20000, high=70000, size=num_house)

print ('house_size type:', type(house_size))
print ('house_prize type:', type(house_price))

# Plot generated house and size
plt.plot(house_size, house_price, "bx")  # bx = blue x
plt.ylabel("Price")
plt.xlabel("Size")
plt.show()

# We need to normalize values to prevent under/overflow
def normalize(array):
    return (array - array.mean()) / array.std()

# define number of training samples, 0.7 = 70%. We can take the first 70% since the values are randomized
num_train_samples = math.floor(num_house * 0.7)

# defining training data
train_house_size = np.asarray(house_size[:num_train_samples])
train_price = np.asarray(house_price[:num_train_samples:])

train_house_size_norm = normalize(train_house_size)
train_price_norm = normalize(train_price)

# define test data
test_house_size = np.array(house_size[num_train_samples:])
test_house_price = np.array(house_price[num_train_samples:])

test_house_size_norm = normalize(test_house_size)
test_house_price_norm = normalize(test_house_price)

# Set up the TensorFlow placeholders that get updated as we descend down the gradient
# Replacing tf.placeholder() in TF 1.x with tf.keras.Input() -> https://stackoverflow.com/questions/58986126/replacing-placeholder-for-tensorflow-v2
tf_house_size = tf.keras.Input(name="house_size", shape=(), dtype=tf.dtypes.float32)
tf_price = tf.keras.Input(name="price", shape=(), dtype=tf.dtypes.float32)

print('tf_house_size:', type(tf_house_size))
print('tf_price:', type(tf_price))

# Define the variables holding the size_factor and price we set during training.
# We define them to some random values based on the normal destribution.
tf_size_factor = tf.Variable(np.random.randn(), name="size_factor")
tf_price_offset = tf.Variable(np.random.randn(), name="price_offset")

# 2. Define the operations for the predicting values - predicted price = (size_factor * house_size) + price_offset
# Notice, the use of the tensorflow add and multiply functions. These add the operations to the computation graph,
# AND the tensorflow methods understand how to deal with Tensors. Therefore, do not try to use numpy or other library methods.
tf_price_pred = tf.add(tf.multiply(tf_size_factor, tf_house_size), tf_price_offset)

# 3. Define the loss Function (how much error) - Mean squared error
tf_cost = lambda: tf.reduce_sum(tf.pow(tf_price_pred - tf_price, 2)) / (2 * num_train_samples)

# Optimizer learning rate. The size of the stops down the gradient.
learning_rate = 0.1

# 4. define a Gradient descent optimizer that will minimize the loss defined in the operation 'cost'
optimizer = tf.optimizers.SGD(learning_rate=learning_rate, name='SGD').minimize(loss=tf_cost,var_list=[tf_size_factor, tf_price_offset])

You can pip install whatever version you want with following explicit pip install:您可以 pip 安装您想要的任何版本,并按照以下明确的 pip 安装:

pip install tensorflow==<VersionYouDesire>

If this doesn't fix your issue, I might recommend switching to an older/newer Python version.如果这不能解决您的问题,我可能会建议切换到较旧/较新的 Python 版本。 From what I remember, TF2 didn't support every package with Python 3.7+ until end of 2019.据我记得,直到 2019 年底,TF2 才支持 Python 3.7+ 的所有 package。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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