先看实验代码:
import numpy as np
from keras.models import Sequential
from keras.layers import Reshape
def GetModel():
model = Sequential()
model.add(Reshape( (-1,), input_shape=(2,3,4)))
return model
if __name__ == "__main__":
r=np.random.randint(0,100,size=(2,3,4))
reshape_size = (-1,4)
r2=r.reshape(reshape_size,order='C')
r3 = r.reshape( (-1) )
print("r",r)
print("*************************")
print("r2",r2)
print("*************************")
print("r3",r3)
my_input = np.expand_dims(r,axis=0)
model = GetModel()
result = model.predict(my_input)
print("*************************")
print("result",result)
结果:
r [[[22 96 4 45]
[38 39 12 82]
[45 47 73 24]]
[[18 95 26 84]
[44 44 71 60]
[47 19 20 77]]]
*************************
r2 [[22 96 4 45]
[38 39 12 82]
[45 47 73 24]
[18 95 26 84]
[44 44 71 60]
[47 19 20 77]]
*************************
r3 [22 96 4 45 38 39 12 82 45 47 73 24 18 95 26 84 44 44 71 60 47 19 20 77]
*************************
result [[22. 96. 4. 45. 38. 39. 12. 82. 45. 47. 73. 24. 18. 95. 26. 84. 44. 44. 71. 60. 47. 19. 20. 77.]]
在结合这篇文章:https://blog.csdn.net/zhanggonglalala/article/details/79356653
简单来说,默认的order='C',也就是后面的维度变化快,前面的维度变化最慢,按照这个顺序去reshape
再附上一个实验代码:
import os
import tensorflow as tf
from keras.models import Model
from keras.optimizers import SGD,Adam
from keras.callbacks import ModelCheckpoint,TensorBoard
from keras.layers import *
from keras import backend as K
from keras.layers.normalization import BatchNormalization
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from keras.utils import plot_model
def GetModel():
inputs = Input(shape=(3,3,2))
nets = Reshape(target_shape=(-1,1) )(inputs)
model = Model(inputs=inputs,outputs=nets)
return model
if __name__ == "__main__":
model = GetModel()
mat = np.random.randint(1,100,size=(3,3,2))
print(mat)
print("mat shape:",mat.shape)
print(mat[0,1,:])
mat = np.asarray(mat)
mat = np.expand_dims(mat,axis=0)
print('(*******************)')
predict = model.predict(mat)
print(predict)
print('predict shape',predict.shape)
-----------------------------------------------------------------
-----------------------------------------------------------------
Result:
[[[ 5 27]
[62 98]
[10 70]]
[[15 54]
[48 93]
[10 64]]
[[24 12]
[61 99]
[53 57]]]
mat shape: (3, 3, 2)
[62 98]
(*******************)
[[[ 5.]
[27.]
[62.]
[98.]
[10.]
[70.]
[15.]
[54.]
[48.]
[93.]
[10.]
[64.]
[24.]
[12.]
[61.]
[99.]
[53.]
[57.]]]
predict shape (1, 18, 1)