Cancelling terms with manim instead TeX - manim

Can you draw diagonal lines/arrows/ whatever looks like youre crossing out cancelling like terms in a math equation in manim?

The closest thing that is defined is Cross, but it is not exactly what you are looking for, I like to use this:
class Cancel(VGroup):
CONFIG = {
"line_kwargs": {"color":RED},
"buff_text": None,
"buff_line": 0.7,
}
def __init__(self,text,texmob=None,**kwargs):
digest_config(self,kwargs)
VGroup.__init__(self,**kwargs)
pre_coord_dl = text.get_corner(DL)
pre_coord_ur = text.get_corner(UR)
reference_line = Line(pre_coord_dl,pre_coord_ur)
reference_unit_vector = reference_line.get_unit_vector()
coord_dl = text.get_corner(DL) - text.get_center() - reference_unit_vector*self.buff_line
coord_ur = text.get_corner(UR) - text.get_center() + reference_unit_vector*self.buff_line
if texmob == None:
line = Line(coord_dl,coord_ur,**self.line_kwargs)
self.add(line)
else:
arrow = Arrow(coord_dl,coord_ur,**self.line_kwargs)
unit_vector = arrow.get_unit_vector()
if self.buff_text == None:
self.buff_text = get_norm((texmob.get_center()-texmob.get_critical_point(unit_vector))/2)*2
texmob.move_to(arrow.get_end()+unit_vector*self.buff_text)
self.add(arrow,texmob)
class CancelTerms(Scene):
def construct(self):
formula = TexMobject("f(x)",height=1)
cancel_formula = Cancel(formula,TexMobject("testa"))
self.add(formula,cancel_formula)

Related

ImageLabel doesn't display in BillboardGUI

So, this is my problem.
This script works with one image id, but not any others.
I literally have no idea why this is happening.
This is the script >>
function newEntity(imgId, eName)
EntityBase = Instance.new("Part", workspace)
EntityBase.Transparency = 1
EntityBase.Size = Vector3.new(0.9, 0.1, 0.7)
EntityBase.Name = eName
EntityBillboardGui = Instance.new("BillboardGui", EntityBase)
EntityBillboardGui.StudsOffset = Vector3.new(0, 5, 0)
EntityBillboardGui.Size = UDim2.new(0,250,0,250)
EntityBillboardGui.MaxDistance = math.huge
EntityBillboardGui.Adornee = EntityBase
EntityImage = Instance.new("ImageLabel",EntityBillboardGui)
EntityImage.Size = EntityBillboardGui.Size
EntityImage.BackgroundTransparency = 1
EntityImage.Image = imgId
return EntityBase
end
troller = newEntity("rbxthumb://11954446780","imposter")
troller.Position = game.Players.LocalPlayer.Character.HumanoidRootPart.Position
trololol = Instance.new("Sound", troller)
trololol.SoundId = "http://www.roblox.com/asset/?id=5677788502"
trololol:Play()
wait(2)
troller:Destroy()
game.Players.LocalPlayer.Character.Humanoid.Health = 0
Can anybody help fix it?
For starters I would recommend seperating the parent, like this:
EntityBase = Instance.new("Part") EntityBase.Parent = workspace
SECOND: I would recommend not using a seperate part, just put the billboardGui into the player's head
third you used rbxthumb wrong
rbxthumb://type=[ThumbnailType]&id=[TargetId]&w=[Width]&h=[Height]”
These are the supported sizes and types
example: rbxthumb://type=Avatar&id=123456789&w=720&h=720

Why does all my emission mu of HMM in pyro converge to the same number?

