How to loop DataExtMod QBXML looping - ruby-on-rails

I am trying to pass data_ext_mod request to webconnector.
q = Qbxml.new(:qb, '13.0')
data_xml =
{"qbxml"=>
{"xml_attributes"=>{},
"qbxml_msgs_rq"=>
{"xml_attributes"=>{"onError"=>"stopOnError"},
"data_ext_mod_rq"=>
data[:inspection_request_details].map do |in_rq|
{"xml_attributes"=>{}, "data_ext_mod"=>{"xml_attributes"=>{}, "owner_id"=>"0", "data_ext_name"=>"Lot", "txn_data_ext_type"=>"SalesOrder", "txn_id"=>in_rq[:txn_id], "txn_line_id"=>in_rq[:txn_line_id], "data_ext_value"=>data[:home_lot]}}
{"xml_attributes"=>{}, "data_ext_mod"=>{"xml_attributes"=>{}, "owner_id"=>"0", "data_ext_name"=>"Address", "txn_data_ext_type"=>"SalesOrder", "txn_id"=>in_rq[:txn_id], "txn_line_id"=>in_rq[:txn_line_id], "data_ext_value"=>data[:home_address]}}
end
}
}
}
xml = q.to_qbxml(data_xml)
I am trying to get the output as below when I loop data_ex_mod_rq from above request.(Expected output)
"data_ext_mod_rq"=>[
{"xml_attributes"=>{}, "data_ext_mod"=>{"xml_attributes"=>{}, "owner_id"=>"0", "data_ext_name"=>"Lot", "txn_data_ext_type"=>"SalesOrder", "txn_id"=>"AE5-1661199994", "txn_line_id"=>"AE7-1661199994", "data_ext_value"=>"000 lot"}},
{"xml_attributes"=>{}, "data_ext_mod"=>{"xml_attributes"=>{}, "owner_id"=>"0", "data_ext_name"=>"Address", "txn_data_ext_type"=>"SalesOrder", "txn_id"=>"AE5-1661199994", "txn_line_id"=>"AE7-1661199994", "data_ext_value"=>"000 address"}},
{"xml_attributes"=>{}, "data_ext_mod"=>{"xml_attributes"=>{}, "owner_id"=>"0", "data_ext_name"=>"Lot", "txn_data_ext_type"=>"SalesOrder", "txn_id"=>"AE5-1661199994", "txn_line_id"=>"AE8-1661199994", "data_ext_value"=>"001 lot"}},
{"xml_attributes"=>{}, "data_ext_mod"=>{"xml_attributes"=>{}, "owner_id"=>"0", "data_ext_name"=>"Address", "txn_data_ext_type"=>"SalesOrder", "txn_id"=>"AE5-1661199994", "txn_line_id"=>"AE8-1661199994", "data_ext_value"=>"001 address"}}
]
But the output I'm getting is like below(only address row)
"data_ext_mod_rq"=>[
{"xml_attributes"=>{}, "data_ext_mod"=>{"xml_attributes"=>{}, "owner_id"=>"0", "data_ext_name"=>"Address", "txn_data_ext_type"=>"SalesOrder", "txn_id"=>"AE5-1661199994", "txn_line_id"=>"AE7-1661199994", "data_ext_value"=>"000 address"}},
{"xml_attributes"=>{}, "data_ext_mod"=>{"xml_attributes"=>{}, "owner_id"=>"0", "data_ext_name"=>"Address", "txn_data_ext_type"=>"SalesOrder", "txn_id"=>"AE5-1661199994", "txn_line_id"=>"AE8-1661199994", "data_ext_value"=>"001 address"}}
]
Can anyone help on this? . Any help is appreciable.

Related

ROS melodic with python3 got openCV error

