ValueError: No gradients provided for any variable in GanModel with tap.gradiant - generative-adversarial-network

I am building GAN Model for image captioning, that generator produce a word. then we call generator to the maximum length of the sentence. and then we give the generated sentence to the discriminator and update the network using these and loss function, but I got error.
optimizer = tf.keras.optimizers.Adam(1e-5)
for name in train:
print(name)
feature=train_features[name].reshape(1,train_features[name].shape[0],
train_features[name].shape[1],
train_features[name].shape[2])
for desc in train_descriptions[name]:
with tf.GradientTape(persistent=True) as tape:
in_text = 'startseq'
for i in range(1, max_length):
sequence = tokenizer.texts_to_sequences([in_text])[0]
sequence = pad_sequences([sequence], maxlen=max_length)
yhat=G([feature,sequence])[0]
## find index of word
word = tf.math.argmax(yhat)
## convert to word
word = word_for_idV2(word, tokenizer)
in_text += ' ' + word
if word == 'endseq':
break
fake_data = tokenizer.texts_to_sequences([in_text])[0]
fake_data = pad_sequences([fake_data], maxlen=max_length)
d_fake_data=D([feature,fake_data])
print("==================================")
print(d_fake_data)
real_data = tf.convert_to_tensor(tokenizer.texts_to_sequences([desc]),dtype=tf.float32)
print(real_data)
g_loss_value = g_loss2(loss_d=d_fake_data,real_desc=real_data)
print("g_loss_value")
print(g_loss_value)
# Now that we have computed the losses, we can compute the gradients
# (using the tape) and optimize the networks
print(G.trainable_variables)
g_gradients = tape.gradient(g_loss_value, G.trainable_variables)
print("g_gradients")
print(g_gradients)
optimizer.apply_gradients(zip(g_gradients, G.trainable_variables))
Error code is below.
ValueError: No gradients provided for any variable: ['conv2d/kernel:0', 'conv2d/bias:0', 'conv2d_1/kernel:0', 'conv2d_1/bias:0', 'conv2d_2/kernel:0', 'conv2d_2/bias:0', 'conv2d_3/kernel:0', 'conv2d_3/bias:0', 'embedding/embeddings:0', 'lstm/kernel:0', 'lstm/recurrent_kernel:0', 'lstm/bias:0', 'lstm_1/kernel:0', 'lstm_1/recurrent_kernel:0', 'lstm_1/bias:0', 'dense/kernel:0', 'dense/bias:0', 'dense_1/kernel:0', 'dense_1/bias:0', 'lstm_2/kernel:0', 'lstm_2/recurrent_kernel:0', 'lstm_2/bias:0', 'decoder_output/kernel:0', 'decoder_output/bias:0'].

Related

Plot title with variable value and subscript characters in Julia

