ValueError: Shapes (None, 200, 3) and (1, 3) are incompatible - keras

This is the model that I am trying to train for identifying possible tag(out of three tags) for each word, also I have added a layer from another model whose output shape is [1, 100]tensors and then I have concatenate it with BiLSTM output-
input1_entity = Input(shape = (200,))
last_hidden_layer_output = last_hidden_layer(tensorflow.reshape(input1_entity, [1, 200]))
embedding_entity = Embedding((4817), 200, input_length = 200, weights = [embedding_matrix], trainable = False)(input1_entity)
bilstm1_entity = Bidirectional(LSTM(100, return_sequences = True, recurrent_dropout = 0.2), merge_mode = 'concat')(embedding_entity)
lstm1_entity = Bidirectional(LSTM(100, return_sequences = True, dropout = 0.5, recurrent_dropout = 0.2))(bilstm1_entity)
lstm2_entity = Bidirectional(LSTM(50))(lstm1_entity)
merge_layer = concatenate([lstm2_entity, last_hidden_layer_output])
dense1_entity = Dense(128, activation = 'relu')(merge_layer)
dense2_entity = Dense(128, activation = 'relu')(dense1_entity)
dropout1_entity = Dropout(0.5)(dense2_entity)
dense3_entity = Dense(64, activation = 'tanh')(dropout1_entity)
output1_entity = Dense(3, activation = 'softmax')(dense3_entity)
model_entity = Model(inputs = input1_entity, outputs = output1_entity)
model_entity.compile(
loss = 'categorical_crossentropy',
optimizer = 'adam',
metrics = [tensorflow.keras.metrics.CategoricalAccuracy()],
sample_weight_mode = 'temporal'
)
And this is how I am training the model -
history = model_entity.fit(pad_tokens_train,
np.array(pad_tags_train),
batch_size=250,
verbose=1,
epochs=50,
sample_weight = sample_weight,
validation_split=0.2)
But I keep on getting this error -
ValueError: in user code:
File "/Users/kawaii/miniforge3/envs/tensor_no_gpu/lib/python3.8/site-packages/keras/engine/training.py", line 878, in train_function *
return step_function(self, iterator)
File "/Users/kawaii/miniforge3/envs/tensor_no_gpu/lib/python3.8/site-packages/keras/engine/training.py", line 867, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/Users/kawaii/miniforge3/envs/tensor_no_gpu/lib/python3.8/site-packages/keras/engine/training.py", line 860, in run_step **
outputs = model.train_step(data)
File "/Users/kawaii/miniforge3/envs/tensor_no_gpu/lib/python3.8/site-packages/keras/engine/training.py", line 809, in train_step
loss = self.compiled_loss(
File "/Users/kawaii/miniforge3/envs/tensor_no_gpu/lib/python3.8/site-packages/keras/engine/compile_utils.py", line 201, in __call__
loss_value = loss_obj(y_t, y_p, sample_weight=sw)
File "/Users/kawaii/miniforge3/envs/tensor_no_gpu/lib/python3.8/site-packages/keras/losses.py", line 141, in __call__
losses = call_fn(y_true, y_pred)
File "/Users/kawaii/miniforge3/envs/tensor_no_gpu/lib/python3.8/site-packages/keras/losses.py", line 245, in call **
return ag_fn(y_true, y_pred, **self._fn_kwargs)
File "/Users/kawaii/miniforge3/envs/tensor_no_gpu/lib/python3.8/site-packages/keras/losses.py", line 1664, in categorical_crossentropy
return backend.categorical_crossentropy(
File "/Users/kawaii/miniforge3/envs/tensor_no_gpu/lib/python3.8/site-packages/keras/backend.py", line 4994, in categorical_crossentropy
target.shape.assert_is_compatible_with(output.shape)
ValueError: Shapes (None, 200, 3) and (1, 3) are incompatible

Related

Problem using tf.keras.utils.timeseries_dataset_from_array in Functional Keras API

I am working on building a LSTM model on M5 Forecasting Challenge (a Kaggle dataset)
I using functional keras API to build my model. I have attached picture of my model. Input is generated using 'tf.keras.utils.timeseries_dataset_from_array' and the error I receive is
ValueError: Layer "model_4" expects 18 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, None, 18) dtype=float32>]
This is the code I am using to generate a time series dataset.
dataset = tf.keras.utils.timeseries_dataset_from_array(data=array, targets=None,
sequence_length=window, sequence_stride=1, batch_size=32)
My NN model
input_tensors = {}
for col in train_sel.columns:
if col in cat_cols:
input_tensors[col] = layers.Input(name = col, shape=(1,),dtype=tf.string)
else:
input_tensors[col]=layers.Input(name = col, shape=(1,), dtype = tf.float16
embedding = []
for feature in input_tensors:
if feature in cat_cols:
embed = layers.Embedding(input_dim = train_sel[feature].nunique(), output_dim = int(math.sqrt(train_sel[feature].nunique())))
embed = embed(input_tensors[feature])
else:
embed = layers.BatchNormalization()
embed = embed(tf.expand_dims(input_tensors[feature], -1))
embedding.append(embed)
temp = embedding
embedding = layers.concatenate(inputs = embedding)
nn_model = layers.LSTM(128)(embedding)
nn_model = layers.Dropout(0.1)(nn_model)
output = layers.Dense(1, activation = 'tanh')(nn_model)
model = tf.keras.Model(inputs=split_input,outputs = output)
Presently, I am fitting the model using
model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),
loss=tf.keras.losses.MeanSquaredError(),
metrics=[tf.keras.losses.MeanSquaredError()])
model.fit(dataset,epochs = 5)
I am receiving a value error
ValueError: in user code:
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1051, in train_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1040, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1030, in run_step **
outputs = model.train_step(data)
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 889, in train_step
y_pred = self(x, training=True)
File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.8/dist-packages/keras/engine/input_spec.py", line 200, in assert_input_compatibility
raise ValueError(f'Layer "{layer_name}" expects {len(input_spec)} input(s),'
ValueError: Layer "model_4" expects 18 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, None, 18) dtype=float32>]

