数据特征提取

在上文处理好的数据集上利用AlexNet和word2vec提取数据特征

test_hdf5_librosa.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import h5py
import numpy as np
from torchvision import models, transforms
import librosa
import os
from torch.utils.data import Dataset, DataLoader
from PIL import Image
import torch.nn as nn
import torch
from torch.autograd import Variable
import gensim


# -----------------prepare for extract feature--------------------------


# -----------------get Alexnet model-------------------------
def getAlexNet(DOWNLOAD=True):
alexnet = models.alexnet(pretrained=DOWNLOAD)
return alexnet


# -----------------revise the AlexNet class--------------------------
class AlexNet(nn.Module):
def __init__(self):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(64, 192, kernel_size=5, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(192, 384, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(384, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
)
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(256 * 6 * 6, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096)
)

def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), 256 * 6 * 6)
x = self.classifier(x)
return x


# -----------------create the dataset class--------------------------
class ImageDataset(Dataset):
def __init__(self, img_path, transform=None):
self.transform = transform
self.images = list(map(lambda x: os.path.join(img_path, x), os.listdir(img_path)))

def __getitem__(self, index):
image_file = self.images[index]
image = Image.open(image_file).convert('RGB')
if self.transform is not None:
image = self.transform(image)
return image

def __len__(self):
return len(self.images)


# -----------------create the dataloader--------------------------
def get_dataset(path, img_scale, batch_size):
transform = transforms.Compose([
transforms.Scale(img_scale),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])

dataset = ImageDataset(path, transform)
data_loader = DataLoader(dataset=dataset,
batch_size=batch_size,
shuffle=False,
drop_last=True)
return data_loader


# -----------------begin to extract feature--------------------------


def text_file(path, h5base, id, model):
finnal_matrix = None
with open(path + 'text.txt', 'r') as f:
texts = f.read()
text_list = texts.strip().split(" ")
for word in text_list:
try:
vec_word = model[word]
except:
vec_word = np.zeros(300)
vec_word = vec_word.reshape(300, 1)
if finnal_matrix is None:
finnal_matrix = vec_word
else:
finnal_matrix = np.concatenate((finnal_matrix, vec_word), axis=1)
h5base.create_dataset(id, data=finnal_matrix)
return


# -----------------get image feature and store--------------------------


def image_file(path, h5base, id, model):
"""
:param path: file path
:param h5base: store 12 * 4096 data
:return:
"""
try:
img_scale = 224
batch_size = 12
data_loader = get_dataset(path, img_scale, batch_size)
for _, data in enumerate(data_loader):
# use model to extract feature
features = model(Variable(data))
# save features
h5base.create_dataset(id, data=features.data.numpy())
except:
print(id + "在图像上出现了有问题!")
return


# -----------------get audio feature and store--------------------------


def audio_file(path, h5base, id):
"""
:param path: file path
:param h5base: store 6 * 512 data
:return:
"""
try:
finnal_matrix = None
use_audio = ["1.mp3", "2.mp3", "3.mp3", "4.mp3", "5.mp3", "6.mp3"]
files = librosa.util.find_files(path, recurse=False, ext='mp3')
for file in files:
file_list = file.split("/")
if file_list[-1] not in use_audio:
continue
y, sr = librosa.load(file)
D = librosa.stft(y, n_fft=1022)
vec_D = np.mean(D, axis=1, keepdims=True)
if finnal_matrix is None:
finnal_matrix = vec_D
else:
finnal_matrix = np.concatenate((finnal_matrix, vec_D), axis=1)
# judge final matrix shape
if finnal_matrix is None or finnal_matrix.shape != (512, 6):
print(id + "有问题!")
return

h5base.create_dataset(id, data=finnal_matrix)

except:
print(id + "在音频上出现了有问题!")

return


# -----------------get audio feature and store--------------------------


if __name__ == '__main__':
# some config variable
root_path = "./dataset1/"
DOWNLOAD = False
pre_train_weight_alexnet = "./alexnet-owt-4df8aa71.pth"

# create h5py file
restore_audio_file = h5py.File("dataset1_audio_feature.hdf5", "w")
restore_images_file = h5py.File("dataset1_images_feature.hdf5", "w")
restore_texts_file = h5py.File("dataset1_texts_feature.hdf5", "w")

# -----------------get Alexnet to extrat imgs features--------------------------
# if you alread download the weight, we can make DOWNLOAD = False
pre_alexnet = getAlexNet(DOWNLOAD)
pre_alexnet.load_state_dict(torch.load(pre_train_weight_alexnet))
pretrain_dict = pre_alexnet.state_dict()

alexnet = AlexNet()
alexnet_dict = alexnet.state_dict()
pretrained_dict = {k: v for k, v in pretrain_dict.items() if k in alexnet_dict}
# update the weight of new alexnet
alexnet_dict.update(pretrained_dict)
# load the new weight
alexnet.load_state_dict(alexnet_dict)

# -----------------get word2vec by Google to extrat texts features--------------------------
word2vec = gensim.models.KeyedVectors.load_word2vec_format("./GoogleNews-vectors-negative300.bin", binary=True)

# go to the dir and loop
dirs = os.listdir(root_path)
process = 0
total = len(dirs)
for dir in dirs:
audio_file(root_path + dir + "/audios/", restore_audio_file, dir)
image_file(root_path + dir + "/images/", restore_images_file, dir, alexnet)
text_file(root_path + dir + "/texts/", restore_texts_file, dir, word2vec)
process += 1
if process % (total // 10) == 0:
print("alread down")

print("Done!")