A simple toy ResNet model and its implementationAcademic implementation of artificial neural networkSimple...
Getting a UK passport renewed when you have dual nationality and a different name in your second country?
Why can a 352GB NumPy ndarray be used on an 8GB memory macOS computer?
What's the rationale behind the objections to these measures against human trafficking?
Overfitting and Underfitting
Longest Jewish year
What to do when being responsible for data protection in your lab, yet advice is ignored?
It took me a lot of time to make this, pls like. (YouTube Comments #1)
Pendulum Rotation
Does Windows 10's telemetry include sending *.doc files if Word crashed?
Why zero tolerance on nudity in space?
Why did Jodrell Bank assist the Soviet Union to collect data from their spacecraft in the mid 1960's?
Word or phrase for showing great skill at something without formal training in it
Integral inequality of length of curve
Why is button three on trumpet almost never used alone?
Early credit roll before the end of the film
Eww, those bytes are gross
High pressure canisters of air as gun-less projectiles
Can we use the stored gravitational potential energy of a building to produce power?
What is the wife of a henpecked husband called?
Everyone is beautiful
What to do if authors don't respond to my serious concerns about their paper?
Quenching swords in dragon blood; why?
Can a person refuse a presidential pardon?
Issues with new Macs: Hardware makes them difficult for me to use. What options might be available in the future?
A simple toy ResNet model and its implementation
Academic implementation of artificial neural networkSimple Java Neural NetworkA simple fully connected ANN moduleTensorflow implementation of the Thomson modelNeural Network in SwiftLow accuracy of LSTM model tensorflowCode for Training a Handwriting Recognition ModelSimple neural network implementation in PythonSimple Neural Network from scratch using NumPy (Python)Flower Type Recognition CNN (Tensorflow)
$begingroup$
I want to understand how resnet works also called us residual networks and I understand it better when I code one myself. I tried to find a simple implementation of resnet in the web but most I found were complicated and all of it used convolutional neural networks especially in python with keras. Because of this I have to code a resnet myself and used the smallest dataset available (that is iris dataset) with dense layers. I am releasing my full code here but I am not fully sure about my resnet implementation. I also included a mlp model to do a comparison study with my resnet implementation. Some where I read that resnet model gives higher accuracy with lesser parameters comparing to a vanilla neural net model. In my implementation also resnet model gave better mean accuracy than the vanilla model.
Please review my code.
used libraries: keras, tensorflow and sckit-learn
"""
A simple toy resnet model and its implementation
Requirements
============
python
keras
tensorflow
sckit-learn
"Added a mlp model also to this code for comparison study with resnet"
"""
from sklearn.model_selection import StratifiedKFold
from sklearn import datasets
from keras.utils import to_categorical
from keras.models import Sequential,Model
from keras.layers import Dense,Input,Add,Activation
import tensorflow as tf
import numpy as np
#Set the seeds
seed=111
tf.set_random_seed(seed)
np.random.seed(seed)
#Load iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
y=to_categorical(y)
input_shape=X.shape[1]
output_shape=y.shape[1]
"""
Training on iris dataset with a vanilla mlp model.
"""
print("Training mlp with cross validationn")
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)
j=False
cvscores = []
for train, test in kfold.split(X, y.argmax(1)):
#mlp model
model = Sequential()
model.add(Dense(4, input_shape=(input_shape,),activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(output_shape,activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
if j==False:
model.summary()
j=True
model.fit(X[train],y[train],batch_size=10,verbose=0,epochs=100)
scores = model.evaluate(X[test], y[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("Average MLP Score:")
mlp_score=[np.mean(cvscores),np.std(cvscores)]
print("%.2f%% (+/- %.2f%%)" % (mlp_score[0],mlp_score[1] ))
ml=len(model.layers)
mp=model.count_params()
del model
"""
Training on iris dataset with a resnet model.
"""
print("Training resnet with cross validationn")
def resnet_block(x):
t=x.get_shape().as_list()[1]
i=x
x=Dense(3,activation='relu')(i)
x=Dense(4,activation='relu')(x)
x=Dense(t)(x)
x=Add()([x,i])
x=Activation('relu')(x)
return x
j=False
cvscores = []
for train, test in kfold.split(X, y.argmax(1)):
i=Input(shape=(input_shape,))
x=Dense(2,activation='relu')(i)
x=resnet_block(x)
x=resnet_block(x)
x=resnet_block(x)
o=Dense(output_shape,activation='softmax')(x)
model=Model(i,o)
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
if j==False:
model.summary()
j=True
model.fit(X[train],y[train],batch_size=10,verbose=0,epochs=100)
scores = model.evaluate(X[test], y[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("Average Resnet Score:")
resnet_score=[np.mean(cvscores),np.std(cvscores)]
print("%.2f%% (+/- %.2f%%)" % (resnet_score[0],resnet_score[1] ))
rl=len(model.layers)
rp=model.count_params()
print("nn")
print("Complete result: n")
print("MLP")
print('Layers:'+str(ml)+' Parameters'+str(mp))
print('Score: ')
print("%.2f%% (+/- %.2f%%)" % (mlp_score[0],mlp_score[1] ))
print("nResnet")
print('Layers:'+str(rl)+' Parameters'+str(rp))
print('Score: ')
print("%.2f%% (+/- %.2f%%)" % (resnet_score[0],resnet_score[1] ))
python ai machine-learning neural-network
$endgroup$
add a comment |
$begingroup$
I want to understand how resnet works also called us residual networks and I understand it better when I code one myself. I tried to find a simple implementation of resnet in the web but most I found were complicated and all of it used convolutional neural networks especially in python with keras. Because of this I have to code a resnet myself and used the smallest dataset available (that is iris dataset) with dense layers. I am releasing my full code here but I am not fully sure about my resnet implementation. I also included a mlp model to do a comparison study with my resnet implementation. Some where I read that resnet model gives higher accuracy with lesser parameters comparing to a vanilla neural net model. In my implementation also resnet model gave better mean accuracy than the vanilla model.
Please review my code.
used libraries: keras, tensorflow and sckit-learn
"""
A simple toy resnet model and its implementation
Requirements
============
python
keras
tensorflow
sckit-learn
"Added a mlp model also to this code for comparison study with resnet"
"""
from sklearn.model_selection import StratifiedKFold
from sklearn import datasets
from keras.utils import to_categorical
from keras.models import Sequential,Model
from keras.layers import Dense,Input,Add,Activation
import tensorflow as tf
import numpy as np
#Set the seeds
seed=111
tf.set_random_seed(seed)
np.random.seed(seed)
#Load iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
y=to_categorical(y)
input_shape=X.shape[1]
output_shape=y.shape[1]
"""
Training on iris dataset with a vanilla mlp model.
"""
print("Training mlp with cross validationn")
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)
j=False
cvscores = []
for train, test in kfold.split(X, y.argmax(1)):
#mlp model
model = Sequential()
model.add(Dense(4, input_shape=(input_shape,),activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(output_shape,activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
if j==False:
model.summary()
j=True
model.fit(X[train],y[train],batch_size=10,verbose=0,epochs=100)
scores = model.evaluate(X[test], y[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("Average MLP Score:")
mlp_score=[np.mean(cvscores),np.std(cvscores)]
print("%.2f%% (+/- %.2f%%)" % (mlp_score[0],mlp_score[1] ))
ml=len(model.layers)
mp=model.count_params()
del model
"""
Training on iris dataset with a resnet model.
"""
print("Training resnet with cross validationn")
def resnet_block(x):
t=x.get_shape().as_list()[1]
i=x
x=Dense(3,activation='relu')(i)
x=Dense(4,activation='relu')(x)
x=Dense(t)(x)
x=Add()([x,i])
x=Activation('relu')(x)
return x
j=False
cvscores = []
for train, test in kfold.split(X, y.argmax(1)):
i=Input(shape=(input_shape,))
x=Dense(2,activation='relu')(i)
x=resnet_block(x)
x=resnet_block(x)
x=resnet_block(x)
o=Dense(output_shape,activation='softmax')(x)
model=Model(i,o)
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
if j==False:
model.summary()
j=True
model.fit(X[train],y[train],batch_size=10,verbose=0,epochs=100)
scores = model.evaluate(X[test], y[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("Average Resnet Score:")
resnet_score=[np.mean(cvscores),np.std(cvscores)]
print("%.2f%% (+/- %.2f%%)" % (resnet_score[0],resnet_score[1] ))
rl=len(model.layers)
rp=model.count_params()
print("nn")
print("Complete result: n")
print("MLP")
print('Layers:'+str(ml)+' Parameters'+str(mp))
print('Score: ')
print("%.2f%% (+/- %.2f%%)" % (mlp_score[0],mlp_score[1] ))
print("nResnet")
print('Layers:'+str(rl)+' Parameters'+str(rp))
print('Score: ')
print("%.2f%% (+/- %.2f%%)" % (resnet_score[0],resnet_score[1] ))
python ai machine-learning neural-network
$endgroup$
add a comment |
$begingroup$
I want to understand how resnet works also called us residual networks and I understand it better when I code one myself. I tried to find a simple implementation of resnet in the web but most I found were complicated and all of it used convolutional neural networks especially in python with keras. Because of this I have to code a resnet myself and used the smallest dataset available (that is iris dataset) with dense layers. I am releasing my full code here but I am not fully sure about my resnet implementation. I also included a mlp model to do a comparison study with my resnet implementation. Some where I read that resnet model gives higher accuracy with lesser parameters comparing to a vanilla neural net model. In my implementation also resnet model gave better mean accuracy than the vanilla model.
Please review my code.
used libraries: keras, tensorflow and sckit-learn
"""
A simple toy resnet model and its implementation
Requirements
============
python
keras
tensorflow
sckit-learn
"Added a mlp model also to this code for comparison study with resnet"
"""
from sklearn.model_selection import StratifiedKFold
from sklearn import datasets
from keras.utils import to_categorical
from keras.models import Sequential,Model
from keras.layers import Dense,Input,Add,Activation
import tensorflow as tf
import numpy as np
#Set the seeds
seed=111
tf.set_random_seed(seed)
np.random.seed(seed)
#Load iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
y=to_categorical(y)
input_shape=X.shape[1]
output_shape=y.shape[1]
"""
Training on iris dataset with a vanilla mlp model.
"""
print("Training mlp with cross validationn")
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)
j=False
cvscores = []
for train, test in kfold.split(X, y.argmax(1)):
#mlp model
model = Sequential()
model.add(Dense(4, input_shape=(input_shape,),activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(output_shape,activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
if j==False:
model.summary()
j=True
model.fit(X[train],y[train],batch_size=10,verbose=0,epochs=100)
scores = model.evaluate(X[test], y[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("Average MLP Score:")
mlp_score=[np.mean(cvscores),np.std(cvscores)]
print("%.2f%% (+/- %.2f%%)" % (mlp_score[0],mlp_score[1] ))
ml=len(model.layers)
mp=model.count_params()
del model
"""
Training on iris dataset with a resnet model.
"""
print("Training resnet with cross validationn")
def resnet_block(x):
t=x.get_shape().as_list()[1]
i=x
x=Dense(3,activation='relu')(i)
x=Dense(4,activation='relu')(x)
x=Dense(t)(x)
x=Add()([x,i])
x=Activation('relu')(x)
return x
j=False
cvscores = []
for train, test in kfold.split(X, y.argmax(1)):
i=Input(shape=(input_shape,))
x=Dense(2,activation='relu')(i)
x=resnet_block(x)
x=resnet_block(x)
x=resnet_block(x)
o=Dense(output_shape,activation='softmax')(x)
model=Model(i,o)
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
if j==False:
model.summary()
j=True
model.fit(X[train],y[train],batch_size=10,verbose=0,epochs=100)
scores = model.evaluate(X[test], y[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("Average Resnet Score:")
resnet_score=[np.mean(cvscores),np.std(cvscores)]
print("%.2f%% (+/- %.2f%%)" % (resnet_score[0],resnet_score[1] ))
rl=len(model.layers)
rp=model.count_params()
print("nn")
print("Complete result: n")
print("MLP")
print('Layers:'+str(ml)+' Parameters'+str(mp))
print('Score: ')
print("%.2f%% (+/- %.2f%%)" % (mlp_score[0],mlp_score[1] ))
print("nResnet")
print('Layers:'+str(rl)+' Parameters'+str(rp))
print('Score: ')
print("%.2f%% (+/- %.2f%%)" % (resnet_score[0],resnet_score[1] ))
python ai machine-learning neural-network
$endgroup$
I want to understand how resnet works also called us residual networks and I understand it better when I code one myself. I tried to find a simple implementation of resnet in the web but most I found were complicated and all of it used convolutional neural networks especially in python with keras. Because of this I have to code a resnet myself and used the smallest dataset available (that is iris dataset) with dense layers. I am releasing my full code here but I am not fully sure about my resnet implementation. I also included a mlp model to do a comparison study with my resnet implementation. Some where I read that resnet model gives higher accuracy with lesser parameters comparing to a vanilla neural net model. In my implementation also resnet model gave better mean accuracy than the vanilla model.
Please review my code.
used libraries: keras, tensorflow and sckit-learn
"""
A simple toy resnet model and its implementation
Requirements
============
python
keras
tensorflow
sckit-learn
"Added a mlp model also to this code for comparison study with resnet"
"""
from sklearn.model_selection import StratifiedKFold
from sklearn import datasets
from keras.utils import to_categorical
from keras.models import Sequential,Model
from keras.layers import Dense,Input,Add,Activation
import tensorflow as tf
import numpy as np
#Set the seeds
seed=111
tf.set_random_seed(seed)
np.random.seed(seed)
#Load iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
y=to_categorical(y)
input_shape=X.shape[1]
output_shape=y.shape[1]
"""
Training on iris dataset with a vanilla mlp model.
"""
print("Training mlp with cross validationn")
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)
j=False
cvscores = []
for train, test in kfold.split(X, y.argmax(1)):
#mlp model
model = Sequential()
model.add(Dense(4, input_shape=(input_shape,),activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(output_shape,activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
if j==False:
model.summary()
j=True
model.fit(X[train],y[train],batch_size=10,verbose=0,epochs=100)
scores = model.evaluate(X[test], y[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("Average MLP Score:")
mlp_score=[np.mean(cvscores),np.std(cvscores)]
print("%.2f%% (+/- %.2f%%)" % (mlp_score[0],mlp_score[1] ))
ml=len(model.layers)
mp=model.count_params()
del model
"""
Training on iris dataset with a resnet model.
"""
print("Training resnet with cross validationn")
def resnet_block(x):
t=x.get_shape().as_list()[1]
i=x
x=Dense(3,activation='relu')(i)
x=Dense(4,activation='relu')(x)
x=Dense(t)(x)
x=Add()([x,i])
x=Activation('relu')(x)
return x
j=False
cvscores = []
for train, test in kfold.split(X, y.argmax(1)):
i=Input(shape=(input_shape,))
x=Dense(2,activation='relu')(i)
x=resnet_block(x)
x=resnet_block(x)
x=resnet_block(x)
o=Dense(output_shape,activation='softmax')(x)
model=Model(i,o)
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
if j==False:
model.summary()
j=True
model.fit(X[train],y[train],batch_size=10,verbose=0,epochs=100)
scores = model.evaluate(X[test], y[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("Average Resnet Score:")
resnet_score=[np.mean(cvscores),np.std(cvscores)]
print("%.2f%% (+/- %.2f%%)" % (resnet_score[0],resnet_score[1] ))
rl=len(model.layers)
rp=model.count_params()
print("nn")
print("Complete result: n")
print("MLP")
print('Layers:'+str(ml)+' Parameters'+str(mp))
print('Score: ')
print("%.2f%% (+/- %.2f%%)" % (mlp_score[0],mlp_score[1] ))
print("nResnet")
print('Layers:'+str(rl)+' Parameters'+str(rp))
print('Score: ')
print("%.2f%% (+/- %.2f%%)" % (resnet_score[0],resnet_score[1] ))
python ai machine-learning neural-network
python ai machine-learning neural-network
edited 4 mins ago
Eka
asked Feb 13 at 12:25
EkaEka
202411
202411
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213371%2fa-simple-toy-resnet-model-and-its-implementation%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213371%2fa-simple-toy-resnet-model-and-its-implementation%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown