- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 Python 中的 TensorFlow 和 Keras 使用循环神经网络进行每小时预测。我已将神经网络的输入分配为 (None, None, 5),如我的 所示。 。
但是,我收到错误ː
ValueError: Error when checking input: expected gru_3_input to have shape (None, None, 10) but got array with shape (1, 4, 1)
My MVCE code isː
%matplotlib inline
#!pip uninstall keras
#!pip install keras==2.1.2
import tensorflow as tf
import pandas as pd
from pandas import DataFrame
import math
#####Create the Recurrent Neural Network###
model = Sequential()
model.add(GRU(units=5,
return_sequences=True,
input_shape=(None, num_x_signals)))
## This line is going to map the above 512 values to just 1 (num_y_signal)
model.add(Dense(num_y_signals, activation='sigmoid'))
if False:
from tensorflow.python.keras.initializers import RandomUniform
# Maybe use lower init-ranges.##### I may have to change these during debugging####
init = RandomUniform(minval=-0.05, maxval=0.05)
model.add(Dense(num_y_signals,
activation='linear',
kernel_initializer=init))
warmup_steps = 5
def loss_mse_warmup(y_true, y_pred):
#
# Ignore the "warmup" parts of the sequences
# by taking slices of the tensors.
y_true_slice = y_true[:, warmup_steps:, :]
y_pred_slice = y_pred[:, warmup_steps:, :]
# These sliced tensors both have this shape:
# [batch_size, sequence_length - warmup_steps, num_y_signals]
# Calculate the MSE loss for each value in these tensors.
# This outputs a 3-rank tensor of the same shape.
loss = tf.losses.mean_squared_error(labels=y_true_slice,
predictions=y_pred_slice)
loss_mean = tf.reduce_mean(loss)
return loss_mean
optimizer = RMSprop(lr=1e-3) ### This is somthing related to debugging
model.compile(loss=loss_mse_warmup, optimizer=optimizer)#### I may have to make the output a singnal rather than the whole data set
print(model.summary())
model.fit_generator(generator=generator,
epochs=20,
steps_per_epoch=100,
validation_data=validation_data)
我不确定为什么会这样,但我相信这可能与 reshape 我的训练和测试数据有关。 ɪ还附上了我的完整向我的代码发送错误消息以使问题可重现。
最佳答案
我不确定正确性,但它是:
%matplotlib inline
#!pip uninstall keras
#!pip install keras==2.1.2
import tensorflow as tf
import pandas as pd
from pandas import DataFrame
import math
import numpy
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
import datetime
from keras.layers import Input, Dense, GRU, Embedding
from keras.optimizers import RMSprop
from keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, ReduceLROnPlateau
datetime = [datetime.datetime(2012, 1, 1, 1, 0, 0) + datetime.timedelta(hours=i) for i in range(10)]
X=np.array([2.25226244,1.44078451,0.99174488,0.71179491,0.92824542,1.67776948,2.96399534,5.06257161,7.06504245,7.77817664
,0.92824542,1.67776948,2.96399534,5.06257161,7.06504245,7.77817664])
y= np.array([0.02062136,0.00186715,0.01517354,0.0129046 ,0.02231125,0.01492537,0.09646542,0.28444476,0.46289928,0.77817664
,0.02231125,0.01492537,0.09646542,0.28444476,0.46289928,0.77817664])
X = X[1:11]
y= y[1:11]
df = pd.DataFrame({'date':datetime,'y':y,'X':X})
df['t']= [x for x in range(10)]
df['X-1'] = df['X'].shift(-1)
x_data = df['X-1'].fillna(0)
y_data = y
num_data = len(x_data)
#### training and testing split####
train_split = 0.6
num_train = int(train_split*num_data)
num_test = num_data-num_train## number of observations in test set
#input train test
x_train = x_data[0:num_train].reshape(-1, 1)
x_test = x_data[num_train:].reshape(-1, 1)
#print (len(x_train) +len( x_test))
#output train test
y_train = y_data[0:num_train].reshape(-1, 1)
y_test = y_data[num_train:].reshape(-1, 1)
#print (len(y_train) + len(y_test))
### number of input signals
num_x_signals = x_data.shape[0]
# print (num_x_signals)
## number of output signals##
num_y_signals = y_data.shape[0]
#print (num_y_signals)
####data scalling'###
x_scaler = MinMaxScaler(feature_range=(0,1))
x_train_scaled = x_scaler.fit_transform(x_train)
x_test_scaled = MinMaxScaler(feature_range=(0,1)).fit_transform(x_test)
y_scaler = MinMaxScaler()
y_train_scaled = y_scaler.fit_transform(y_train)
y_test_scaled = MinMaxScaler(feature_range=(0,1)).fit_transform(y_test)
def batch_generator(batch_size, sequence_length):
"""
Generator function for creating random batches of training-data.
"""
# Infinite loop. providing the neural network with random data from the
# datase for x and y
while True:
# Allocate a new array for the batch of input-signals.
x_shape = (batch_size, sequence_length, num_x_signals)
x_batch = np.zeros(shape=x_shape, dtype=np.float16)
# Allocate a new array for the batch of output-signals.
y_shape = (batch_size, sequence_length, num_y_signals)
y_batch = np.zeros(shape=y_shape, dtype=np.float16)
# Fill the batch with random sequences of data.
for i in range(batch_size):
# Get a random start-index.
# This points somewhere into the training-data.
idx = np.random.randint(num_train - sequence_length)
# Copy the sequences of data starting at this index.
x_batch[i] = x_train_scaled[idx:idx+sequence_length]
y_batch[i] = y_train_scaled[idx:idx+sequence_length]
yield (x_batch, y_batch)
batch_size =20
sequence_length = 2
generator = batch_generator(batch_size=batch_size,
sequence_length=sequence_length)
x_batch, y_batch = next(generator)
#########Validation Set Start########
def batch_generator(batch_size, sequence_length):
"""
Generator function for creating random batches of training-data.
"""
# Infinite loop. providing the neural network with random data from the
# datase for x and y
while True:
# Allocate a new array for the batch of input-signals.
x_shape = (batch_size, sequence_length, num_x_signals)
x_batch = np.zeros(shape=x_shape, dtype=np.float16)
# Allocate a new array for the batch of output-signals.
y_shape = (batch_size, sequence_length, num_y_signals)
y_batch = np.zeros(shape=y_shape, dtype=np.float16)
# Fill the batch with random sequences of data.
for i in range(batch_size):
# Get a random start-index.
# This points somewhere into the training-data.
idx = np.random.randint(num_train - sequence_length)
# Copy the sequences of data starting at this index.
x_batch[i] = x_test_scaled[idx:idx+sequence_length]
y_batch[i] = y_test_scaled[idx:idx+sequence_length]
yield (x_batch, y_batch)
validation_data= next(batch_generator(batch_size,sequence_length))
# validation_data = (np.expand_dims(x_test_scaled, axis=0),
# np.expand_dims(y_test_scaled, axis=0))
#Validation set end
#####Create the Recurrent Neural Network###
model = Sequential()
model.add(GRU(units=5,
return_sequences=True,
input_shape=(None, num_x_signals)))
## This line is going to map the above 512 values to just 1 (num_y_signal)
model.add(Dense(num_y_signals, activation='sigmoid'))
if False:
from tensorflow.python.keras.initializers import RandomUniform
# Maybe use lower init-ranges.##### I may have to change these during debugging####
init = RandomUniform(minval=-0.05, maxval=0.05)
model.add(Dense(num_y_signals,
activation='linear',
kernel_initializer=init))
warmup_steps = 5
def loss_mse_warmup(y_true, y_pred):
#
# Ignore the "warmup" parts of the sequences
# by taking slices of the tensors.
y_true_slice = y_true[:, warmup_steps:, :]
y_pred_slice = y_pred[:, warmup_steps:, :]
# These sliced tensors both have this shape:
# [batch_size, sequence_length - warmup_steps, num_y_signals]
# Calculate the MSE loss for each value in these tensors.
# This outputs a 3-rank tensor of the same shape.
loss = tf.losses.mean_squared_error(labels=y_true_slice,
predictions=y_pred_slice)
loss_mean = tf.reduce_mean(loss)
return loss_mean
optimizer = RMSprop(lr=1e-3) ### This is somthing related to debugging
model.compile(loss=loss_mse_warmup, optimizer=optimizer)#### I may have to make the output a singnal rather than the whole data set
print(model.summary())
model.fit_generator(generator=generator,
epochs=20,
steps_per_epoch=100,
validation_data=validation_data)
我仅更改了验证集开始
和验证集结束
之间的部分代码。
关于python - ValueError : Error when checking input: expected gru_5_input to have shape (None, None, 10) 但得到形状为 (1, 4, 1) 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51598437/
这个问题在这里已经有了答案: Why does the print function return None? (1 个回答) 关闭 6 年前。 我正在学习理解。我得到了 print(x) 部分(我
我以为我理解了 Python 中的这两个单例值,直到我看到有人在代码中使用 return l1 or l2,其中 l1 和 l2 都是链表对象,并且(s)他想如果不为 None 则返回 l1,否则返回
我希望在 IPython Notebook 中使用列表理解生成枚举字符串列表。它有效,但给了我一个我不理解的奇怪输出。 cols = [] [cols.append('Value'+str(hour)
这个问题在这里已经有了答案: Why does the expression 0 >> import dis >>> def a(): ... return None is None is N
《Learning Python 5th》第608页有示例代码: >>> list(print(x.upper(), end=' ') for x in 'spam') S P A M [None,
我对此进行了搜索并遇到了列表返回函数,但我仍然不明白。 我试图理解为什么 Print 函数到另一个函数返回以下内容: 生日快乐 生日快乐 无 无 我的代码: def happy(): prin
除非我疯了 if None not in x 和 if not None in x 是等价的。有首选版本吗?我想 None not in 更像英语,因此更像 pythonic,但 not None i
尝试绘制 k-NN 分类器的决策边界但无法这样做得到 TypeError: '(slice(None, None, None), 0)' is an invalid key h = .01 # st
我正在尝试将可变大小的序列输入 LSTM。因此我使用生成器且批量大小为 1。 我有一个嵌入的 (sequence_length,)-input-tensor,并输出 (batch_size,equen
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: Is there any way to know if the value of an argument i
我正在尝试根据环境变量的返回值进行条件赋值。 self._TBLFilePath = iTBLFilePath or os.environ.get("CDO_TBLPATH") + os.enviro
我正在使用 marshmallow 2.0.0rc2 验证 HTTP 请求的输入数据,并在 HTTP 响应上将 SQLAlchemy 模型加载到 JSON。我偶然发现了两个问题: 首先,在通过 HTT
我想将我设置为 None 的变量与 is 进行比较,但它失败了。 当我使用 == 将此变量与 None 进行比较时,它起作用了。 这就是我所说的变量: print type(xml.a) -> 因为
我最近遇到了这种语法,我不知道有什么区别。 如果有人能告诉我其中的区别,我将不胜感激。 最佳答案 答案解释here . 引用: A class is free to implement compari
尝试使用 BorutaPy 进行特征选择。但出现 TypeError: '(slice(None, None, None), array([0, 1, 2, 3, 4]))' 是无效键。 from s
我见过使用 [] 的代码片段, [None] , None或 ()作为 placeholder 的形状, 那是 x = tf.placeholder(..., shape=[], ...) y = t
是否有逻辑推理可以解释为什么下面的 Ansible playbook 中的两个 debug 任务分别输出 "NONE" 和 "FALSE"并且不是两者都“NONE”? - hosts: 'all'
我有一个函数,它可以返回两个整数的元组或(None, None)的元组: (出于本问题的目的,我们假设此返回格式是执行此操作的唯一方法,并且无法更改) from typing import Tuple
问题: 如何遍历字典并从中删除 None 键或值? 这是我尝试过的: 代码: import copy def _ignore(data): copied_data = copy.deepcop
什么是简洁的 python 表达方式 if : # do a bunch of stuff once 最佳答案 为什么不简单, None not in lst 关于python - 简明地说 "
我是一名优秀的程序员,十分优秀!