I'm trying to have a plot title which contains variable values and also characters with subscripts, however when I try:
title = "ηₛ = $η̂[Pa S] , μₛ = $μ̂[Pa], μₚ = $μ̂ₚ[Pa] , ηₚ = $η̂ₚ[Pa S] \n α = $α̂ , ζ = $ζ̂"
Inside the plot function, the title appears with X marks where the subscripts are. I tried to use LaTeX ```title = L" .." but then the variable values don't appear.
Is there any way to have both in the title I need?
If you want a fully working solution this is what I think you need to do, note that %$ is used for interpolation:
title = L"\eta_1 = %$(η̂[Pa, S])"
The reason is that, while some of the characters will be rendered correctly as Bill noted, not all of them will unless you use LaTeXStrings.jl.
See:
help?> LaTeXStrings.#L_str
L"..."
Creates a LaTeXString and is equivalent to latexstring(raw"..."), except that %$ can be used for interpolation.
julia> L"x = \sqrt{2}"
L"$x = \sqrt{2}$"
julia> L"x = %$(sqrt(2))"
L"$x = 1.4142135623730951$"

Preallocating a dict of dicts

When I run #code_warntype on the following function (Shown in bold are the expressions that are likely raising the red flags.)
function cardata(df::DataFrame,Emission_val::Float64,search_cars::Dict{String,Tuple{Int64,Int64}}=Dict("Car1" => (1000,10000), "Car2" => (1000,50000), "Car3" => (1000,6000)),
all_cars::Array{String,1}=["Car1","Car2","Car3","Car4","Car5","Car6"])
**species = Dict()**
# The data file containing car information of interest
car_library = joinpath(path,"cars.csv")
df_car_data=CSV.read(car_library,header=["Model","Velocity","Emission_Value","Mass","Column6"],delim='\t')
#delete unused column
deletecols!(df_car_data, :Column6)
#create a new column with only the car Identifier name
df_car_data[:Identifier_car]=[split(i,r"[0-9]+")[1] for i in df_car_data[:Model]]
#get the properties of all_cars from the cars_data table
for search_models in all_cars
**cars[search_models] = Dict()**
for i in 1:1:length(df_cars_data[1])
num = split(df_cars_data[:Model][i],r"[0-9]+")[1]
alpha = split(df_cars_data[:Model][i],r"[a-zA-Z]+")[2]
if ( num == search_models )
species[num][alpha] = df_car_data[:Velocity][i]
end
end
end
end
I get the following warning highlighted in red:
Body::Tuple{Dict{Any,Any},Union{DataFrame,DataFrameRow{DataFrame,Index}},Any,Any}.
How to preallocate the types for dicts in such a case, assuming that I know the length of data that will populate the dict?
You have not provided a minimal working example.
Have a look at the code below. Note that for efficiency reasons
it is recommended to use Symbol a the key rather than String
species = Dict{Symbol,Dict{Symbol,Float64}}()
group = get!(()->Dict{Symbol,Float64}(),species,Symbol("audi"))
group[Symbol("a4")]=10.5
group[Symbol("a6")]=9.5
And now printing the output:
julia> println(species)
Dict(:audi=>Dict(:a6=>9.5,:a4=>10.5))

This is math quiz doesn't work. I don't know why

import random
while True:
calc_1 = (random.randint(1,50)) #generates random variables
calc_2 = (random.randint(1,50))
print (calc_1,"+",calc_2) #prints the random question
a = ((calc_1)+(calc_2)) #calculates the random question
q = input ("? ")
if q == a :
print ("right")
break
else:
print ("wrong")
It won't say right, when the answer is right. I already tested a few other possibilities but I couldn't figure it out.
input() gives you str so convert it to int before comparison
import random
while True:
calc_1 = (random.randint(1, 50)) # generates random variables
calc_2 = (random.randint(1, 50))
print(calc_1, "+", calc_2) # prints the random question
a = ((calc_1) + (calc_2)) # calculates the random question
q = input("? ")
try:
q = int(q)
if q == a:
print("right")
break
else:
print("wrong")
except:
print('Not a number')

How to print a complex number without percent sign in Scilab?

I tried this
a = 1+3*%i;
disp("a = "+string(a))
I got a = 1+%i*3 , but what I want is a = 1. + 3.i
So is there any method in Scilab to print a complex number without the percent sign?
Similarly to Matlab, you can format the output string by including the real and imaginary parts separately.
mprintf('%g + %gi\n', real(a) , imag(a))
However, that looks pretty ugly when the imaginary part is negative. I suggest writing a formatting function:
function s = complexstring(a)
if imag(a)>=0 then
s = sprintf('%g+%gi', real(a) , imag(a))
else
s = sprintf('%g%gi', real(a) , imag(a))
end
endfunction
Examples:
disp('a = '+complexstring(1+3*%i))
disp('b = '+complexstring(1-3*%i))
Output:
a = 1+3i
b = 1-3i

alignment of sequences

I want to do pairwise alignment with uniprot and pdb sequences. I have an input file containing uniprot and pdb IDs like this.
pdb id uniprot id
1dbh Q07889
1e43 P00692
1f1s Q53591
first, I need to read each line in an input file
2) retrieve the pdb and uniprot sequences from pdb.fasta and uniprot.fasta files
3) Do alignment and calculate sequence identity.
Usually, I use the following program for pairwise alignment and seq.identity calculation.
library("seqinr")
seq1 <- "MDEKRRAQHNEVERRRRDKINNWIVQLSKIIPDSSMESTKSGQSKGGILSKASDYIQELRQSNHR"
seq2<- "MKGQQKTAETEEGTVQIQEGAVATGEDPTSVAIASIQSAATFPDPNVKYVFRTENGGQVM"
library(Biostrings)
globalAlign<- pairwiseAlignment(seq1, seq2)
pid(globalAlign, type = "PID3")
I need to print the output like this
pdbid uniprotid seq.identity
1dbh Q07889 99
1e43 P00692 80
1f1s Q53591 56
How can I change the above code ? your help would be appreciated!
'
This code is hopefully what your looking for:
class test():
def get_seq(self, pdb,fasta_file): # Get sequences
from Bio.PDB.PDBParser import PDBParser
from Bio import SeqIO
aa = {'ARG':'R','HIS':'H','LYS':'K','ASP':'D','GLU':'E','SER':'S','THR':'T','ASN':'N','GLN':'Q','CYS':'C','SEC':'U','GLY':'G','PRO':'P','ALA':'A','ILE':'I','LEU':'L','MET':'M','PHE':'F','TRP':'W','TYR':'Y','VAL':'V'}
p=PDBParser(PERMISSIVE=1)
structure_id="%s" % pdb[:-4]
structure=p.get_structure(structure_id, pdb)
residues = structure.get_residues()
seq_pdb = ''
for res in residues:
res = res.get_resname()
if res in aa:
seq_pdb = seq_pdb+aa[res]
handle = open(fasta_file, "rU")
for record in SeqIO.parse(handle, "fasta") :
seq_fasta = record.seq
handle.close()
self.seq_aln(seq_pdb,seq_fasta)
def seq_aln(self,seq1,seq2): # Align the sequences
from Bio import pairwise2
from Bio.SubsMat import MatrixInfo as matlist
matrix = matlist.blosum62
gap_open = -10
gap_extend = -0.5
alns = pairwise2.align.globalds(seq1, seq2, matrix, gap_open, gap_extend)
top_aln = alns[0]
aln_seq1, aln_seq2, score, begin, end = top_aln
with open('aln.fasta', 'w') as outfile:
outfile.write('> PDB_seq\n'+str(aln_seq1)+'\n> Uniprot_seq\n'+str(aln_seq2))
print aln_seq1+'\n'+aln_seq2
self.seq_id('aln.fasta')
def seq_id(self,aln_fasta): # Get sequence ID
import string
from Bio import AlignIO
input_handle = open("aln.fasta", "rU")
alignment = AlignIO.read(input_handle, "fasta")
j=0 # counts positions in first sequence
i=0 # counts identity hits
for record in alignment:
#print record
for amino_acid in record.seq:
if amino_acid == '-':
pass
else:
if amino_acid == alignment[0].seq[j]:
i += 1
j += 1
j = 0
seq = str(record.seq)
gap_strip = seq.replace('-', '')
percent = 100*i/len(gap_strip)
print record.id+' '+str(percent)
i=0
a = test()
a.get_seq('1DBH.pdb','Q07889.fasta')
This outputs:
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------EQTYYDLVKAF-AEIRQYIRELNLIIKVFREPFVSNSKLFSANDVENIFSRIVDIHELSVKLLGHIEDTVE-TDEGSPHPLVGSCFEDLAEELAFDPYESYARDILRPGFHDRFLSQLSKPGAALYLQSIGEGFKEAVQYVLPRLLLAPVYHCLHYFELLKQLEEKSEDQEDKECLKQAITALLNVQSG-EKICSKSLAKRRLSESA-------------AIKK-NEIQKNIDGWEGKDIGQCCNEFI-EGTLTRVGAKHERHIFLFDGL-ICCKSNHGQPRLPGASNAEYRLKEKFF-RKVQINDKDDTNEYKHAFEIILKDENSVIFSAKSAEEKNNW-AALISLQYRSTL---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
MQAQQLPYEFFSEENAPKWRGLLVPALKKVQGQVHPTLESNDDALQYVEELILQLLNMLCQAQPRSASDVEERVQKSFPHPIDKWAIADAQSAIEKRKRRNPLSLPVEKIHPLLKEVLGYKIDHQVSVYIVAVLEYISADILKL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FPNSPSPFTPPPPQTPSPHGTRRHLPSPPLTQEVDLHSIAGPPVPPRQSTSQHIPKLPPKTYKREHTHPSMHRDGPPLLENAHSS
PDB_seq 100 # pdb to itself would obviously have 100% identity
Uniprot_seq 24 # pdb sequence has 24% identity to the uniprot sequence
For this to work on you input file, you need to put my a.get_seq() in a for loop with the inputs from your text file.
EDIT:
Replace the seq_id function with this one:
def seq_id(self,aln_fasta):
import string
from Bio import AlignIO
from Bio import SeqIO
record_iterator = SeqIO.parse(aln_fasta, "fasta")
first_record = record_iterator.next()
print '%s has a length of %d' % (first_record.id, len(str(first_record.seq).replace('-','')))
second_record = record_iterator.next()
print '%s has a length of %d' % (second_record.id, len(str(second_record.seq).replace('-','')))
lengths = [len(str(first_record.seq).replace('-','')), len(str(second_record.seq).replace('-',''))]
if lengths.index(min(lengths)) == 0: # If both sequences have the same length the PDB sequence will be taken as the shortest
print 'PDB sequence has the shortest length'
else:
print 'Uniport sequence has the shortes length'
idenities = 0
for i,v in enumerate(first_record.seq):
if v == '-':
pass
#print i,v, second_record.seq[i]
if v == second_record.seq[i]:
idenities +=1
#print i,v, second_record.seq[i], idenities
print 'Sequence Idenity = %.2f percent' % (100.0*(idenities/min(lengths)))
to pass the arguments to the class use:
with open('input_file.txt', 'r') as infile:
next(infile)
next(infile) # Going by your input file
for line in infile:
line = line.split()
a.get_seq(segs[0]+'.pdb',segs[1]+'.fasta')
It might be something like this; a repeatable example (e.g., with short files posted on-line) would help...
library(Biostrings)
pdb = readAAStringSet("pdb.fasta")
uniprot = readAAStringSet("uniprot.fasta")
to input all sequences into two objects. pairwiseAlignment accepts a vector as first (query) argument, so if you were wanting to align all pdb against all uniprot pre-allocate a result matrix
pids = matrix(numeric(), length(uniprot), length(pdb),
dimnames=list(names(uniprot), names(pdb)))
and then do the calculations
for (i in seq_along(uniprot)) {
globalAlignment = pairwiseAlignment(pdb, uniprot[i])
pids[i,] = pid(globalAlignment)
}

Resources