Shapes are incompatible for multi class classifier

I have a multi-class classifier, that takes inputs from a generator:
def generate_train_data(path, x_shape):
genres = {"hip-hop":0, "r&b":1, "pop":2, "jazz":3}
genre_labels = to_categorical(list(genres.values()), num_classes=len(genres))
# some processing to create variables x and genre...
# (mock values)
x = np.zeros(x_shape)
x = x[None, :, :, :]
genre = "hip-hop"
yield (x, genre_labels[genres[genre]])
The classifier is defined below:
input_shape = (96, 84, 5)
i = Input(shape=input_shape, name='encoder_input')
cx = Conv2D(filters=8, kernel_size=3, strides=2, padding='same', activation='relu')(i)
cx = BatchNormalization()(cx)
cx = Conv2D(filters=16, kernel_size=3, strides=2, padding='same', activation='relu')(cx)
cx = BatchNormalization()(cx)
x = Flatten()(cx)
x = Dense(20, activation='relu')(x)
x = BatchNormalization()(x)
x = Dense(4, activation='softmax')(x)
classifier = Model(i, x, name='genre_classifier')
classifier.summary()
classifier.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
However, when I try to fit the classifier:
classifier.fit(generate_train_data(path, input_shape), epochs=30, validation_data=generate_test_data(path, input_shape), verbose=verbosity)
I get the following error:
ValueError: in user code:
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:806 train_function *
return step_function(self, iterator)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:796 step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
/usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:1211 run
return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2585 call_for_each_replica
return self._call_for_each_replica(fn, args, kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2945 _call_for_each_replica
return fn(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:789 run_step **
outputs = model.train_step(data)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:749 train_step
y, y_pred, sample_weight, regularization_losses=self.losses)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/compile_utils.py:204 __call__
loss_value = loss_obj(y_t, y_p, sample_weight=sw)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:149 __call__
losses = ag_call(y_true, y_pred)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:253 call **
return ag_fn(y_true, y_pred, **self._fn_kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:1535 categorical_crossentropy
return K.categorical_crossentropy(y_true, y_pred, from_logits=from_logits)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:201 wrapper
return target(*args, **kwargs)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/backend.py:4687 categorical_crossentropy
target.shape.assert_is_compatible_with(output.shape)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/tensor_shape.py:1134 assert_is_compatible_with
raise ValueError("Shapes %s and %s are incompatible" % (self, other))
ValueError: Shapes (None, 1) and (None, 4) are incompatible
The class label value returned by the generators is an array of length 4 so why is keras suggesting it is of size 1?
NOTE: This code is being run on Colab, tensorflow version 2.3. A mock version that reprocuces this error can be found on this Colab link: https://colab.research.google.com/drive/1SQZFspj3UOwP2ApIiaI2lvB2Z59bdVOk?usp=sharing
EDIT: added mock values in generate_train_data so that code can be reproducible
You need to add a dimension for batch_size for both x and y. In your generator, add a None-dimension by changing: genre_labels[genres[genre]] to genre_labels[genres[genre]][None, :].
The ouput of the one-hot encoding needed to be packed into a small 1 batch to fit [None,4] this is done by np.asarray([]).
Use
yield (x, np.asarray([genre_labels[genres[genre], :]]))
instead of:
yield (x, genre_labels[genres[genre]])

ValueError: Graph disconnected in vgg16

Traceback:
model = Model(input_tensor,x,name = 'vgg16_trunk')
File "/usr/local/lib/python3.6/dist-packages/keras/legacy/interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/network.py", line 93, in __init__
self._init_graph_network(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/network.py", line 231, in _init_graph_network
self.inputs, self.outputs)
File "/usr/local/lib/python3.6/dist-packages/keras/engine/network.py", line 1443, in _map_graph_network
str(layers_with_complete_input))
ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_2:0", shape=(?, 32, 32, 3), dtype=float32) at layer "input_2". The following previous layers were accessed without issue: []
How to solve this problem in vgg16 ??
def create_model(input_shape):
channel_axis = 1 if K.image_data_format() == "channels_first" else -1
input_tensor = Input(shape=input_shape)
base_model = VGG16(classes=10,input_tensor=None,input_shape=input_shape,include_top=False)
x = base_model.output
x = BatchNormalization(axis=channel_axis, momentum=mom,
epsilon=eps, gamma_initializer=gamma)(x)
x = LeakyReLU(leakiness)(x)
model = Model(input_tensor,x,name = 'vgg16_trunk')
return model
Pass the input_tensor you created here:
input_tensor = Input(shape=input_shape)
where base_model is created:
base_model = VGG16(classes=10,input_tensor=input_tensor,include_top=False)
Please note also, that the tensor will already have the input_shape so it's not necessary to give it as parameter again when creating the base_model.

How to customize a loss function with a trainable parameter?

I want to customize the following loss function with a training parameter, where λ is the regularization term and w is a trainable parameter. I customize the loss layer and add the loss into my model. But, it occurs the following errors. I don't know where the wrong is and whether my this custom loss layer is right?
Loss function = binary_crossentropy(y_true, y_pred) + λ|w|
1.I customize a loss layer.
class BCLoss(Layer):
def __init__(self,gamma_init='zero',lamada = 0.00005,**kwargs):
self.gamma_init = initializations.get(gamma_init)
self.lamada = lamada
super(BCLoss, self).__init__(**kwargs)
def build(self, input_shape):
self.gamma_init = self.add_weight(name='gamma',
shape=(1,),
initializer='uniform',
trainable=True)
super(BCLoss,self).build(input_shape)
def call(self, inputs, **kwargs):
y_true, y_pred = inputs
loss = K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1) + self.lamada* K.abs(self.gamma_init)
return loss
def compute_output_shape(self, input_shape):
return input_shape
2.Training the model
def build_model(self):
img_input = layers.Input(shape=self.input_shape, name='img_input')
y_true = layers.Input(shape=(1,),name='y_true')
nb_channels = self.growth_rate
# Initial convolution layer
layer_1 = layers.Convolution2D(2 * self.growth_rate, (1, 1), strides=(2, 2),
kernel_regularizer=keras.regularizers.l2(self.weight_decay))(img_input)
average_1 = layers.AveragePooling2D((2, 2), strides=(4, 4))(layer_1)
x = layers.BatchNormalization()(layer_1)
x = layers.Activation('relu')(x)
x = layers.MaxPooling2D()(x)
# Building dense blocks
skip_layer = [average_1]
for block in range(self.dense_blocks - 1):
# Add dense block
x, nb_channels = self.dense_block(x, self.dense_layers[block], nb_channels, self.growth_rate,
self.dropout_rate, self.bottleneck, self.weight_decay)
# Add transition_block
x_left,x_right = self.transition_layer(x, nb_channels, self.dropout_rate, self.compression, self.weight_decay)
x = x_left
nb_channels = int(nb_channels * self.compression)
skip_layer.append(x_right)
# Add last dense block without transition but for that with global average pooling
x, nb_channels = self.dense_block(x, self.dense_layers[-1], nb_channels,
self.growth_rate, self.dropout_rate, self.weight_decay,skip_layer =skip_layer)
x = layers.BatchNormalization()(x)
x = layers.Activation('relu')(x)
x = layers.GlobalAveragePooling2D()(x)
x = layers.Dropout(0.2)(x)
y_pred = layers.Dense(self.nb_classes, activation='sigmoid')(x)
model = keras.Model(inputs=[img_input,y_true], outputs=y_pred, name='densenet')
loss = BCLoss()([y_true,y_pred])
model.add_loss(loss)
return model
3.compile model
model.compile(loss=None, optimizer=Adam(lr=0.001), metrics=['accuracy'])
4. The error
Traceback (most recent call last):
File "G:/Workspace/workspace_python/Lung_EGRF/train.py", line 109, in <module>
train_model(config['training_data'],config['testing_data'], config['model_file'],config['input_shape'])
File "G:/Workspace/workspace_python/Lung_EGRF/train.py", line 97, in train_model
early_stopping_patience=50))
File "D:\Anaconda3\envs\py36\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "D:\Anaconda3\envs\py36\lib\site-packages\keras\engine\training.py", line 1418, in fit_generator
initial_epoch=initial_epoch)
File "D:\Anaconda3\envs\py36\lib\site-packages\keras\engine\training_generator.py", line 217, in fit_generator
class_weight=class_weight)
File "D:\Anaconda3\envs\py36\lib\site-packages\keras\engine\training.py", line 1211, in train_on_batch
class_weight=class_weight)
File "D:\Anaconda3\envs\py36\lib\site-packages\keras\engine\training.py", line 789, in _standardize_user_data
exception_prefix='target')
File "D:\Anaconda3\envs\py36\lib\site-packages\keras\engine\training_utils.py", line 63, in standardize_input_data
'expected no data, but got:', data)
ValueError: ('Error when checking model target: expected no data, but got:',
array([0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0,
1, 0, 1, 1, 1, 1, 1, 1, 0, 1], dtype=int64))
Process finished with exit code 1