as mentioned on title I'm trying to use ros melodic with python3. First error pop up because of cv_bridge and it has been fixed. Now I'm getting this error:
[ERROR] [1673464074.204372, 2767.036000]: bad callback: <function im_callback at 0x7f889d1aed90>
cv2.error: OpenCV(4.4.0) /tmp/pip-req-build-civioau0/opencv/modules/dnn/src/tensorflow/tf_importer.cpp:586:
error: (-2:Unspecified error) Const input blob for weights not found in function 'getConstBlob'
I checked and could not find anything about this error.
Here is my code that I'm trying to rosrun:
#! /usr/bin/env python3
import cv2
import numpy as np
import rospy
import sensor_msgs.msg as sensor
import cv_bridge
rostopic = "/iris/camera/rgb/image_raw"
rosmsg = sensor.Image
configPath = "/home/irene/catkin_ws/src/beginner_tutorials/scripts/model/ssd_mobilenet_v3_large_coco_2020_01_14.pbtxt" #file.pbtxt
modelPath = "/home/irene/catkin_ws/src/beginner_tutorials/scripts/model/frozen_inference_graph.pb" #file.pb
classesPath = "/home/irene/catkin_ws/src/beginner_tutorials/scripts/model/coco.names" #file.names
bridge = cv_bridge.CvBridge()
def im_callback(rosmsg):
global configPath, modelPath, classesPath, bridge
img = bridge.imgmsg_to_cv2(rosmsg, "bgr8")
net = cv2.dnn_DetectionModel(modelPath, configPath)
net.setInputSize(320,320)
net.setInputScale(1/127.5)
net.setInputMean((127.5, 127.5, 127.5))
net.setInputSwapRB(True)
with open(classesPath, "r") as file:
classesList = file.read().splitlines()
classesLabelIDs, confidences, body_rects = net.detect(img, confThreshold = 0.6)
body_rects = list(body_rects)
confidences = list(np.array(confidences).reshape(1,-1)[0])
confidences = list(map(float, confidences))
bboxsIDx = cv2.dnn.NMSBoxes(body_rects, confidences, score_threshold=0.5, nms_threshold = 0.2)
if len(bboxsIDx) != 0:
for _, bID in enumerate(bboxsIDx):
classLabelID = np.squeeze(classesLabelIDs[np.squeeze(bID)])
classLabel = classesList[classLabelID]
if classLabel == "person":
body_rect = body_rects[np.squeeze(bID)]
classConfidence = confidences[np.squeeze(bID)]
display_text = "{} - {:.1}".format(classLabel, classConfidence)
x,y,w,h = body_rect
cv2.rectangle(img, (x,y), (x+w, y+h), (0,0,255), 1)
cv2.line(img, (x,y), (x+ int(w*.3), y), (0,0,255), 3)
cv2.line(img, (x,y), (x, y + int(h*.3)), (0,0,255), 3)
cv2.line(img, (x+w,y), (x + w - int(w*.3), y), (0,0,255), 3)
cv2.line(img, (x+w,y), (x+w, y + int(h*.3)), (0,0,255), 3)
cv2.line(img, (x+w,y+h), (x + w - int(w*.3), y + h), (0,0,255), 3)
cv2.line(img, (x+w,y+h), (x+w, y + h - int(h*.3)), (0,0,255), 3)
cv2.line(img, (x,y+h), (x + int(w*.3), y+h), (0,0,255), 3)
cv2.line(img, (x,y+h), (x, y + h -int(h*.3)), (0,0,255), 3)
cv2.putText(img, display_text, (x, y-8), cv2.FONT_HERSHEY_COMPLEX, .4, (255,255,255), 1)
cv2.imshow("Image", img)
cv2.waitKey(1)
def main():
global rosmsg, rostopic
rospy.init_node("webcam_node", anonymous=True)
rospy.Subscriber(rostopic, rosmsg, im_callback)
rospy.spin()
if __name__ == "__main__":
main()
I was trying to use ROS melodic with python3 and I got this error
As you've probably gathered, the error is because of you're trying to use Python3. Melodic targets Python2.7 exclusively and it's highly not recommended to try and make it run with Python3 for the reasons you're seeing. If you really want to use Python3 packages and dependencies in your project, you should instead be running the Noetic distro of ROS.

How to save a BoolValue in a DataStore System

I'm trying to make a system that saves a value so that if the player has that value then he gains the powers of that particular item but I'm not able to make that happen. There are no errors in the output and the powers are not forwarded to the player, how can I make the Data store system work to save this boolean value? There are probably errors in my code. The code is below.
local DataStoreService = game:GetService("DataStoreService") -- pegar serviço
local DataStore = DataStoreService:GetDataStore("PlrData") -- setar as informações onde serão guardadas
local FrutaSalva = DataStoreService:GetDataStore("Fruit")
local ReplicatedS = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService") -- runservice
game.Players.PlayerAdded:Connect(function(Plr) -- se o player entrar
local data = Instance.new("Folder", Plr) -- criar pasta no player que guarda valores
data.Name = "Data"
local exp = Instance.new("IntValue", data) -- valor
exp.Name = "Exp"
exp.Value = 1
local levels = Instance.new("IntValue", data)-- valor
levels.Name = "Level"
levels.Value = 1
local Points = Instance.new("IntValue", data)
Points.Name = "Points"
Points.Value = 3
local expneed = Instance.new("IntValue", data)-- valor
expneed.Name = "ExpNeeded"
expneed.Value = 100
local strenght = Instance.new("IntValue", data)-- valor
strenght.Value = 1
strenght.Name = "Strenght"
local Health = Instance.new("IntValue", data)-- valor
Health.Value = 100
Health.Name = "Health"
local char = Plr.Character or Plr.CharacterAdded:Wait()
local charhealth = char.Humanoid.Health
local DevilFruit = Instance.new("IntValue", data)-- valor
DevilFruit.Value = 1
DevilFruit.Name = "DevilFruit"
local PlayerId = Plr.UserId -- id do jogador
local PlayerData = DataStore:GetAsync(PlayerId) -- informações do jogador são pegas e se estiverem salvas então
local FruitGet = FrutaSalva:GetAsync("PlayerId")
if PlayerData then
strenght.Value = PlayerData["Strenght"] -- coloca o valor correspondente da informação salva na informação atual
Health.Value = PlayerData["Health"] -- coloca o valor correspondente da informação salva na informação atual
DevilFruit.Value = PlayerData["DevilFruit"] -- coloca o valor correspondente da informação salva na informação atual
exp.Value = PlayerData["Exp"] -- coloca o valor correspondente da informação salva na informação atual
levels.Value = PlayerData["Level"] -- coloca o valor correspondente da informação salva na informação atual
expneed.Value = PlayerData["ExpNeeded"]
Points.Value = PlayerData["Points"]-- coloca o valor correspondente da informação salva na informação atual
end
end)
local function tab(Player) -- cria uma table com o nome de status do player
local PlrStats = {} -- table criada
for _, v in pairs(Player.Data:GetChildren()) do -- procura os valores na pasta Data no player
PlrStats[v.Name] = v.Value -- pega os valores e os coloca na table de acordo com o valor e o nome
end
return PlrStats -- não sei (pesquisar)
end
game.Players.PlayerRemoving:Connect(function(Plr) -- conecta a função ao player sair
local PlrStats = tab(Plr) -- PlrStats é a função enviada com o parametro de player
local Sucess, Result = pcall(function() -- função safe
local PlrId = Plr.UserId -- player id
DataStore:SetAsync(PlrId, PlrStats) -- seta os valores da table plrstats no id do player para salvar
end)
if not Sucess then -- erro no save alerta
print(Result)
warn("Erro no save (Preocupante)")
end
end)
game:BindToClose(function() -- qunado o jogo fechar pelo servidor salva as info
for _, Player in pairs(game.Players:GetPlayers()) do
task.wait()
local PlrStats = tab(Player) -- PlrStats é a função enviada com o parametro de player
local Sucess, Result = pcall(function() -- função safe
local PlrId = Player.UserId -- player id
DataStore:SetAsync(PlrId, PlrStats) -- seta os valores da table plrstats no id do player para salvar
end)
if not Sucess then -- erro no save alerta
print(Result)
warn("Erro no save (Preocupante)")
end
end
end)
game.Players.PlayerAdded:Connect(function(Player) -- se o xp for maior que o necessário ou igual
task.wait(0.1) -- então um nivel aumenta e o xp necessário é maior
local Level = Player.Data.Level
local Exp = Player.Data.Exp
local ExpNeed = Player.Data.ExpNeeded
local Points = Player.Data.Points
local Strenght = Player.Data.Strenght
local Health = Player.Data.Health
local DevilFruit = Player.Data:WaitForChild("DevilFruit", 12)
local Char = Player.CharacterAdded:Wait()
local Hum = Char:WaitForChild("Humanoid")
Hum.MaxHealth = Hum.MaxHealth + Health.Value
task.wait(.1)
Hum.Health = Hum.Health + Health.Value
RunService.Heartbeat:Connect(function()
if Exp.Value == 0 and ExpNeed.Value == 0 then
Exp.Value = 1
ExpNeed.Value = 100
end
if Points.Value > 300 then
Points.Value = 300
end
if Exp.Value >= ExpNeed.Value then
Exp.Value = Exp.Value - ExpNeed.Value
Level.Value += 1
ExpNeed.Value *= 1.13
Points.Value += 3
end
if Strenght.Value == 0 or DevilFruit.Value == 0 or Health.Value == 0 then
Strenght.Value = 1
DevilFruit.Value = 1
Health.Value = 1
end
if Strenght.Value > 100 or DevilFruit.Value > 100 then
Strenght.Value = 100
DevilFruit.Value = 100
end
if Health.Value > 1000 then
Health.Value = 1000
end
end)
RunService.Heartbeat:Connect(function()
if Level.Value >= 100 then
Level.Value = 100
end
end)
end)
ReplicatedS:WaitForChild("Frutas"):WaitForChild("Fruta").OnServerEvent:Connect(function(Player, Fruit)
if FrutaSalva == true then
if Player.GomuGomu.Value == true then
ReplicatedS:WaitForChild("Frutas"):WaitForChild("Poderes"):WaitForChild("GomuPowers").Parent = Player.Character
end
end
end)
game.Players.PlayerRemoving:Connect(function(Player)
local success, result = pcall(function()
FrutaSalva:SetAsync(Player.UserId, true)
end)
if success then
FrutaSalva:SetAsync(Player.UserId, true)
else print(result)
end
end)

How can I make my Lua script do a natural curve down rather then juddering diagonally?

EnablePrimaryMouseButtonEvents (true);
function OnEvent(event,arg)
if IsKeyLockOn("numlock")then
if IsMouseButtonPressed(3)then
repeat
if IsMouseButtonPressed(1) then
repeat
MoveMouseRelative(0,11)
Sleep(15)
MoveMouseRelative(-1,0)
until not IsMouseButtonPressed(1)
end
until not IsMouseButtonPressed(3)
end
end
end
I tried this code in lua however it makes it judder and need it to curve slowly down. What can I try?
To move smoothly you may try to jump with shorter steps and sleep for shorter periods.
This would require special versions for Sleep and MoveMouseRelative:
do
local frac_x, frac_y = 0, 0
local orig_MoveMouseRelative = MoveMouseRelative
function MoveMouseRelative(x, y)
frac_x, frac_y = frac_x + x, frac_y + y
x, y = math.floor(frac_x), math.floor(frac_y)
frac_x, frac_y = frac_x - x, frac_y - y
while x ~= 0 or y ~= 0 do
local dx = math.min(127, math.max(-127, x))
local dy = math.min(127, math.max(-127, y))
x, y = x - dx, y - dy
orig_MoveMouseRelative(dx, dy)
end
end
local function busyloop(final_ctr)
final_ctr = final_ctr - final_ctr%1
local ctr, prev_ms, ms0, ctr0 = 0
while ctr ~= final_ctr do
local ms = GetRunningTime()
if prev_ms and ms ~= prev_ms then
if not ms0 then
ms0, ctr0 = ms, ctr
elseif final_ctr < 0 and ms - ms0 > 500 then
return (ctr - ctr0) / (ms - ms0)
end
end
prev_ms = ms
ctr = ctr + 1
end
end
local coefficient = busyloop(-1)
local orig_Sleep = Sleep
function Sleep(ms)
if ms > 30 then
return orig_Sleep(ms)
else
return busyloop(ms * coefficient)
end
end
end
EnablePrimaryMouseButtonEvents(true)
function OnEvent(event,arg)
if IsKeyLockOn("numlock")then
if IsMouseButtonPressed(3)then
repeat
if IsMouseButtonPressed(1) then
repeat
MoveMouseRelative(-0.1, 1.1)
Sleep(1.5) -- should be about 1ms for really smooth movement
until not IsMouseButtonPressed(1)
end
until not IsMouseButtonPressed(3)
end
end
end
UPDATE
If you don't have unused CPU core there is another version, not so smooth, but with a constant speed
do
local frac_x, frac_y, prev_time = 0, 0
function StartMoving()
prev_time = GetRunningTime()
end
function MoveMouseForAWhile(x, y)
Sleep(1)
local time = GetRunningTime()
time, prev_time = time - prev_time, time
frac_x, frac_y = frac_x + time * x, frac_y + time * y
x, y = math.floor(frac_x), math.floor(frac_y)
frac_x, frac_y = frac_x - x, frac_y - y
while x ~= 0 or y ~= 0 do
local dx = math.min(127, math.max(-127, x))
local dy = math.min(127, math.max(-127, y))
x, y = x - dx, y - dy
MoveMouseRelative(dx, dy)
end
end
end
EnablePrimaryMouseButtonEvents(true)
function OnEvent(event,arg)
if IsKeyLockOn("numlock")then
if IsMouseButtonPressed(3)then
repeat
if IsMouseButtonPressed(1) then
local speed = 1.5
StartMoving()
repeat
MoveMouseForAWhile(-0.1 * speed, 1.1 * speed)
until not IsMouseButtonPressed(1)
end
until not IsMouseButtonPressed(3)
end
end
end

ValueError: Incompatible shapes for broadcasting

I am new to tensorflow and I am training a neural network for all 36 characters (0-9 and a-z).
I converted a few images do tfrecords using:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import os
import cv2
import tensorflow as tf
tf.app.flags.DEFINE_string('directory', '/root/data2',
'Directory to download data files and write the '
'converted result')
FLAGS = tf.app.flags.FLAGS
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def le_imagens(aux_folder):
cont=0
img=np.empty([1,28,28,1])
for letter in os.listdir(aux_folder):
folder=aux_folder+letter+"/"
for imagem in os.listdir(folder):
os.chdir(folder)
img_temp=cv2.imread(imagem)
img_temp = cv2.cvtColor(img_temp,cv2.COLOR_BGR2GRAY)
img_temp= np.expand_dims(img_temp, axis=0)
img_temp= np.expand_dims(img_temp, axis=3)
img=np.vstack((img,img_temp))
cont=cont+1
print (cont)
print (img.shape)
return img
def calcula_label(letter):
aux_label=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1","2","3","4","5","6","7","8","9","0"]
label= np.zeros([1,36])
cont=0
for let in aux_label:
if let==letter:
label[0,cont]=1
else:
label[0,cont]=0
cont=cont+1
return label
def cria_array_labels(aux_folder):
cont=0
lab=np.empty([1,36])
for letter in os.listdir(aux_folder):
lab_temp=calcula_label(letter)
folder=aux_folder+letter+"/"
for imagem in os.listdir(folder):
lab=np.vstack((lab,lab_temp))
cont=cont+1
print (cont)
print (lab.shape)
return lab
def convert_to(images, labels, name):
#identifica quantidade de imagens e labels
num_examples = labels.shape[0]
if images.shape[0] != num_examples:
raise ValueError("Images size %d does not match label size %d." %
(images.shape[0], num_examples))
#pega parametros da imagem
rows = images.shape[1]
cols = images.shape[2]
depth = 1
#cria nome do arquivo de saida-acho que todas as imagens vao ser escritas aqui
filename = os.path.join(FLAGS.directory, name + '.tfrecords')
print('Writing', filename)
writer = tf.python_io.TFRecordWriter(filename)
#faz um loop para cada uma das imagens
for index in range(num_examples):
#converte a imagem para string
image_raw = images[index].tostring()
labels_raw = labels[index].tostring()
#aloca no exemplo as dimensoes da img, o label e a imagem convertida
example = tf.train.Example(features=tf.train.Features(feature={
'height': _int64_feature(rows),
'width': _int64_feature(cols),
'depth': _int64_feature(depth),
'label': _bytes_feature(labels_raw),
'image_raw': _bytes_feature(image_raw)}))
#escreve o exemplo
writer.write(example.SerializeToString())
writer.close()
def main(argv):
#Train
aux_folder="/root/captchas/captchas_lft/"
img_treino=le_imagens(aux_folder)
lab_treino=cria_array_labels(aux_folder)
print ("Base de Treino Preparada")
#Cross Validation
aux_folder="/root/captchas/captchas_lfcv/"
img_cv=le_imagens(aux_folder)
lab_cv=cria_array_labels(aux_folder)
print ("Base de CV Preparada")
#Test Set
aux_folder="/root/captchas/captchas_lfts/"
img_ts=le_imagens(aux_folder)
lab_ts=cria_array_labels(aux_folder)
print ("Base de Teste Preparada")
convert_to(img_treino, lab_treino, 'train')
convert_to(img_cv, lab_cv, 'validation')
convert_to(img_ts, lab_ts, 'test')
if __name__ == '__main__':
tf.app.run()
And I am feeding the following network (which is an adaptation of MNIST2 Tensorflow tutorial):
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import time
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import mnist
# Basic model parameters as external flags.
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('num_epochs', 2, 'Number of epochs to run trainer.')
flags.DEFINE_integer('batch_size', 100, 'Batch size.')
flags.DEFINE_string('train_dir', '/root/data', 'Directory with the training data.')
#flags.DEFINE_string('train_dir', '/root/data2', 'Directory with the training data.')
# Constants used for dealing with the files, matches convert_to_records.
TRAIN_FILE = 'train.tfrecords'
VALIDATION_FILE = 'validation.tfrecords'
# Set-up dos pacotes
sess = tf.InteractiveSession()
def read_and_decode(filename_queue):
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
dense_keys=['image_raw', 'label'],
# Defaults are not specified since both keys are required.
dense_types=[tf.string, tf.string])
# Convert from a scalar string tensor (whose single string has
# length mnist.IMAGE_PIXELS) to a uint8 tensor with shape
# [mnist.IMAGE_PIXELS].
image = tf.decode_raw(features['image_raw'], tf.uint8)
image.set_shape([784])
#print (mnist.IMAGE_PIXELS)
# OPTIONAL: Could reshape into a 28x28 image and apply distortions
# here. Since we are not applying any distortions in this
# example, and the next step expects the image to be flattened
# into a vector, we don't bother.
# Convert from [0, 255] -> [-0.5, 0.5] floats.
image = tf.cast(image, tf.float32) * (1. / 255) - 0.5
# Convert label from a scalar uint8 tensor to an int32 scalar.
label = tf.cast(features['label'], tf.float32)
#print (label)
#label.set_shape([1])
#print (label)
return image, label
def inputs(train, batch_size, num_epochs):
"""Reads input data num_epochs times.
Args:
train: Selects between the training (True) and validation (False) data.
batch_size: Number of examples per returned batch.
num_epochs: Number of times to read the input data, or 0/None to
train forever.
Returns:
A tuple (images, labels), where:
* images is a float tensor with shape [batch_size, 30,26,1]
in the range [-0.5, 0.5].
* labels is an int32 tensor with shape [batch_size] with the true label,
a number in the range [0, char letras).
Note that an tf.train.QueueRunner is added to the graph, which
must be run using e.g. tf.train.start_queue_runners().
"""
if not num_epochs: num_epochs = None
filename = os.path.join(FLAGS.train_dir,
TRAIN_FILE if train else VALIDATION_FILE)
with tf.name_scope('input'):
filename_queue = tf.train.string_input_producer(
[filename], num_epochs=num_epochs)
# Even when reading in multiple threads, share the filename
# queue.
image, label = read_and_decode(filename_queue)
# Shuffle the examples and collect them into batch_size batches.
# (Internally uses a RandomShuffleQueue.)
# We run this in two threads to avoid being a bottleneck.
images, sparse_labels = tf.train.shuffle_batch(
[image, label], batch_size=batch_size, num_threads=2,
capacity=1000 + 3 * batch_size,
# Ensures a minimum amount of shuffling of examples.
min_after_dequeue=1000)
return images, sparse_labels
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
#Variaveis
x, y_ = inputs(train=True, batch_size=FLAGS.batch_size, num_epochs=FLAGS.num_epochs)
#y_ = tf.string_to_number(y_, out_type=tf.int32)
teste=tf.convert_to_tensor(y_)
#Layer 1
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
#Layer 2
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)
#Densely Connected Layer
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
#Dropout - reduz overfitting
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
#Readout layer
W_fc2 = weight_variable([1024, 36])
b_fc2 = bias_variable([36])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
#y_conv=tf.cast(y_conv, tf.int32)
#Train and evaluate
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
sess.run(tf.initialize_all_variables())
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for i in range(20000):
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={keep_prob: 1.0})
print("step %d, training accuracy %g"%(i, train_accuracy))
train_step.run(feed_dict={keep_prob: 0.5})
x, y_ = inputs(train=True, batch_size=2000)
#y_ = tf.string_to_number(y_, out_type=tf.int32)
print("test accuracy %g"%accuracy.eval(feed_dict={keep_prob: 1.0}))
coord.join(threads)
sess.close()
But whe it comes to
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))
The following error appears:
ValueError: Incompatible shapes for broadcasting: TensorShape([Dimension(100)]) and TensorShape([Dimension(100), Dimension(36)])
I think the problem is de label tensor, but i am not sure how to fix it in order to have a (None,36) dimension. Does anyone knows how to solve this issue?
Thanks
Marcelo
The simplest way to make this work is to replace y_ with a one-hot encoding using tf.one_hot():
onehot_y_ = tf.one_hot(y_, 36, dtype=tf.float32)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(onehot_y_ * tf.log(y_conv),
reduction_indices=[1]))
An alternative would be to switch to using the specialized op tf.nn.sparse_softmax_cross_entropy_with_logits(), which is more efficient and more numerically stable. To use it, you'll have to remove the call to tf.nn.softmax() in the definition of y_conv:
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(y_conv, y_))