I'm trying to create a Gaussian HMM model in pyro to infer the parameters of a very simple Markov sequence. However, my model fails to infer the parameters and something wired happened during the training process. Using the same sequence, hmmlearn has successfully infer the true parameters.
Full code can be accessed in here:
https://colab.research.google.com/drive/1u_4J-dg9Y1CDLwByJ6FL4oMWMFUVnVNd#scrollTo=ZJ4PzdTUBgJi
My model is modified from the example in here:
https://github.com/pyro-ppl/pyro/blob/dev/examples/hmm.py
I manually created a first order Markov sequence where there are 3 states, the true means are [-10, 0, 10], sigmas are [1,2,1].
Here is my model
def model(observations, num_state):
assert not torch._C._get_tracing_state()
with poutine.mask(mask = True):
p_transition = pyro.sample("p_transition",
dist.Dirichlet((1 / num_state) * torch.ones(num_state, num_state)).to_event(1))
p_init = pyro.sample("p_init",
dist.Dirichlet((1 / num_state) * torch.ones(num_state)))
p_mu = pyro.param(name = "p_mu",
init_tensor = torch.randn(num_state),
constraint = constraints.real)
p_tau = pyro.param(name = "p_tau",
init_tensor = torch.ones(num_state),
constraint = constraints.positive)
current_state = pyro.sample("x_0",
dist.Categorical(p_init),
infer = {"enumerate" : "parallel"})
for t in pyro.markov(range(1, len(observations))):
current_state = pyro.sample("x_{}".format(t),
dist.Categorical(Vindex(p_transition)[current_state, :]),
infer = {"enumerate" : "parallel"})
pyro.sample("y_{}".format(t),
dist.Normal(Vindex(p_mu)[current_state], Vindex(p_tau)[current_state]),
obs = observations[t])
My model is compiled as
device = torch.device("cuda:0")
obs = torch.tensor(obs)
obs = obs.to(device)
torch.set_default_tensor_type("torch.cuda.FloatTensor")
guide = AutoDelta(poutine.block(model, expose_fn = lambda msg : msg["name"].startswith("p_")))
Elbo = Trace_ELBO
elbo = Elbo(max_plate_nesting = 1)
optim = Adam({"lr": 0.001})
svi = SVI(model, guide, optim, elbo)
As the training goes, the ELBO has decreased steadily as shown. However, the three means of the states converges.
I have tried to put the for loop of my model into a pyro.plate and switch pyro.param to pyro.sample and vice versa, but nothing worked for my model.
I have not tried this model, but I think it should be possible to solve the problem by modifying the model in the following way:
def model(observations, num_state):
assert not torch._C._get_tracing_state()
with poutine.mask(mask = True):
p_transition = pyro.sample("p_transition",
dist.Dirichlet((1 / num_state) * torch.ones(num_state, num_state)).to_event(1))
p_init = pyro.sample("p_init",
dist.Dirichlet((1 / num_state) * torch.ones(num_state)))
p_mu = pyro.sample("p_mu",
dist.Normal(torch.zeros(num_state), torch.ones(num_state)).to_event(1))
p_tau = pyro.sample("p_tau",
dist.HalfCauchy(torch.zeros(num_state)).to_event(1))
current_state = pyro.sample("x_0",
dist.Categorical(p_init),
infer = {"enumerate" : "parallel"})
for t in pyro.markov(range(1, len(observations))):
current_state = pyro.sample("x_{}".format(t),
dist.Categorical(Vindex(p_transition)[current_state, :]),
infer = {"enumerate" : "parallel"})
pyro.sample("y_{}".format(t),
dist.Normal(Vindex(p_mu)[current_state], Vindex(p_tau)[current_state]),
obs = observations[t])
The model would then be trained using MCMC:
# MCMC
hmc_kernel = NUTS(model, target_accept_prob = 0.9, max_tree_depth = 7)
mcmc = MCMC(hmc_kernel, num_samples = 1000, warmup_steps = 100, num_chains = 1)
mcmc.run(obs)
The results could then be analysed using:
mcmc.get_samples()

how can I modify Dataset class to make the mask RCNN work with multiple objects?

I am currently working on instance segmentation. I follow these two tutorials:
https://haochen23.github.io/2020/06/fine-tune-mask-rcnn-pytorch.html
https://colab.research.google.com/github/dlmacedo/starter-academic/blob/master/content/courses/deeplearning/notebooks/pytorch/torchvision_finetuning_instance_segmentation.ipynb#scrollTo=mTgWtixZTs3X
However, these two tutorials work perfectly with one class like person + background. But in my case, I have two classes like a person and car + background. I didn't find any resources about making the Mask RCNN work with multiple objects.
Notice that:
I am using PyTorch ( torchvision ), torch==1.10.0+cu111 torchvision==0.11.0+cu111 torchaudio==0.10.0
I am using a Pascal VOC annotation
i used segmentation class (not the XML file) + the images
and this is my dataset class
class PennFudanDataset(torch.utils.data.Dataset):
def __init__(self, root, transforms=None):
self.root = root
self.transforms = transforms
# load all image files, sorting them to
# ensure that they are aligned
self.imgs = list(sorted(os.listdir(os.path.join(root, "img"))))
self.masks = list(sorted(os.listdir(os.path.join(root, "imgMask"))))
def __getitem__(self, idx):
# load images ad masks
img_path = os.path.join(self.root, "img", self.imgs[idx])
mask_path = os.path.join(self.root, "imgMask", self.masks[idx])
img = Image.open(img_path).convert("RGB")
# note that we haven't converted the mask to RGB,
# because each color corresponds to a different instance
# with 0 being background
mask = Image.open(mask_path)
mask = np.array(mask)
# instances are encoded as different colors
obj_ids = np.unique(mask)
# first id is the background, so remove it
obj_ids = obj_ids[1:]
# split the color-encoded mask into a set
# of binary masks
masks = mask == obj_ids[:, None, None]
# get bounding box coordinates for each mask
num_objs = len(obj_ids)
boxes = []
for i in range(num_objs):
pos = np.where(masks[i])
xmin = np.min(pos[1])
xmax = np.max(pos[1])
ymin = np.min(pos[0])
ymax = np.max(pos[0])
boxes.append([xmin, ymin, xmax, ymax])
boxes = torch.as_tensor(boxes, dtype=torch.float32)
# there is only one class
labels = torch.ones((num_objs,), dtype=torch.int64)
masks = torch.as_tensor(masks, dtype=torch.uint8)
image_id = torch.tensor([idx])
area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])
# suppose all instances are not crowd
iscrowd = torch.zeros((num_objs,), dtype=torch.int64)
target = {}
target["boxes"] = boxes
target["labels"] = labels
target["masks"] = masks
target["image_id"] = image_id
target["area"] = area
target["iscrowd"] = iscrowd
if self.transforms is not None:
img, target = self.transforms(img, target)
return img, target
def __len__(self):
return len(self.imgs)
anyone can help me?