ValueError: Dimension 2 in both shapes must be equal, but are 3 and 32

I am currently studying Tensorflow. I used a pre-trained model for prediction through the Django app, But during the prediction, I got the error, Please help me to resolve the error.
def alpha_to_color(image, color=(255, 255, 255)):
x = np.array(image)
r, g, b, a = np.rollaxis(x, axis=-1)
r[a == 0] = color[0]
g[a == 0] = color[1]
b[a == 0] = color[2]
x = np.dstack([r, g, b, a])
return Image.fromarray(x, 'RGBA')
def preprocess(data):
# dimensions of our images.
img_width, img_height = 250, 250
dataUrlPattern = re.compile('data:image/(png|jpeg);base64,(.*)$')
imgb64 = dataUrlPattern.match(data).group(2)
if imgb64 is not None and len(imgb64) > 0:
data= base64.b64decode(imgb64)
im1 = Image.open(BytesIO(data))
im1 = alpha_to_color(im1)
im1=im1.convert('RGB')
im1= im1.resize((250,250))
print("[INFO] loading and preprocessing image...")
image = img_to_array(im1)
image = image.reshape((1,) + image.shape) # this is a Numpy array with shape (1, 3, 250,250)
test_ob = ImageDataGenerator(rescale=1./255)
X=[]
for batch in test_ob.flow(image, batch_size=1):
X= batch
break
return X
def build_model():
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(250, 250, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(64))
model.add(Activation('relu'))
#model.add(Dropout(0.5))
model.add(Dense(250))
model.add(Activation('sigmoid'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
module_dir = os.path.dirname(__file__) # get current directory
file_path = os.path.join(module_dir, 'bestWeight.hdf5')
model.load_weights(file_path)
return model
def load_labels():
module_dir = os.path.dirname(__file__) # get current directory
file_path = os.path.join(module_dir, 'labels.csv')
df = pd.read_csv(file_path,
header=0)
target_names = df['Category'].tolist()
return target_names
def predict_labels(data):
model = build_model()
image = preprocess(data)
target_names = load_labels()
encoder = LabelEncoder()
encoder.fit(target_names)
pL = model.predict(image)
prob = model.predict_proba(image)
p= np.argsort(pL, axis=1)
n1 = (p[:,-4:]) #gives top 5 labels
pL_names = (encoder.inverse_transform(n1))
pL_names = pL_names[0]
p= np.sort(prob, axis=1)
convertperc = [stats.percentileofscore(p[0], a, 'rank') for a in p[0]]
n = (convertperc[-4:]) #gives top 5 probabilities perc
prob_values = (p[:,-4:])
prob_single_values = prob_values[0]
return zip(pL_names,n,prob_single_values)
The code give this error
ValueError: Dimension 2 in both shapes must be equal, but are 3 and 32. Shapes are [3,3,3,32] and [3,3,32,3]. for 'Assign' (op: 'Assign') with input shapes: [3,3,3,32], [3,3,32,3].
This error occurs when running the line for cross_entropy. I don't understand why this is happing, if you need any more information I would be happy to give it to you.
Here is my compilation log
Traceback (most recent call last):
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1576, in _create_c_op
c_op = c_api.TF_FinishOperation(op_desc)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Dimension 2 in both shapes must be equal, but are 3 and 32. Shapes are [3,3,3,32] and [3,3,32,3]. for 'Assign' (op: 'Assign') with input shapes: [3,3,3,32], [3,3,32,3].
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\RAHKARP\Desktop\webApplication\sketchPad\views.py", line 148, in recognizeSketch
result = predict_labels(data)
File "C:\Users\RAHKARP\Desktop\webApplication\sketchPad\views.py", line 113, in predict_labels
model = build_model()
File "C:\Users\RAHKARP\Desktop\webApplication\sketchPad\views.py", line 99, in build_model
model.load_weights(file_path)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\keras\engine\network.py", line 1161, in load_weights
f, self.layers, reshape=reshape)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\keras\engine\saving.py", line 928, in load_weights_from_hdf5_group
K.batch_set_value(weight_value_tuples)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 2435, in batch_set_value
assign_op = x.assign(assign_placeholder)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\tensorflow\python\ops\variables.py", line 645, in assign
return state_ops.assign(self._variable, value, use_locking=use_locking)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\tensorflow\python\ops\state_ops.py", line 216, in assign
validate_shape=validate_shape)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_state_ops.py", line 63, in assign
use_locking=use_locking, name=name)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\tensorflow\python\util\deprecation.py", line 454, in new_func
return func(*args, **kwargs)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 3155, in create_op
op_def=op_def)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1731, in __init__
control_input_ops)
File "C:\Users\RAHKARP\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1579, in _create_c_op
raise ValueError(str(e))
ValueError: Dimension 2 in both shapes must be equal, but are 3 and 32. Shapes are [3,3,3,32] and [3,3,32,3]. for 'Assign' (op: 'Assign') with input shapes: [3,3,3,32], [3,3,32,3].
Can you send a minimal example of your code with error which can be executed on our side? It would be very helpful. I suppose that error is in wrong channel order. You generate batch with following shape:
image = image.reshape((1,) + image.shape) # shape = (1, 3, 250,250)
In keras channels should be a last dimension: (1, 250, 250, 3)

Resources