Lua: Calling functions in own module

I created a module for an RTC. It looks like this:
local moduleName = ...
local M = {}
_G[moduleName] = M
---------- Local variables ---------------------
local id = 0
local address = 0x68
---------- Helper functions --------------------
local function bcdToDec(val)
local hl=bit.rshift(val, 4)
local hh=bit.band(val,0xf)
local hr = string.format("%d%d", hl, hh)
return string.format("%d%d", hl, hh)
end
local function decToBcd(val)
local d = string.format("%d",tonumber(val / 10))
local d1 = tonumber(d*10)
local d2 = val - d1
return tonumber(d*16+d2)
end
---------- Module functions --------------------
function M.Init(sda, scl)
i2c.setup(id, sda, scl, i2c.SLOW)
end
function M.PrintTime()
i2c.start(id)
i2c.address(id, address, i2c.TRANSMITTER)
i2c.write(id, 0x00)
i2c.stop(id)
i2c.start(id)
i2c.address(id, address, i2c.RECEIVER)
c=i2c.read(id, 7)
i2c.stop(id)
s = bcdToDec(string.byte(c,1))
m = bcdToDec(string.byte(c,2))
h = bcdToDec(string.byte(c,3))
time=string.format(" %s:%s:%s", h, m, s)
print(time);
end
function M.PrintDate()
i2c.start(id)
i2c.address(id, address, i2c.TRANSMITTER)
i2c.write(id, 0x00)
i2c.stop(id)
i2c.start(id)
i2c.address(id, address, i2c.RECEIVER)
c=i2c.read(id, 7)
i2c.stop(id)
s = bcdToDec(string.byte(c,1))
m = bcdToDec(string.byte(c,2))
h = bcdToDec(string.byte(c,3))
wkd = bcdToDec(string.byte(c,4))
day = bcdToDec(string.byte(c,5))
month = bcdToDec(string.byte(c,6))
year = bcdToDec(string.byte(c,7))
time=string.format(" %s.%s.%s", day, month, year)
print(time);
end
return M
I saved this file as "ds3231_m.lua". Calling functions from another file works like this:
m = require 'ds3231_m'
m.Init(2,1) --sda, scl = 2, 1
m.PrintTime()
--m.PrintDate()
package.loaded.ds3231_m = Nil
as well as
m = require 'ds3231_m'
m.Init(2,1) --sda, scl = 2, 1
--m.PrintTime()
m.PrintDate()
package.loaded.ds3231_m = Nil
But when I try calling both functions:
m = require 'ds3231_m'
m.Init(2,1) --sda, scl = 2, 1
m.PrintTime()
m.PrintDate()
package.loaded.ds3231_m = Nil
I get an error:
test.lua:4: attempt to call field 'PrintDate' (a nil value)
Can anyone tell me what is going wrong?
Thank you very much in advance!
Regards
Inside PrintTime (and PrintDate) you're doing m = something. That does overwrite your m from m = require(...).
You should use locals in those functions:
function M.PrintTime()
i2c.start(id)
i2c.address(id, address, i2c.TRANSMITTER)
i2c.write(id, 0x00)
i2c.stop(id)
i2c.start(id)
i2c.address(id, address, i2c.RECEIVER)
local c=i2c.read(id, 7)
i2c.stop(id)
local s = bcdToDec(string.byte(c,1))
local m = bcdToDec(string.byte(c,2))
local h = bcdToDec(string.byte(c,3))
local time=string.format(" %s:%s:%s", h, m, s)
print(time);
end
That way, you won't be editing any globals. Also do the same for PrintDate.
(If you did other_name_than_m = require(...) you wouldn't have noticed, but print(m) would still print a number, the amount of minutes from something)

Resources