-
Notifications
You must be signed in to change notification settings - Fork 0
/
LipReading.py
201 lines (178 loc) · 9.44 KB
/
LipReading.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
#%%
import sys
sys.path.append('/home/a.chernov/anaconda3/lib/python3.5/site-packages')
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from config import *
from alphabet import Alphabet
from utilities import load_to_cuda
def get_word(seq): # seq-числаf
#print(seq)
alphabet=Alphabet()
s=""
if len(seq)==0:
return s
for el in seq:
#print("el:",el.data)
if(el!=34):#хардкод
s+=alphabet.index2ch(el)
return s
class EncoderRNN(nn.Module):
def __init__(self):
super(EncoderRNN, self).__init__()
self.conv1 = nn.Conv2d(in_channels=5, out_channels=96, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
self.conv2 = nn.Conv2d(in_channels=96, out_channels=256, kernel_size=(3, 3), padding=1, stride=(2, 2))
self.conv3 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=(3, 3), padding=1)
self.conv4 = nn.Conv2d(in_channels=512, out_channels=512, kernel_size=(3, 3), padding=1)
self.conv5 = nn.Conv2d(in_channels=512, out_channels=512, kernel_size=(3, 3), padding=1)
self.fc6 = nn.Linear(32768, 512) # 512*8*8=32768 перейдет в 512
# batch norm for CNN
self.batchNorm1 = nn.BatchNorm2d(96)
self.batchNorm2 = nn.BatchNorm2d(256)
#dropout
self.dropout1 = nn.Dropout(0.1)
self.dropout2 = nn.Dropout(0.1)
self.lstm1=nn.LSTM(512,256,num_layers=3,batch_first=True)
def forward(self,x):
first_dim=x.shape[0]
second_dim=x.shape[1]
# print("x",x.shape)
# print("f",first_dim,"s",second_dim)
x=x.view(x.shape[0]*x.shape[1],5,120,120)
x = F.relu(self.conv1(x))
x = F.max_pool2d(x, kernel_size=(3, 3), stride=2, padding=1)
x = self.batchNorm1(x)
# 2
x = F.relu(self.conv2(x))
x = F.max_pool2d(x, kernel_size=(3, 3), stride=2, padding=1)
x = self.batchNorm2(x)
# 3
x = F.relu(self.conv3(x))
x = self.dropout1(x)
# 4
x = F.relu(self.conv4(x))
x = self.dropout2(x)
# 5
x = F.relu(self.conv5(x))
x = F.max_pool2d(x, kernel_size=(3, 3), stride=2, padding=1)
# 6
x = x.view(x.shape[0],32768)
x = self.fc6(x) # должна ли быть функция актвации для последнего слоя?
x = x.view(first_dim,second_dim,512)# меняем местами first и second, так как в lstm первая это seq_len, вторая - batch
h = load_to_cuda(Variable(torch.zeros(3,x.shape[0],256)))
c = load_to_cuda(Variable(torch.zeros(3,x.shape[0],256)))
self.lstm1.flatten_parameters()
output, hidden = self.lstm1(x,(h,c))
#self.lstm1.flatten_parameters()
hidden=list(hidden)
hidden[0]=hidden[0].view(hidden[0].shape[1],hidden[0].shape[0],-1)
hidden[1]=hidden[1].view(hidden[1].shape[1],hidden[1].shape[0],-1)
return output,hidden
class DecoderRNN(nn.Module):
def __init__(self):
super(DecoderRNN, self).__init__()
# LSTM
self.hidden_size=256
self.embedding = nn.Embedding(48, self.hidden_size)
self.lstm1=nn.LSTMCell(self.hidden_size,self.hidden_size)
self.lstm2=nn.LSTMCell(self.hidden_size,self.hidden_size)
self.lstm3=nn.LSTMCell(self.hidden_size,self.hidden_size)
# attention
self.att_fc1=nn.Linear(self.hidden_size,self.hidden_size)
self.att_fc2=nn.Linear(self.hidden_size,self.hidden_size)
self.att_fc3=nn.Linear(self.hidden_size,self.hidden_size)
self.att_vector = load_to_cuda(Variable(torch.randn(1,self.hidden_size),requires_grad=True))
self.att_W = load_to_cuda(Variable(torch.randn(self.hidden_size,self.hidden_size), requires_grad=True))
self.att_V = load_to_cuda(Variable(torch.randn(self.hidden_size,self.hidden_size), requires_grad=True))
self.att_b = load_to_cuda(Variable(torch.randn(self.hidden_size,1), requires_grad=True))
#MLP
self.MLP_hidden_size=256
self.MLP_fc1 = nn.Linear(2*self.MLP_hidden_size,self.MLP_hidden_size)
self.MLP_fc2 = nn.Linear(self.MLP_hidden_size,self.MLP_hidden_size)
self.MLP_fc3=nn.Linear(self.MLP_hidden_size,48)
def forward(self,Y,h,c, outEncoder,teacher_force):# Y это кол-во символов умножить на 256
if (np.random.rand()>teacher_force):
seq_len=Y.shape[0]-1
output_decoder= load_to_cuda(torch.autograd.Variable(torch.zeros(seq_len, h.shape[1], 48)))
Y = self.embedding(Y)
for i in range(len(Y)-1): # -1 так как sos не учитывем в criterion
h[0],c[0] = self.lstm1(Y[i],(h[0].clone(),c[0].clone()))
h[1],c[1] = self.lstm2(h[0].clone(),(h[1].clone(),c[1].clone()))
h[2],c[2] = self.lstm3(h[1].clone(),(h[2].clone(),c[2].clone()))
h2=h[2].clone()
context = self.attention(h2, outEncoder,BATCH_SIZE)
context = torch.bmm( context,outEncoder.view(outEncoder.shape[1],outEncoder.shape[0],-1) )
# print("context",context.shape) # torch sueeze
output_decoder[i] = self.MLP(torch.cat( (h2,torch.squeeze(context,1)) ,1 ))
else:
seq_len=Y.shape[0]-1
output_decoder= load_to_cuda(torch.autograd.Variable(torch.zeros(seq_len, h.shape[1], 48)))
alphabet = Alphabet()
Y_cur = self.embedding( load_to_cuda(Variable(torch.LongTensor([alphabet.ch2index('<sos>')]))) ).view(1,self.hidden_size)
for i in range(seq_len-1):
Y_cur=Y_cur.expand(BATCH_SIZE,self.hidden_size)
h[0],c[0] = self.lstm1(Y_cur,(h[0].clone(),c[0].clone()))
h[1],c[1] = self.lstm2(h[0].clone(),(h[1].clone(),c[1].clone()))
h[2],c[2] = self.lstm3(h[1].clone(),(h[2].clone(),c[2].clone()))
h2 = h[2].clone()
context = self.attention(h2, outEncoder,BATCH_SIZE)
context = torch.bmm( context,outEncoder.view(outEncoder.shape[1],outEncoder.shape[0],-1) )
output_decoder[i] = self.MLP(torch.cat( (h2,torch.squeeze(context,1)) ,1 ))
argmax = torch.max(output_decoder[i][0],dim=0)
Y_cur=self.embedding( Variable(load_to_cuda(torch.LongTensor([argmax[1][0].data[0]]))) ).view(1,self.hidden_size)
return output_decoder
def evaluate(self,h,c,outEncoder,max_len=-1): # sos в return быть не должно
# h = load_to_cuda(torch.squeeze(h0.clone(),0))
# c = load_to_cuda(torch.squeeze(c0.clone(),0))
h = h.view(h.shape[1],h.shape[0],-1).clone()
c = c.view(c.shape[1],c.shape[0],-1).clone()
if max_len==-1:
seq_len = 50# максимальная длина
else:
seq_len=max_len
result = load_to_cuda(torch.FloatTensor(seq_len,1,48).zero_())
if (len(outEncoder.shape))!=3:
print("размерность encoderOut неправильная")
return result, result[0], False
alphabet = Alphabet()
listArgmax=[]# буквы, которые выдал
Y_cur = self.embedding( load_to_cuda(Variable(torch.LongTensor([alphabet.ch2index('<sos>')]))) ).view(1,self.hidden_size)
for i in range(seq_len-1):
h[0],c[0] = self.lstm1(Y_cur,(h[0].clone(),c[0].clone()))
h[1],c[1] = self.lstm2(h[0],(h[1].clone(),c[1].clone()))
h[2],c[2] = self.lstm3(h[1].clone(),(h[2].clone(),c[2].clone()))
context = self.attention(h[2].clone(), outEncoder.view(outEncoder.shape[1],outEncoder.shape[0],-1),1)
context = torch.bmm(context,outEncoder)
char = self.MLP( torch.cat( (h[2].clone(),context.view(1,self.hidden_size)),1 ) )
result[i] = char.data
argmax = torch.max(result[i][0],dim=0)
listArgmax.append(argmax[1][0])
if argmax[1][0] == alphabet.ch2index('<eos>'):
seq_len=i+1
break
Y_cur=self.embedding( Variable(load_to_cuda(torch.LongTensor([argmax[1][0]]))) ).view(1,self.hidden_size)
word=get_word(torch.LongTensor(listArgmax))
# print("res:",word)
# with open('log2/result.txt', 'a') as f:
# f.write("res:"+word+'\n')
# print("res:",word)
return result[:seq_len],word, True
def MLP(self,v):
v = F.relu(self.MLP_fc1(v))
v = F.relu(self.MLP_fc2(v))
v = self.MLP_fc3(v)
return v
def attention(self,hidden, outEncoder,batch):# то есть hidden это 1*1*256; outEncoder это 10*1*256, если batch_size=1
outEnSize = outEncoder.shape[0]
hidden =hidden.view(hidden.shape[0],self.hidden_size,1)
hidden= hidden.expand(-1,-1,outEnSize)
# hidden=hidden.contiguous().view(hidden.shape[1],self.hidden_size,hidden.shape[0])
# print(hidden.shape)
WS = torch.bmm(self.att_W.expand(batch,-1,-1),hidden)
VOut = torch.bmm(self.att_V.expand(batch,-1,-1),outEncoder.view(batch,self.hidden_size,outEnSize))
E = F.tanh(WS + VOut + self.att_b.expand(batch,-1,outEnSize))
E = torch.bmm(self.att_vector.expand(batch,-1,-1),E)
return F.softmax(E, dim=2)