I'm trying to plot different paths at rviz
I'm using the following code to get a first approach (based on this repository: https://github.com/HaoQChen/show_trajectory/tree/master/src)
import rospy
import math
import numpy as np
from geometry_msgs.msg import PoseStamped
from nav_msgs.msg import Path, Odometry
from std_msgs.msg import Empty
class ProjectElement(object):
def __init__(self):
self.path_pub = rospy.Publisher('~path', Path, latch=True, queue_size=10)
self.circle_sub = rospy.Subscriber('~circle', Empty, self.circle_cb, queue_size=10)
self.line_sub = rospy.Subscriber('~line', Empty, self.line_cb, queue_size=10)
self.project_sub = rospy.Subscriber('~project', Empty, self.project_cb, queue_size=10)
self.paths = []
self.rate = rospy.Rate(50)
def circle_cb(self, msg):
path = Path()
centre_x = 1
centre_y = 1
R = 0.5
th = 0.0
delta_th = 0.1
while (th<2*math.pi):
x = centre_x + R * math.sin(th)
y = centre_y + R * math.cos(th)
th += delta_th
this_pose_stamped = PoseStamped()
this_pose_stamped.pose.position.x = x
this_pose_stamped.pose.position.y = y
this_pose_stamped.header.stamp = rospy.get_rostime()
this_pose_stamped.header.frame_id = "/my_cs"
path.poses.append(this_pose_stamped)
path.header.frame_id = "/my_cs"
path.header.stamp = rospy.get_rostime()
self.paths.append(path)
def line_cb(self, msg):
path = Path()
x_start = 0.0
y_start = 0.0
length = 2
angle = 45 * math.pi/180
th = 0.0
delta_th = 0.1
while (th<length):
x = x_start + th * math.cos(angle)
y = y_start + th * math.sin(angle)
th += delta_th
this_pose_stamped = PoseStamped()
this_pose_stamped.pose.position.x = x
this_pose_stamped.pose.position.y = y
this_pose_stamped.header.stamp = rospy.get_rostime()
this_pose_stamped.header.frame_id = "/my_cs"
path.poses.append(this_pose_stamped)
path.header.frame_id = "/my_cs"
path.header.stamp = rospy.get_rostime()
self.paths.append(path)
def project_cb(self, msg):
while(True):
for element in self.paths:
# element.header.stamp = rospy.get_rostime()
self.path_pub.publish(element)
if __name__ == '__main__':
rospy.init_node('path_simulate')
elements = ProjectElement()
rospy.spin()
I can visualize the paths at rviz, but I don't know how to plot both figures at the same time in this way.
line
circle
I would like to ask if this approach is the best way to address this issue or which could be the best way.
I finally solved with visualization_msgs/MarkerArray based on this question:
https://answers.ros.org/question/220898/how-to-use-rviz-to-show-multiple-planing-paths/?answer=220993#post-id-220993
I post the code used here in case anyone needs it
import rospy
import math
import numpy as np
from geometry_msgs.msg import Vector3, Point
from std_msgs.msg import Empty
from visualization_msgs.msg import Marker, MarkerArray
class ProjectElement(object):
def __init__(self):
self.marker_pub = rospy.Publisher('~marker', MarkerArray, latch=True, queue_size=10)
self.circle_sub = rospy.Subscriber('~circle', Empty, self.circle_cb, queue_size=10)
self.line_sub = rospy.Subscriber('~line', Empty, self.line_cb, queue_size=10)
self.project_sub = rospy.Subscriber('~project', Empty, self.project_cb, queue_size=10)
self.marker_array = MarkerArray()
def circle_cb(self, msg):
marker = Marker()
marker.type = Marker.LINE_STRIP
marker.action = Marker.ADD
marker.scale = Vector3(0.01, 0.01, 0)
marker.color.g = 1.0
marker.color.a = 1.0
centre_x = 1
centre_y = 1
R = 0.5
delta_th = 0.1
for th in np.arange(0.0, 2*math.pi+delta_th, delta_th):
x = centre_x + R * math.sin(th)
y = centre_y + R * math.cos(th)
point = Point()
point.x = x
point.y = y
marker.points.append(point)
marker.id = 0
marker.header.stamp = rospy.get_rostime()
marker.header.frame_id = "/my_cs"
self.marker_array.markers.append(marker)
def line_cb(self, msg):
marker = Marker()
marker.type = Marker.LINE_STRIP
marker.action = Marker.ADD
marker.scale = Vector3(0.01, 0.01, 0)
marker.color.g = 1.0
marker.color.a = 1.0
x_start = 0.0
y_start = 0.0
length = 2
angle = 45 * math.pi/180
delta_th = 0.1
for th in np.arange(0.0, length, delta_th):
x = x_start + th * math.cos(angle)
y = y_start + th * math.sin(angle)
point = Point()
point.x = x
point.y = y
marker.points.append(point)
marker.id = 1
marker.header.stamp = rospy.get_rostime()
marker.header.frame_id = "/my_cs"
self.marker_array.markers.append(marker)
def project_cb(self, msg):
self.marker_pub.publish(self.marker_array)
if __name__ == '__main__':
rospy.init_node('markers_simulate')
elements = ProjectElement()
rospy.spin()
And the result achieved
marker array display
Related
I would like to re-create the following keras model in PyTorch.
vocab_size = 22
maxlen = 200
embed_dim = 256
num_heads = 2
feed_forward_dim = 256
batch_size = 128
decoders = 5
def create_model():
inputs = layers.Input(shape=(maxlen,), dtype=tf.int32)
embedding_layer = TokenAndPositionEmbedding(maxlen, vocab_size, embed_dim)
x = embedding_layer(inputs)
decoder_blocks = []
for i in range(decoders):
decoder_blocks.append(DecoderBlock(embed_dim, num_heads, feed_forward_dim))
for i in range(len(decoder_blocks)):
x = decoder_blocks[i](x)
outputs = layers.Dense(vocab_size)(x)
model = keras.Model(inputs=inputs, outputs=[outputs, x])
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=lr_schedule),
loss=[loss_fn, None],
)
return model
model = create_model()
Here are the Decoder and the TokenAndPositionEmbedding layers along with the Causal Attention Mask
def causal_attention_mask(batch_size, n_dest, n_src, dtype):
i = tf.range(n_dest)[:, None]
j = tf.range(n_src)
m = i >= j - n_src + n_dest
mask = tf.cast(m, dtype)
mask = tf.reshape(mask, [1, n_dest, n_src])
mult = tf.concat(
[tf.expand_dims(batch_size, -1), tf.constant([1, 1], dtype=tf.int32)], 0
)
return tf.tile(mask, mult)
class DecoderBlock(layers.Layer):
def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):
super(DecoderBlock, self).__init__()
self.att = layers.MultiHeadAttention(num_heads, embed_dim)
self.ffn = keras.Sequential(
[layers.Dense(ff_dim, activation="relu"), layers.Dense(embed_dim),]
)
self.layernorm1 = layers.LayerNormalization(epsilon=1e-6)
self.layernorm2 = layers.LayerNormalization(epsilon=1e-6)
self.dropout1 = layers.Dropout(rate)
self.dropout2 = layers.Dropout(rate)
def call(self, inputs):
input_shape = tf.shape(inputs)
batch_size = input_shape[0]
seq_len = input_shape[1]
causal_mask = causal_attention_mask(batch_size, seq_len, seq_len, tf.bool)
attention_output = self.att(inputs, inputs, attention_mask=causal_mask)
attention_output = self.dropout1(attention_output)
out1 = self.layernorm1(inputs + attention_output)
ffn_output = self.ffn(out1)
ffn_output = self.dropout2(ffn_output)
return self.layernorm2(out1 + ffn_output)
class TokenAndPositionEmbedding(layers.Layer):
def __init__(self, maxlen, vocab_size, embed_dim):
super(TokenAndPositionEmbedding, self).__init__()
self.token_emb = layers.Embedding(input_dim=vocab_size, output_dim=embed_dim)
self.pos_emb = layers.Embedding(input_dim=maxlen, output_dim=embed_dim)
def call(self, x):
maxlen = tf.shape(x)[-1]
positions = tf.range(start=0, limit=maxlen, delta=1)
positions = self.pos_emb(positions)
x = self.token_emb(x)
return x + positions
For reference, this code is copied directly from: https://keras.io/examples/generative/text_generation_with_miniature_gpt/
I have tried to create equivalent architecture in PyTorch using nn.TransformerDecoderLayer. Apologies for not including my own code, but I have been completely unsuccessful.
The code is as follows:
src = np.float32([[506,210],[1268,206],[1366,450],[ 258,460]])
dst = np.float32([[258, 210], [1366, 210], [1366, 460], [258, 460]])
dst = np.array(dst,dtype = 'float64')
src = np.array(src,dtype = 'float64')
matrix = cv2.getPerspectiveTransform(np.float32(src), np.float32(dst))
p = (506,210)
px = (matrix[0][0]*p[0] + matrix[0][1]*p[1] + matrix[0][2]) / ((matrix[2][0]*p[0] + matrix[2][1]*p[1] + matrix[2][2]))
py = (matrix[1][0]*p[0] + matrix[1][1]*p[1] + matrix[1][2]) / ((matrix[2][0]*p[0] + matrix[2][1]*p[1] + matrix[2][2]))
print(px,py)
s1 = np.array([[506,210,1]])
s11 = s1[:,:2]
print(s11)
print(np.dot(s1,matrix))
s2 = np.dot(s1,matrix)
s22 = s2[:,:2]
poly1 = Polygon(dst)
poly2 = Polygon(src)
ax = plt.gca()
ax.xaxis.set_ticks_position('top')
ax.invert_yaxis()
plt.plot(*poly1.exterior.xy)
plt.plot(*poly2.exterior.xy)
plt.plot([s11[0][0],ss1],[s11[0][1],ss2],'o')
plt.show()
The corresponding point of correct output should be at point 1, but the actual output is at point 2
I am trying to train an adversarial patch located at the bottom left corner of the image to cause a misclassification. Currently, I am using these parameters to normalize the CIFAR10 dataset.
transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.4914,0.4822,0.4465),(0.2023,0.1994,0.201))]
This would result in the images having a maximum and minimum value of around 2.55 and -2.55 respectively. However, I'm not sure how to work with this range when training my patch. I struggle between converting the patch from a range of (0,1) to (-2.55,2.55). Any help is appreciated!
My code for training is below: (I don't think its training properly for now)
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
import matplotlib.pyplot as plt
import numpy as np
from torch.autograd import Variable
import torchattacks
import random
import torch.nn.functional as F
dictionary ={
'0':'airplane',
'1':'automobile',
'2':'bird',
'3':'cat',
'4':'deer',
'5':'dog',
'6':'frog',
'7':'horse',
'8':'ship',
'9':'truck',
}
transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.4914,0.4822,0.4465),(0.2023,0.1994,0.201))])
#transform1 = transforms.Compose([transforms.ToTensor()])
normalize = transforms.Normalize((0.4914,0.4822,0.4465),(0.2023,0.1994,0.201))
mean =(0.4914,0.4822,0.4465)
std =(0.2023,0.1994,0.201)
inv_normalize = transforms.Normalize(
mean=[-0.4914/0.2023, -0.4822/0.1994, -0.4465/0.201],
std=[1/0.2023, 1/0.1994, 1/0.201])
batch_size = 1
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
shuffle=False, num_workers=2)
testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=batch_size,
shuffle=True, num_workers=2)
model = torch.hub.load("chenyaofo/pytorch-cifar-models", "cifar10_resnet20", pretrained=True)
model = model.cuda()
import os
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
patch = np.random.rand(3,32,32)
model.eval()
def mask_generation(mask_type='rectangle', patch = patch, image_size=(3, 7, 7)):
applied_patch = np.zeros(image_size) #0,1
#patch = torch.tensor(patch)
#padding = (3,3,3,3)
#patch = F.pad(patch, padding)
if mask_type == 'rectangle':
rotation_angle = 0
for i in range(patch.shape[0]):
patch[i] = np.rot90(patch[i], rotation_angle)
x_location , y_location = 25,0
for i in range(patch.shape[0]):
applied_patch[:, x_location:x_location + patch.shape[1], y_location:y_location + patch.shape[2]] = patch
mask = applied_patch.copy()
mask[mask != 0] = 1.0
return patch , applied_patch, mask, x_location, y_location , rotation_angle
def patch_attack(image, applied_patch, mask, target, probability_threshold, model, lr, max_iteration):
applied_patch = torch.from_numpy(applied_patch)
mask = torch.from_numpy(mask)
image = inv_normalize(image)
target_probability, count = 0,0
perturbated_image = torch.mul(mask.type(torch.FloatTensor), applied_patch.type(torch.FloatTensor)) + torch.mul((1 - mask.type(torch.FloatTensor)), image.type(torch.FloatTensor))
perturbated_image = normalize(perturbated_image)
while target_probability < probability_threshold and count < max_iteration:
count += 1
# Optimize the patch
perturbated_image = Variable(perturbated_image.data, requires_grad=True)
per_image = perturbated_image.cuda()
output = model(per_image)
target_log_softmax = torch.nn.functional.log_softmax(output, dim=1)[0][target]
target_log_softmax.backward()
patch_grad = perturbated_image.grad.clone().cpu()
applied_patch = (lr * patch_grad) + applied_patch.type(torch.FloatTensor)
applied_patch = torch.clamp(applied_patch,0,1)
perturbated_image.grad.data.zero_()
# Test the patch
perturbated_image = torch.mul(mask.type(torch.FloatTensor), applied_patch.type(torch.FloatTensor)) + torch.mul((1-mask.type(torch.FloatTensor)), image.type(torch.FloatTensor))
perturbated_image = normalize(perturbated_image)
perturbated_image = perturbated_image.cuda()
output = model(perturbated_image)
target_probability = torch.nn.functional.softmax(output, dim=1).data[0][target]
perturbated_image = perturbated_image.detach().cpu().numpy()
applied_patch = applied_patch.cpu().numpy()
return perturbated_image, applied_patch
def test_patch(patch_type, target, patch, test_loader, model):
test_total, test_actual_total, test_success = 0, 0, 0
for (image, label) in test_loader:
test_total += label.shape[0]
assert image.shape[0] == 1, 'Only one picture should be loaded each time.'
image = image.cuda() #-3,3
label = label.cuda()
output = model(image)
_, predicted = torch.max(output.data, 1)
if predicted[0] != label and predicted[0].data.cpu().numpy() != target:
test_actual_total += 1
patch ,applied_patch, mask, x_location, y_location = mask_generation('rectangle', patch, (3, 32, 32))
applied_patch = torch.from_numpy(applied_patch)
mask = torch.from_numpy(mask)
mask = normalize(mask)
applied_patch = normalize(applied_patch)
perturbated_image = torch.mul(mask.type(torch.FloatTensor), applied_patch.type(torch.FloatTensor)) + torch.mul((1 - mask.type(torch.FloatTensor)), image.type(torch.FloatTensor))
perturbated_image = perturbated_image.cuda() #-3,3
output = model(perturbated_image)
_, predicted = torch.max(output.data, 1)
if predicted[0].data.cpu().numpy() == target:
test_success += 1
return test_success / test_actual_total
#training parameters
epochs = 1
target = 0
probability_threshold = 0.99
lr = 1/255
max_iteration = 1
runs = 0
for epoch in range(epochs):
train_total, train_actual_total, train_success = 0, 0, 0
for (image, label) in trainloader:
runs+=1
assert image.shape[0] == 1
image = image.cuda()
label = label.cuda()
train_total += label.shape[0]
output = model(image)
_, predicted = torch.max(output.data, 1)
if predicted[0] != label or predicted[0].data.cpu().numpy() != target:
train_actual_total += 1
patch , applied_patch, mask, x_location, y_location ,rotation_angle = mask_generation('rectangle', patch, (3, 32, 32))
perturbated_image, applied_patch = patch_attack(image, applied_patch, mask, target, probability_threshold, model, lr,max_iteration)
perturbated_image = torch.from_numpy(perturbated_image).cuda()
output = model(perturbated_image)
_, predicted = torch.max(output.data, 1)
if predicted[0].data.cpu().numpy() == target:
train_success += 1
patch = applied_patch[0][:, x_location:x_location + patch.shape[1], y_location:y_location + patch.shape[2]]
patch = np.array(patch)
To convert a number x in the range [0,1] to the range [-2.55,2.55]:
Multiply by size of final range / size of original range or in this case 5.1/1.0.
Add min of final range - min of starting range to the result, so in this case -2.55+0 = 0.
if I insert an image of size (205,205) the algorithm compresses it very quickly. But if I insert a larger image, the algorithm takes a very long time to compress it.
my intention would be to optimize the code and consequently speed up the compression phase
do you have any suggestions?
library
from PIL import Image
import numpy as np
from cv2 import cv2
**function of compression**
def lz77Compress (image,sw,lab):
img = cv2.imread(image)
flat = np.array(img).flatten()
row = img.shape[0]
col = img.shape[1]
ch = img.shape[2]
tot = row * col * ch
slidingWindows = sw
lookAhead = lab
array of tuple and char
encodedTuple = np.array([], dtype=np.uint16)
encodedChar = np.array([], dtype=np.uint8)
**# Lunghezza del Search Buffer**
sbSize = slidingWindows - lookAhead
for it in range(sbSize):
encodedTuple = np.append(encodedTuple, (0, 0))
encodedChar = np.append(encodedChar, flat[it])
**# pointer in the Search Buffer**
sbPointer = 0
while sbPointer < tot :
max_match = 0
max_match_go_back = 0
selChar = sbPointer + sbSize
# corrispondenza del carattere in Sb da lookAd
encodeCharacters = flat[selChar]
**#sequenza vuota[]**
seqY = np.array([],dtype=np.int16)
for i in range(sbPointer,sbPointer + sbSize):
if(flat[i] == encodeCharacters):
seqY = np.append(seqY,i)
**check of corrispondence and insert in encodedtuple and encodedChar**
if(seqY.size == 0 ):
encodedTuple = np.append(encodedTuple,(0,0))
encodedChar = np.append (encodedChar,encodeCharacters)
else:
for j in seqY:
**size of corrisponddence**
matchLenght= 0
returnBack= selChar - j
it = 0
while selChar + it < tot :
if flat[it + j] == flat[selChar + it]:
matchLenght +=1
it +=1
**# if there is not corrispondence*
else:
break
if matchLenght>max_match:
max_match = matchLenght
returnBack= max_match_go_back
encodedTuple = np.append(encodedTuple,(max_match_go_back,max_match))
encodedChar = np.append(encodedChar,flat[selChar + max_match - 1])
sbPointer+= 1 +max_match
**save encoedTupe and encodedChar and image size for the compression**
np.save("encodedTuple", encodedTuple)
np.save("encodedChar", encodedChar)
print("File compresso in : Copressed.txt")
output = open("Compressed.txt","w+")
output.write(str(c))
I'm beginner in tensorflow and i'm working on a model which Colorize Greyscale images but when i run the optmizer it give the same Error (MSE) every epoch and i can't figure out what is the error, so what is wrong with my code , what am i missing?
The logic: I get the low level and global and mid level features from the image and pass the global Features to multilayer function and fuse it's output with the global part in a one fusion layer and send the fused features vector to the colorization network ,, and i have Get_images_chrominance function which get the a,b values from the labels images and store them to feed the lables with them.
The Code
Ab_values = None
Batch_size = 3
Batch_indx = 1
Batch_GreyImages = []
Batch_ColorImages = []
EpochsNum = 11
ExamplesNum = 9
Imgsize = 224, 224
Channels = 1
Input_images = tf.placeholder(dtype=tf.float32,shape=[None,224,224,1])
Ab_Labels_tensor = tf.placeholder(dtype=tf.float32,shape=[None,224,224,2])
def ReadNextBatch():
global Batch_GreyImages
global Batch_ColorImages
global Batch_indx
global Batch_size
global Ab_values
Batch_GreyImages = []
Batch_ColorImages = []
for ind in range(Batch_size):
Colored_img = Image.open(r'Path' + str(Batch_indx) + '.jpg')
Batch_ColorImages.append(Colored_img)
Grey_img = Image.open(r'Path' + str(Batch_indx) + '.jpg')
Grey_img = np.asanyarray(Grey_img)
img_shape = Grey_img.shape
img_reshaped = Grey_img.reshape(img_shape[0],img_shape[1], Channels)#[224,224,1]
Batch_GreyImages.append(img_reshaped)#[#imgs,224,224,1]
Batch_indx = Batch_indx + 1
Get_Images_Chrominance()
return Batch_GreyImages
#-------------------------------------------------------------------------------
def Get_Images_Chrominance():
global Ab_values
global Batch_ColorImages
Ab_values = np.empty((Batch_size,224,224,2),"float32")
for indx in range(Batch_size):
lab = color.rgb2lab(Batch_ColorImages[indx])
for i in range(len(lab[:,1,1])):
for j in range(len(lab[1,:,1])):
Ab_values[indx][i][j][0] = lab[i,j,1]
Ab_values[indx][i][j][1] = lab[i,j,2]
min_value = np.amin(Ab_values[indx])
max_value = np.amax(Ab_values[indx])
for i in range(len(lab[:,1,1])):
for j in range(len(lab[1,:,1])):
Ab_values[indx][i][j][0] = Normalize(lab[i,j,1],min_value,max_value)
Ab_values[indx][i][j][1] = Normalize(lab[i,j,1],min_value,max_value)
#-------------------------------------------------------------------------------
def Normalize(value,min_value,max_value):
min_norm_value = 0
max_norm_value = 1
value = min_norm_value + (((max_norm_value - min_norm_value) * (value - min_value)) / (max_value - min_value))
return value
def Frobenius_Norm(M):
return tf.reduce_sum(M ** 2) ** 0.5
def Model(Input_images):
low_layer1 = ConstructLayer(Input_images,1,3,3,64,2,'Relu')
low_layer2 = ConstructLayer(low_layer1,64,3,3,128,1,'Relu')
low_layer3 = ConstructLayer(low_layer2,128,3,3,128,2,'Relu')
low_layer4 = ConstructLayer(low_layer3,128,3,3,256,1,'Relu')
low_layer5 = ConstructLayer(low_layer4,256,3,3,256,2,'Relu')
low_layer6 = ConstructLayer(low_layer5,256,3,3,512,1,'Relu')
mid_layer1 = ConstructLayer(low_layer6,512,3,3,512,1,'Relu')
mid_layer2 = ConstructLayer(mid_layer1,512,3,3,256,1,'Relu')
global_layer1 = ConstructLayer(low_layer6,512,3,3,512,2,'Relu')
global_layer2 = ConstructLayer(global_layer1,512,3,3,512,1,'Relu')
global_layer3 = ConstructLayer(global_layer2,512,3,3,512,2,'Relu')
global_layer4 = ConstructLayer(global_layer3,512,3,3,512,1,'Relu')
ML_Net = ConstructML(global_layer4,3,[1024,512,256])
Fuse = Fusion_layer(mid_layer2, ML_OUTPUT)
Color_layer1 = ConstructLayer(Fuse,256,3,3,128,1,'Relu')
Color_layer1 = UpSampling(56,56,Color_layer1)
Color_layer2 = ConstructLayer(Color_layer1,128,3,3,64,1,'Relu')
Color_layer3 = ConstructLayer(Color_layer2,64,3,3,64,1,'Relu')
Color_layer3 = UpSampling(112,112,Color_layer3)
Color_layer4 = ConstructLayer(Color_layer3,64,3,3,32,1,'Relu')
Output = ConstructLayer(Color_layer4,32,3,3,2,1,'Sigmoid')
Output = UpSampling(224,224,Output)
return Output
#----------------------------------------------------Training-------------------
def RunModel(Input_images):
global Ab_values
global Batch_indx
Prediction = Model(Input_images)
Colorization_MSE = tf.reduce_mean((Frobenius_Norm(tf.sub(Prediction,Ab_Labels_tensor))))
Optmizer = tf.train.AdadeltaOptimizer().minimize(Colorization_MSE)
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
for epoch in range(EpochsNum):
epoch_loss = 0
Batch_indx = 1
for i in range(int(ExamplesNum / Batch_size)):#over batches
print("Batch Num ",i+1)
ReadNextBatch()
_, c = sess.run([Optmizer,Colorization_MSE],feed_dict={Input_images:Batch_GreyImages,Ab_Labels_tensor:Ab_values})
epoch_loss += c
print("epoch: ",epoch+1, ",Los: ",epoch_loss)
#---- ---------------------------------------------------------------------------
RunModel(Input_images)
EDIT: this is the full code if any anyone want to help me in