How to Display a decomposition wavelet in 3 level?

I want to display a decomposition wavelet in 3 level.
so can any help me in give a Matlab function to display it?
[cA cH cV cD]=dwt2(a,waveletname);
out=[cA cH;cV cD];
figure;imshow(out,[]);
That only works for the first level.
actually, I want to representation square mode such wavemenu in Matlab.
example of the view decomposition
I am fairly new to it.
thanx.
You should use the function wavedec2(Image,numberOfLevels,'wname') with the amount of levels that you need.
For more information look at
http://www.mathworks.com/help/wavelet/ref/wavedec2.html
Code for example with db1
clear all
im = imread('cameraman.tif');
[c,s] = wavedec2(im,3,'db1');
A1 = appcoef2(c,s,'db1',1);
[H1,V1,D1] = detcoef2('all',c,s,1);
A2 = appcoef2(c,s,'db1',2);
[H2,V2,D2] = detcoef2('all',c,s,2);
A3 = appcoef2(c,s,'db1',3);
[H3,V3,D3] = detcoef2('all',c,s,3);
V1img = wcodemat(V1,255,'mat',1);
H1img = wcodemat(H1,255,'mat',1);
D1img = wcodemat(D1,255,'mat',1);
A1img = wcodemat(A1,255,'mat',1);
V2img = wcodemat(V2,255,'mat',1);
H2img = wcodemat(H2,255,'mat',1);
D2img = wcodemat(D2,255,'mat',1);
A2img = wcodemat(A2,255,'mat',1);
V3img = wcodemat(V3,255,'mat',1);
H3img = wcodemat(H3,255,'mat',1);
D3img = wcodemat(D3,255,'mat',1);
A3img = wcodemat(A3,255,'mat',1);
mat3 = [A3img,V3img;H3img,D3img];
mat2 = [mat3,V2img;H2img,D2img];
mat1 = [mat2,V1img;H1img,D1img];
imshow(uint8(mat1))
The final result

help in coding decision tree in python

I am not sure if this is the right place to post this, but I have been trying to code up a simple decision tree class for a while and am getting lost at various points.
Specifically, I'm not sure what kind of data structure would represent a recursive tree that uses (feature, value) as nodes.
class DecisionTree():
def entropy(self, data):
# if there's nothing in this region, entropy is 1
if len(data) <= 1:
return 1
target_col = data.ix[:,-1]
size = float(len(target_col))
classes = Counter(target_col)
# if there's only one class, entropy is 1
if len(classes) == 1:
return 1
else:
probs = [i / size for i in classes.values()]
entropy = np.sum([-probs[i]*np.log(probs[i]) for i in range(len(probs))])
return entropy
def what_to_split_on(self, data):
split_feature = -1
best_entropy = 0.0
base_entropy = self.entropy(data)
for f, feature in enumerate(data.T):
unique_vals = list(set(feature))
for val in unique_vals:
left, right = self.split(f, val)
prop_left = float(len(left)) / (len(left) + len(right))
prop_right = 1 - prop_left
e_1 = prop_left * self.entropy(left)
e_2 = prop_right * self.entropy(right)
entropy_change = base_entropy - e_1 - e_2
if entropy_change > best_entropy:
best_entropy = entropy_change
split_feature = f; split_val = val
if split_feature != -1:
return split_feature, split_val
def split(self, data, f, val):
left = np.array([row for row in data if row[f] == val])
right = np.array([row for row in data if row[f] != val])
return left, right
def create_tree(self, data):
if self.entropy(data) == 1:
return
feature, value = self.what_to_split_on(data)
dt = Tree(feature, value)
left_child = np.array([row for row in data if row[feature] == value])
right_child = np.array([row for row in data if row[feature] == value])
feature, value = self.what_to_split_on(left_child)
sub_left = create_tree(left_child)
dt.insert_left(sub_left)
feature, value = self.what_to_split_on(right_child)
sub_right = create_tree(right_child)
dt.insert_right(sub_right)
return dt

Resources