- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在学习 Tensorflow 2.0,我认为在 Tensorflow 中实现最基本的简单线性回归是个好主意。不幸的是,我遇到了几个问题,我想知道这里是否有人可以提供帮助。
考虑以下设置:
import tensorflow as tf # 2.0.0-alpha0
import numpy as np
x_data = np.random.randn(2000, 1)
w_real = [0.7] # coefficients
b_real = -0.2 # global bias
noise = np.random.randn(1, 2000) * 0.5 # level of noise
y_data = np.matmul(w_real, x_data.T) + b_real + noise
现在开始模型定义:
# modelling this data with tensorflow (manually!)
class SimpleRegressionNN(tf.keras.Model):
def __init__(self):
super(SimpleRegressionNN, self).__init__()
self.input_layer = tf.keras.layers.Input
self.output_layer = tf.keras.layers.Dense(1)
def call(self, data_input):
model = self.input_layer(data_input)
model = self.output_layer(model)
# open question: how to account for the intercept/bias term?
# Ideally, we'd want to generate preds as matmult(X,W) + b
return model
nn_regressor = SimpleRegressionNN()
reg_loss = tf.keras.losses.MeanSquaredError()
reg_optimiser = tf.keras.optimizers.SGD(0.1)
metric_accuracy = tf.keras.metrics.mean_squared_error
# define forward step
@tf.function
def train_step(x_sample, y_sample):
with tf.GradientTape() as tape:
predictions = nn_regressor(x_sample)
loss = reg_loss(y_sample, predictions)
gradients = tape.gradient(loss, nn_regressor.trainable_variables) # had to indent this!
reg_optimiser.apply_gradients(zip(gradients, nn_regressor.trainable_variables))
metric_accuracy(y_sample, predictions)
#%%
# run the model
for epoch in range(10):
for x_point, y_point in zip(x_data.T[0], y_data[0]): # batch of 1
train_step(x_sample=x_point, y_sample=y_point)
print("MSE: {}".format(metric_accuracy.result()))
不幸的是,我收到以下错误:
TypeError: You are attempting to use Python control flow in a layer that was not declared to be dynamic. Pass `dynamic=True` to the class constructor.
Encountered error:
"""
Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn.
"""
完整的错误输出在这里:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
611 inputs)) as auto_updater:
--> 612 outputs = self.call(inputs, *args, **kwargs)
613 auto_updater.set_outputs(outputs)
<ipython-input-5-8464ad8bcf07> in call(self, data_input)
7 def call(self, data_input):
----> 8 model = self.input_layer(data_input)
9 model = self.output_layer(model)
/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/input_layer.py in Input(shape, batch_size, name, dtype, sparse, tensor, **kwargs)
232 sparse=sparse,
--> 233 input_tensor=tensor)
234 # Return tensor including `_keras_history`.
/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/input_layer.py in __init__(self, input_shape, batch_size, dtype, input_tensor, sparse, name, **kwargs)
93 if input_shape is not None:
---> 94 batch_input_shape = (batch_size,) + tuple(input_shape)
95 else:
/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in __iter__(self)
448 raise TypeError(
--> 449 "Tensor objects are only iterable when eager execution is "
450 "enabled. To iterate over this tensor use tf.map_fn.")
TypeError: Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn.
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-22-e1bde858b0fc> in <module>()
3 #train_step(x_sample=x_data.T[0], y_sample=y_data[0])
4 for x_point, y_point in zip(x_data.T[0], y_data[0]):
----> 5 train_step(x_sample=x_point, y_sample=y_point)
6 print("MSE: {}".format(metric_accuracy.result()))
7
/anaconda3/lib/python3.6/site-packages/tensorflow/python/eager/def_function.py in __call__(self, *args, **kwds)
416 # In this case we have not created variables on the first call. So we can
417 # run the first trace but we should fail if variables are created.
--> 418 results = self._stateful_fn(*args, **kwds)
419 if self._created_variables:
420 raise ValueError("Creating variables on a non-first call to a function"
/anaconda3/lib/python3.6/site-packages/tensorflow/python/eager/function.py in __call__(self, *args, **kwargs)
1285 def __call__(self, *args, **kwargs):
1286 """Calls a graph function specialized to the inputs."""
-> 1287 graph_function, args, kwargs = self._maybe_define_function(args, kwargs)
1288 return graph_function._filtered_call(args, kwargs) # pylint: disable=protected-access
1289
/anaconda3/lib/python3.6/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)
1609 relaxed_arg_shapes)
1610 graph_function = self._create_graph_function(
-> 1611 args, kwargs, override_flat_arg_shapes=relaxed_arg_shapes)
1612 self._function_cache.arg_relaxed[rank_only_cache_key] = graph_function
1613
/anaconda3/lib/python3.6/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)
1510 arg_names=arg_names,
1511 override_flat_arg_shapes=override_flat_arg_shapes,
-> 1512 capture_by_value=self._capture_by_value),
1513 self._function_attributes)
1514
/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
692 converted_func)
693
--> 694 func_outputs = python_func(*func_args, **func_kwargs)
695
696 # invariant: `func_outputs` contains only Tensors, IndexedSlices,
/anaconda3/lib/python3.6/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
315 # __wrapped__ allows AutoGraph to swap in a converted function. We give
316 # the function a weak reference to itself to avoid a reference cycle.
--> 317 return weak_wrapped_fn().__wrapped__(*args, **kwds)
318 weak_wrapped_fn = weakref.ref(wrapped_fn)
319
/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
684 optional_features=autograph_options,
685 force_conversion=True,
--> 686 ), args, kwargs)
687
688 # Wrapping around a decorator allows checks like tf_inspect.getargspec
/anaconda3/lib/python3.6/site-packages/tensorflow/python/autograph/impl/api.py in converted_call(f, owner, options, args, kwargs)
390 return _call_unconverted(f, args, kwargs)
391
--> 392 result = converted_f(*effective_args, **kwargs)
393
394 # The converted function's closure is simply inserted into the function's
/var/folders/8_/pl9fgq297ld3b7kgy5tmvf700000gn/T/tmpluzodr7d.py in tf__train_step(x_sample, y_sample)
2 def tf__train_step(x_sample, y_sample):
3 with tf.GradientTape() as tape:
----> 4 predictions = ag__.converted_call(nn_regressor, None, ag__.ConversionOptions(recursive=True, verbose=0, strip_decorators=(tf.function, defun, ag__.convert, ag__.do_not_convert, ag__.converted_call), force_conversion=False, optional_features=(), internal_convert_user_code=True), (x_sample,), {})
5 loss = ag__.converted_call(reg_loss, None, ag__.ConversionOptions(recursive=True, verbose=0, strip_decorators=(tf.function, defun_1, ag__.convert, ag__.do_not_convert, ag__.converted_call), force_conversion=False, optional_features=(), internal_convert_user_code=True), (y_sample, predictions), {})
6 gradients = ag__.converted_call('gradient', tape, ag__.ConversionOptions(recursive=True, verbose=0, strip_decorators=(tf.function, defun_2, ag__.convert, ag__.do_not_convert, ag__.converted_call), force_conversion=False, optional_features=(), internal_convert_user_code=True), (loss, nn_regressor.trainable_variables), {})
/anaconda3/lib/python3.6/site-packages/tensorflow/python/autograph/impl/api.py in converted_call(f, owner, options, args, kwargs)
265
266 if not options.force_conversion and conversion.is_whitelisted_for_graph(f):
--> 267 return _call_unconverted(f, args, kwargs)
268
269 # internal_convert_user_code is for example turned off when issuing a dynamic
/anaconda3/lib/python3.6/site-packages/tensorflow/python/autograph/impl/api.py in _call_unconverted(f, args, kwargs)
186 return f.__self__.call(args, kwargs)
187
--> 188 return f(*args, **kwargs)
189
190
/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/engine/base_layer.py in __call__(self, inputs, *args, **kwargs)
623 'dynamic. Pass `dynamic=True` to the class '
624 'constructor.\nEncountered error:\n"""\n' +
--> 625 exception_str + '\n"""')
626 raise
627 else:
TypeError: You are attempting to use Python control flow in a layer that was not declared to be dynamic. Pass `dynamic=True` to the class constructor.
Encountered error:
"""
Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn.
"""
麻烦的是,2.0默认设置为eager execution!
除了这个问题,我还有几个额外的问题:
非常感谢!
最佳答案
我有以下评论:
SimpleRegression
模型中不需要Input
层。另外,不要通过“model
”名称调用层的张量输出(就像在 call()
方法中所做的那样)。这真的很令人困惑。train_step
函数。它期望在您传递 (input_dim
, ) 时收到 (n_samples, input_dim)
。tensorflow
中,张量的第一个维度始终是批量大小(即样本数)。永远这样使用它,不要转置。metric_accuracy = tf.keras.metrics.mean_squared_error
精度?你有一个回归问题,回归中没有准确性这样的东西。另外,为什么要定义两次并计算两次 mse
?tf.convert_to_tensor()
转换数据,执行速度会更快。train_step()
执行前向和后向传递,而不仅仅是前向传递。train_step()
不返回任何内容,您希望如何打印 mse
损失的值。这是您的代码的更正版本:
import tensorflow as tf # 2.0.0-alpha0
import numpy as np
x_data = np.random.randn(5, 2)
w_real = 0.7 # coefficients
b_real = -0.2 # global bias
noise = np.random.randn(5, 2) * 0.01 # level of noise
y_data = w_real * x_data + b_real + noise
class SimpleRegressionNN(tf.keras.Model):
def __init__(self):
super(SimpleRegressionNN, self).__init__()
self.output_layer = tf.keras.layers.Dense(1, input_shape=(2, ))
def call(self, data_input):
result = self.output_layer(data_input)
return result
reg_loss = tf.keras.losses.MeanSquaredError()
reg_optimiser = tf.keras.optimizers.SGD(0.1)
nn_regressor = SimpleRegressionNN()
@tf.function
def train_step(x_sample, y_sample):
with tf.GradientTape() as tape:
predictions = nn_regressor(x_sample)
loss = reg_loss(y_sample, predictions)
gradients = tape.gradient(loss, nn_regressor.trainable_variables) # had to indent this!
reg_optimiser.apply_gradients(zip(gradients, nn_regressor.trainable_variables))
return loss
for x_point, y_point in zip(x_data, y_data): # batch of 1
x_point, y_point = tf.convert_to_tensor([x_point]), tf.convert_to_tensor([y_point])
mse = train_step(x_sample=x_point, y_sample=y_point)
print("MSE: {}".format(mse.numpy()))
关于python - 在基础 Tensorflow 2.0 中运行简单回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55734820/
好的,所以我想从批处理文件运行我的整个工作环境... 我想要实现什么...... 打开新的 powershell,打开我的 API 文件夹并从该文件夹运行 VS Code 编辑器(cd c:\xy;
我正在查看 Cocoa Controls 上的示例并下载了一些演示。我遇到的问题是一些例子,比如 BCTabBarController ,不会在我的设备上构建或启动。当我打开项目时,它看起来很正常,没
我刚刚开始学习 C 语言(擅长 Java 和 Python)。 当编写 C 程序(例如 hello world)时,我在 ubuntu cmd 行上使用 gcc hello.c -o hello 编译
我在 php 脚本从 cron 开始运行到超时后注意到了这个问题,但是当它从命令行手动运行时这不是问题。 (对于 CLI,PHP 默认的 max_execution_time 是 0) 所以我尝试运行
我可以使用命令行运行测试 > ./node_modules/.bin/wdio wdio.conf.js 但是如果我尝试从 IntelliJ 的运行/调试配置运行它,我会遇到各种不同的错误。 Fea
Error occurred during initialization of VM. Could not reserve enough space for object heap. Error: C
将 Anaconda 安装到 C:\ 后,我无法打开 jupyter 笔记本。无论是在带有 jupyter notebook 的 Anaconda Prompt 中还是在导航器中。我就是无法让它工作。
我遇到一个问题,如果我双击我的脚本 (.py),或者使用 IDLE 打开它,它将正确编译并运行。但是,如果我尝试在 Windows 命令行中运行脚本,请使用 C:\> "C:\Software_Dev
情况 我正在使用 mysql 数据库。查询从 phpmyadmin 和 postman 运行 但是当我从 android 发送请求时(它返回零行) 我已经记录了从 android 发送的电子邮件是正确
所以这个有点奇怪 - 为什么从 Java 运行 .exe 文件会给出不同的输出而不是直接运行 .exe。 当 java 在下面的行执行时,它会调用我构建的可与 3CX 电话系统配合使用的 .exe 文
这行代码 Environment.Is64BitProcess 当我的应用单独运行时评估为真。 但是当它在我的 Visual Studio 单元测试中运行时,相同的表达式的计算结果为 false。 我
关闭。这个问题是opinion-based .它目前不接受答案。 想要改进这个问题? 更新问题,以便 editing this post 可以用事实和引用来回答它. 关闭 8 年前。 Improve
我写了一个使用 libpq 连接到 PostgreSQL 数据库的演示。 我尝试通过包含将 C 文件连接到 PostgreSQL #include 在我将路径添加到系统变量 I:\Program F
如何从 Jenkins 运行 Android 模拟器来运行我的测试?当我在 Execiute Windows bath 命令中写入时,运行模拟器的命令: emulator -avd Tester 然后
我已经配置好东西,这样我就可以使用 ssl 登录和访问在 nginx 上运行的 errbit 我的问题是我不知道如何设置我的 Rails 应用程序的 errbit.rb 以便我可以运行测试 nginx
我编写了 flutter 应用程序,我通过 xcode 打开了 ios 部分并且应用程序正在运行,但是当我通过 flutter build ios 通过 vscode 运行应用程序时,我得到了这个错误
我有一个简短的 python 脚本,它使用日志记录模块和 configparser 模块。我在Win7下使用PyCharm 2.7.1和Python 3.3。 当我使用 PyCharm 运行我的脚本时
我在这里遇到了一些难题。 我的开发箱是 64 位的,windows 7。我所有的项目都编译为“任何 CPU”。该项目引用了 64 位版本的第 3 方软件 当我运行不使用任何 Web 引用的单元测试时,
当我注意到以下问题时,我正在做一些 C++ 练习。给定的代码将不会在 Visual Studio 2013 或 Qt Creator 5.4.1 中运行/编译 报错: invalid types 'd
假设我有一个 easteregg.py 文件: from airflow import DAG from dateutil import parser from datetime import tim
我是一名优秀的程序员,十分优秀!