You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I wrote the first common FER code, but when running it, it shows error that : AttributeError: 'torch.Size' object has no attribute 'as_list'.
How to solve the problem, please? and the code is all attached in the following:
`#!/usr/bin/env python3
-- coding: utf-8 --
"""
Created on Sun Mar 19 16:38:34 2023
The code do high order FER in identity-disentangled FER following the paper "Learning a Facial Expression Embedding Disentangled from Identity"
This is the first test, which use the idea discussed with Pro. WangSF in which f2, and f3 are the iteratively element-wise product of f1 that is
produced from the 512-D V(exp). @author: yi huo
"""
#Learning a Facial Expression Embedding Disentangled From Identity
#https://fuxivirtualhuman.github.io/
import argparse
import tensorflow
tf_version = int(tensorflow.version.split(".")[0])
if tf_version == 1:
from keras.models import Model
from keras.layers import Activation
from keras.layers import BatchNormalization
from keras.layers import Concatenate
from keras.layers import Conv2D
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import GlobalAveragePooling2D
from keras.layers import Input
from keras.layers import Lambda
from keras.layers import MaxPooling2D
from keras.layers import add
from keras import backend as K
else:
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import Concatenate
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import GlobalAveragePooling2D
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Lambda
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import add
from tensorflow.keras import backend as K
import tensorflow.keras
import torchvision
import torchvision.transforms as transforms
from fer import FER2013
from deepface.basemodels import Facenet512
from deepface import DeepFace
import os
import sys
from torch import nn
import torch
import torch.optim as optim
class SequentialModule(tensorflow.Module):
def init(self, name=None):
super().init(name=name)
self.model=Facenet512.loadModel(url = 'https://github.com/serengil/deepface_models/releases/download/v1.0/facenet512_weights.h5')
self.dense_512to256 = Dense(in_features=512, out_features=256)
self.dense_256to128 = Dense(in_features=256, out_features=128)
self.dense_128to16 = Dense(in_features=128, out_features=16)
self.dense_48to16 = Dense(in_features=48, out_features=16)
self.classifier = Dense(in_features=16, out_features=7) #classifed to 7 categories. ?how to know which data to which label?
def call(self, x):
x=faceEmbedCommon=self.model(x)
x = self.dense_512to256(x)
x = self.dense_256to128(x)
f1 = self.dense_128to16(x)
f2 = tensorflow.multiply(f1, f1)
f3 = tensorflow.multiply(f1, f2)
fList=list()
fList.append(f1)
fList.append(f2)
fList.append(f3)
Fk=tensorflow.concat(fList, 0)
#add linear layer from 48D to 16D.
E_exp=self.dense_48to16(Fk)
out = self.classifier(E_exp)
return out #the final result computed by the model.
You have made a model!
my_model = SequentialModule(name="the_model")
#3. define loss function
criterion=tensorflow.keras.losses.CategoricalCrossentropy()
optimizer = tensorflow.keras.optimizers.Adam()
#4. Train the network,pytorch?
for epoch in range(2):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data #128 images, 128 labels, since the batch size is set to be 128. The color channel has only one, and valued from 0.0-1.0.
print(inputs)
print(labels)
# zero the parameter gradients
#optimizer.zero_grad() #?
# forward + backward + optimize
outputs = my_model(inputs)
loss = criterion(outputs, labels) #here know which data correspond to which label.
loss.backward()
optimizer.step()
print("test")
# print statistics
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')
running_loss = 0.0
I wrote the first common FER code, but when running it, it shows error that : AttributeError: 'torch.Size' object has no attribute 'as_list'.
How to solve the problem, please? and the code is all attached in the following:
`#!/usr/bin/env python3
-- coding: utf-8 --
"""
Created on Sun Mar 19 16:38:34 2023
The code do high order FER in identity-disentangled FER following the paper "Learning a Facial Expression Embedding Disentangled from Identity"
This is the first test, which use the idea discussed with Pro. WangSF in which f2, and f3 are the iteratively element-wise product of f1 that is
produced from the 512-D V(exp).
@author: yi huo
"""
#Learning a Facial Expression Embedding Disentangled From Identity
#https://fuxivirtualhuman.github.io/
import argparse
import tensorflow
tf_version = int(tensorflow.version.split(".")[0])
if tf_version == 1:
from keras.models import Model
from keras.layers import Activation
from keras.layers import BatchNormalization
from keras.layers import Concatenate
from keras.layers import Conv2D
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import GlobalAveragePooling2D
from keras.layers import Input
from keras.layers import Lambda
from keras.layers import MaxPooling2D
from keras.layers import add
from keras import backend as K
else:
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import Concatenate
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import GlobalAveragePooling2D
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Lambda
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import add
from tensorflow.keras import backend as K
import tensorflow.keras
import torchvision
import torchvision.transforms as transforms
from fer import FER2013
from deepface.basemodels import Facenet512
from deepface import DeepFace
import os
import sys
from torch import nn
import torch
import torch.optim as optim
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#0. initialize.
parser = argparse.ArgumentParser(description='PyTorch Fer2013 CNN Training')
parser.add_argument('--bs', default=128, type=int, help='batch size')
opt = parser.parse_args()
#1. Load and normalize data? here,4.8 start with.pytorch?
transform_train = transforms.Compose([ #add by HY, compose several tranforms together.
transforms.RandomCrop(44), #crop to 44*44 image
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
])
trainset = FER2013(split = 'Training', transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=opt.bs, shuffle=True, num_workers=1)
#2. define network
#TensorFlow
class Dense(tensorflow.Module):
def init(self, in_features, out_features, name=None):
super().init(name=name)
self.w = tensorflow.Variable(
tensorflow.random.normal([in_features, out_features]), name='w')
self.b = tensorflow.Variable(tensorflow.zeros([out_features]), name='b')
def call(self, x):
y = tensorflow.matmul(x, self.w) + self.b
return tensorflow.nn.relu(y)
class SequentialModule(tensorflow.Module):
def init(self, name=None):
super().init(name=name)
self.model=Facenet512.loadModel(url = 'https://github.com/serengil/deepface_models/releases/download/v1.0/facenet512_weights.h5')
self.dense_512to256 = Dense(in_features=512, out_features=256)
self.dense_256to128 = Dense(in_features=256, out_features=128)
self.dense_128to16 = Dense(in_features=128, out_features=16)
self.dense_48to16 = Dense(in_features=48, out_features=16)
self.classifier = Dense(in_features=16, out_features=7) #classifed to 7 categories. ?how to know which data to which label?
def call(self, x):
x=faceEmbedCommon=self.model(x)
x = self.dense_512to256(x)
x = self.dense_256to128(x)
f1 = self.dense_128to16(x)
f2 = tensorflow.multiply(f1, f1)
f3 = tensorflow.multiply(f1, f2)
fList=list()
fList.append(f1)
fList.append(f2)
fList.append(f3)
Fk=tensorflow.concat(fList, 0)
#add linear layer from 48D to 16D.
E_exp=self.dense_48to16(Fk)
out = self.classifier(E_exp)
return out #the final result computed by the model.
You have made a model!
my_model = SequentialModule(name="the_model")
#3. define loss function
criterion=tensorflow.keras.losses.CategoricalCrossentropy()
optimizer = tensorflow.keras.optimizers.Adam()
#4. Train the network,pytorch?
for epoch in range(2):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data #128 images, 128 labels, since the batch size is set to be 128. The color channel has only one, and valued from 0.0-1.0.
print(inputs)
print(labels)
# zero the parameter gradients
#optimizer.zero_grad() #?
# forward + backward + optimize
outputs = my_model(inputs)
loss = criterion(outputs, labels) #here know which data correspond to which label.
loss.backward()
optimizer.step()
print("test")
# print statistics
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 2000:.3f}')
running_loss = 0.0
print('Finished Training')
#Let’s quickly save our trained model:
PATH = './identityDisFER_net.pth'
torch.save(SequentialModule.state_dict(), PATH)
`
The text was updated successfully, but these errors were encountered: