- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
训练具有三个特征的 LSTM 模型,但在预测时,我收到一个 matmul 错误,看起来预测调用的输入只期望一个特征。
matmul:In[0]:[2,3],In[1]:[1,101]
这看起来像是三个输入,但该层只需要 1 个输入,如果该层需要 3 个输入(如训练中那样),那么第二个矩阵将为 [3,101],并且 matmul 将起作用。
带数据的简化代码和下面的错误。
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
print(tf.__version__)
lag = 1
epochs = 2
learning_rate = 0.001
dropout = 0.2
feature_count = 3
data_raw = np.array([[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]])
dataset = pd.DataFrame(data_raw)
times = pd.date_range('1990-01-01', periods=dataset.shape[0], freq='M')
dataset = dataset.set_index(times)
def MakeLayerLSTMInput(units, input_shape, return_sequences=False):
return tf.keras.layers.RNN(tf.keras.layers.LSTMCell(units=units, dropout=dropout, input_shape=input_shape),
return_sequences=return_sequences)
def MakeLayerLSTM(units, return_sequences=False):
return tf.keras.layers.RNN(tf.keras.layers.LSTMCell(units=units, dropout=dropout),
return_sequences=return_sequences)
def MakeLayerDense(units):
return tf.keras.layers.Dense(units=units)
def MakeModelStart():
return tf.keras.models.Sequential()
def MakeOptimizer():
return tf.train.AdamOptimizer(learning_rate=learning_rate)
def MakeModel():
model_inputs = (1, feature_count)
print("model_inputs "+str(model_inputs))
regressor = MakeModelStart()
regressor.add(MakeLayerLSTMInput(101, model_inputs))
regressor.add(MakeLayerDense(1))
regressor.compile(optimizer = MakeOptimizer(), loss = 'mean_squared_error')
return regressor
train_dataset = dataset.take(range(10))
test_dataset = dataset.take(range(10,12))
normalize = MinMaxScaler(feature_range = (0, 1))
train_dataset = normalize.fit_transform(train_dataset)
print('train shape: '+str(train_dataset.shape))
x_train = []
y_train = []
for i in range(lag, train_dataset.shape[0]):
x_train.append(train_dataset[i-lag:i, 0:feature_count])
y_train.append(train_dataset[i, 0])
x_train, y_train = np.array(x_train), np.array(y_train)
x_train = np.reshape(x_train, (train_dataset.shape[0]-lag, feature_count, 1))
print('normalized x train shape: '+str(x_train.shape))
print('normalized y train shape: '+str(y_train.shape))
regressor = MakeModel()
regressor.fit(x_train, y_train, epochs = epochs, batch_size = x_train.shape[0], verbose=1)
p_count=2
print("last years shape "+str(dataset.shape))
inputs = dataset[len(dataset) - len(test_dataset) - p_count :].values
print("inputs shape "+str(inputs.shape))
inputs = normalize.transform(inputs)
X_test = []
for i in range(p_count, len(inputs)):
X_test.append(inputs[i-p_count:i, 0:feature_count])
X_test = np.array(X_test)
print("X test shape "+str(X_test.shape))
X_test = np.reshape(X_test, (len(inputs) - p_count, X_test.shape[1], feature_count))
print("X test re-shape "+str(X_test.shape))
predicted = regressor.predict(X_test)
predicted = normalize.inverse_transform(predicted)
print("mse: "+str(mean_squared_error(test_dataset.values, predicted)))
输出:
(p36) D:\src\ml\MLPhase2>python ea-simple1.py
1.13.1
d:\apps\Miniconda3\envs\p36\lib\site-packages\sklearn\preprocessing\data.py:323: DataConversionWarning: Data with input dtype int32 were all converted to float64 by MinMaxScaler.
return self.partial_fit(X, y)
train shape: (10, 3)
normalized x train shape: (9, 3, 1)
normalized y train shape: (9,)
model_inputs (1, 3)
WARNING:tensorflow:From d:\apps\Miniconda3\envs\p36\lib\site-packages\tensorflow\python\ops\resource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
WARNING:tensorflow:From d:\apps\Miniconda3\envs\p36\lib\site-packages\tensorflow\python\keras\backend.py:4010: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.
Instructions for updating:
Please use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.
WARNING:tensorflow:From d:\apps\Miniconda3\envs\p36\lib\site-packages\tensorflow\python\keras\utils\losses_utils.py:170: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
WARNING:tensorflow:From d:\apps\Miniconda3\envs\p36\lib\site-packages\tensorflow\python\ops\math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.cast instead.
Epoch 1/2
2019-04-24 13:19:13.920954: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
2019-04-24 13:19:14.192634: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1433] Found device 0 with properties:
name: GeForce RTX 2080 Ti major: 7 minor: 5 memoryClockRate(GHz): 1.635
pciBusID: 0000:42:00.0
totalMemory: 11.00GiB freeMemory: 9.03GiB
2019-04-24 13:19:14.204693: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1512] Adding visible gpu devices: 0
2019-04-24 13:19:14.858476: I tensorflow/core/common_runtime/gpu/gpu_device.cc:984] Device interconnect StreamExecutor with strength 1 edge matrix:
2019-04-24 13:19:14.863341: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990] 0
2019-04-24 13:19:14.866858: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1003] 0: N
2019-04-24 13:19:14.872024: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1115] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 8698 MB memory) -> physical GPU (device: 0, name: GeForce RTX 2080 Ti, pci bus id: 0000:42:00.0, compute capability: 7.5)
2019-04-24 13:19:15.863877: I tensorflow/stream_executor/dso_loader.cc:152] successfully opened CUDA library cublas64_100.dll locally
9/9 [==============================] - 2s 261ms/sample - loss: 0.0000e+00
Epoch 2/2
9/9 [==============================] - 0s 1ms/sample - loss: 0.0000e+00
last years shape (12, 3)
inputs shape (4, 3)
X test shape (2, 2, 3)
X test re-shape (2, 2, 3)
Traceback (most recent call last):
File "ea-simple1.py", line 69, in <module>
predicted = regressor.predict(X_test)
File "d:\apps\Miniconda3\envs\p36\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1113, in predict
self, x, batch_size=batch_size, verbose=verbose, steps=steps)
File "d:\apps\Miniconda3\envs\p36\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py", line 329, in model_iteration
batch_outs = f(ins_batch)
File "d:\apps\Miniconda3\envs\p36\lib\site-packages\tensorflow\python\keras\backend.py", line 3076, in __call__
run_metadata=self.run_metadata)
File "d:\apps\Miniconda3\envs\p36\lib\site-packages\tensorflow\python\client\session.py", line 1439, in __call__
run_metadata_ptr)
File "d:\apps\Miniconda3\envs\p36\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 528, in __exit__
c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [2,3], In[1]: [1,101]
[[{{node while/MatMul_2}}]]
[[{{node BiasAdd_4}}]]
最佳答案
问题在于 x_train.reshape 与 x_test.reshape 分别作为拟合和预测的输入不匹配。我有(-1,3,1)用于训练输入,(-1,1,3)用于预测输入。这只是我的错误。一点点橡皮鸭会有很大帮助。
关于python - 具有三个特征的 LSTM 训练,但由于输入形状而无法预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55835696/
这是代码片段。 请说出这种用小内存存储大数据的算法是什么。 public static void main(String[] args) { long longValue = 21474836
所以我使用 imap 从 gmail 和 outlook 接收电子邮件。 Gmail 像这样编码 =?UTF-8?B?UmU6IM69zq3OvyDOtc68zrHOuc67IG5ldyBlbWFpb
很久以前就学会了 C 代码;想用 Scheme 尝试一些新的和不同的东西。我正在尝试制作一个接受两个参数并返回两者中较大者的过程,例如 (define (larger x y) (if (> x
Azure 恢复服务保管库有两个备份配置选项 - LRS 与 GRS 这是一个有关 Azure 恢复服务保管库的问题。 当其驻留区域发生故障时,如何处理启用异地冗余的恢复服务保管库?如果未为恢复服务启
说,我有以下实体: @Entity public class A { @Id @GeneratedValue private Long id; @Embedded private
我有下一个问题。 我有下一个标准: criteria.add(Restrictions.in("entity.otherEntity", getOtherEntitiesList())); 如果我的
如果这是任何类型的重复,我会提前申请,但我找不到任何可以解决我的具体问题的内容。 这是我的程序: import java.util.Random; public class CarnivalGame{
我目前正在使用golang创建一个聚合管道,在其中使用“$ or”运算符查询文档。 结果是一堆需要分组的未分组文档,这样我就可以进入下一阶段,找到两个数据集之间的交集。 然后将其用于在单独的集合中进行
是否可以在正则表达式中创建 OR 条件。 我正在尝试查找包含此类模式的文件名列表的匹配项 第一个案例 xxxxx-hello.file 或者案例二 xxxx-hello-unasigned.file
该程序只是在用户输入行数时创建菱形的形状,因此它有 6 个 for 循环; 3 个循环创建第一个三角形,3 个循环创建另一个三角形,通过这 2 个三角形和 6 个循环,我们得到了一个菱形,这是整个程序
我有一个像这样的查询字符串 www.google.com?Department=Education & Finance&Department=Health 我有这些 li 标签,它们的查询字符串是这样
我有一个带有静态构造函数的类,我用它来读取 app.config 值。如何使用不同的配置值对类进行单元测试。我正在考虑在不同的应用程序域中运行每个测试,这样我就可以为每个测试执行静态构造函数 - 但我
我正在寻找一个可以容纳多个键的容器,如果我为其中一个键值输入保留值(例如 0),它会被视为“或”搜索。 map, int > myContainer; myContainer.insert(make_
我正在为 Web 应用程序创建数据库,并正在寻找一些建议来对可能具有多种类型的单个实体进行建模,每种类型具有不同的属性。 作为示例,假设我想为“数据源”对象创建一个关系模型。所有数据源都会有一些共享属
(1) =>CREATE TABLE T1(id BIGSERIAL PRIMARY KEY, name TEXT); CREATE TABLE (2) =>INSERT INTO T1 (name)
我不确定在使用别名时如何解决不明确的列引用。 假设有两个表,a 和 b,它们都有一个 name 列。如果我加入这两个表并为结果添加别名,我不知道如何为这两个表引用 name 列。我已经尝试了一些变体,
我的查询是: select * from table where id IN (1,5,4,3,2) 我想要的与这个顺序完全相同,不是从1...5,而是从1,5,4,3,2。我怎样才能做到这一点? 最
我正在使用 C# 代码执行动态生成的 MySQL 查询。抛出异常: CREATE TABLE dump ("@employee_OID" VARCHAR(50)); "{"You have an er
我有日期 2016-03-30T23:59:59.000000+0000。我可以知道它的格式是什么吗?因为如果我使用 yyyy-MM-dd'T'HH:mm:ss.SSS,它会抛出异常 最佳答案 Sim
我有一个示例模式,它的 SQL Fiddle 如下: http://sqlfiddle.com/#!2/6816b/2 这个 fiddle 只是根据 where 子句中的条件查询示例数据库,如下所示:
我是一名优秀的程序员,十分优秀!