ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Hi,
I tried to execute a python script but I don't know how to initialize the self variable in python:
This is my code:
Code:
import tensorflow as tf
import numpy as np
import readers
import pre_precessing
from app_flag import FLAGS
from StackedAutoencoder import StackedAutoencoder
def write_and_encode(data_list, tfrecord_filename):
writer = tf.python_io.TFRecordWriter(tfrecord_filename)
for label, data_matrix in data_list:
example = tf.train.Example(features=tf.train.Features(
feature={
"label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),
"data_raw": tf.train.Feature(bytes_list=tf.train.BytesList(value=[data_matrix.tostring()]))
}
))
writer.write(example.SerializeToString())
writer.close()
def read_and_decode(tfrecord_filename):
reader = tf.TFRecordReader()
filename_queue = tf.train.string_input_producer([tfrecord_filename],)
_, serialized_example = reader.read(filename_queue)
feature = tf.parse_single_example(serialized_example,
features={
"label": tf.FixedLenFeature([], tf.int64),
"data_raw": tf.FixedLenFeature([], tf.string)
})
data = tf.decode_raw(feature["data_raw"], tf.float64)
data = tf.reshape(data, [FLAGS.image_rows, FLAGS.image_cols])
return data, feature["label"]
def train_input_fn():
tfrecord_file = "../resources/train_tfrecord"
dataset = tf.data.TFRecordDataset(tfrecord_file)
dataset = dataset.map(parser)
train_dataset = dataset.repeat(FLAGS.num_epochs).batch(FLAGS.batch_size)
train_iterator = train_dataset.make_one_shot_iterator()
features, labels = train_iterator.get_next()
return features, labels
def parser(record_line):
features = {
"label": tf.FixedLenFeature([], tf.int64),
"data_raw": tf.FixedLenFeature([], tf.string)
}
parsed = tf.parse_single_example(record_line, features=features)
label = tf.cast(parsed["label"], tf.int32) - 1
data = tf.decode_raw(parsed["data_raw"], tf.float64)
data = tf.reshape(data, [FLAGS.image_rows, FLAGS.image_cols])
data = tf.cast(data, tf.float32)
return data, label
def write_user_instances_to_tfrecord():
users = ["0"+str(i) for i in range(1, 10)]
users.extend([str(i) for i in range(10, 17)])
users.extend(["32", "40", "41", "42", "43", "49", "50", "51"])
instances = []
for user in users:
train_data = readers.read_user_files(user)
for label, instance in train_data.items():
instances.append((label, instance))
formalized_instances = pre_precessing.extend_to_maxsize(instances)
train_instances = formalized_instances[:100]
write_and_encode(train_instances, "../resources/train_tfrecord")
def main():
build_stacked_ae("../resources/train_tfrecord")
def build_stacked_ae(path):
"""
Build the stacked auto-encoder neural network, and evaluate its performance
:param path: Path to the genetic dataset
:return: Accuracy of classification of cell cycle phase.
"""
############### Stacked Auto-Encoders ##############
train=train_input_fn()
ae = StackedAutoencoder(train,5)
ae.create_autoencoder()
result = ae.evaluate_autoencoder()
return result[1] * 100
print("Accuracy: %.2f%%" % (result[1] * 100))
if __name__ == "__main__":
main()
The Stacked autoencoder function:
Code:
from __future__ import print_function
import keras
import numpy
from keras.models import Sequential
from keras.layers.core import *
from sklearn.model_selection import train_test_split
class StackedAutoencoder(object):
"""
Implementation of stacked autoencoder multi-class classifier using the Keras Python package.
This classifier is used to classify cells to cell cycle phases S, G1 or G2M.
"""
def __init__(self, features, labels, num_labels):
self.features = features
self.labels = labels
self.auto_encoder = None
self.encoding_dim = num_labels
# fix random seed for reproducibility
self.seed = 7
numpy.random.seed(7)
def create_autoencoder(self):
"""
Build the stacked auto-encoder using multiple hidden layers.
The stacked auto-encoder is then trained and weights are freezed afterwards.
A softmax classification layer is that appended to the last layer, replacing the input
re-constructed layer of the auto-encoder.
:return: Compiled classification neural network model.
"""
self.auto_encoder = Sequential()
self.auto_encoder.add(Dense(3000, activation='relu', input_dim=self.features.shape[1]))
self.auto_encoder.add(Dense(1000, activation='relu'))
self.auto_encoder.add(Dense(30, activation='relu'))
self.auto_encoder.add(Dense(3000, activation='relu'))
self.auto_encoder.add(Dense(self.features.shape[1], activation='sigmoid'))
self.auto_encoder.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
self.auto_encoder.fit(self.features, self.features,
epochs=10,
batch_size=5,
shuffle=True,
validation_split=0.33,
validation_data=None)
self.auto_encoder.layers.pop()
self.auto_encoder.add(Dense(self.encoding_dim, activation='softmax'))
self.auto_encoder.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
print(self.auto_encoder.summary())
# Freeze all weights after training the stacked auto-encoder and all the classification layer
for i in range(0, len(self.auto_encoder.layers)-1):
self.auto_encoder.layers[i].trainable = False
return self.auto_encoder
def evaluate_autoencoder(self):
"""
Fit the trained neural network and validate it using splitting the dataset to training and testing sets.
:return: Accuracy score of the classification.
"""
self.auto_encoder.fit(self.features, self.labels,
epochs=10,
batch_size=5,
shuffle=True)
X_train, X_test, Y_train, Y_test = train_test_split(self.features, self.labels, test_size=0.33, random_state=self.seed)
#predictions = self.auto_encoder.predict_classes(X_test)
#print(predictions)
#print(self.label_encoder.inverse_transform(predictions))
score = self.auto_encoder.evaluate(X_test, Y_test, batch_size=5, verbose=1)
return score
The error is:
Using TensorFlow backend.
Traceback (most recent call last):
File "Classifier.py", line 110, in <module>
main()
File "Classifier.py", line 91, in main
build_stacked_ae("../resources/train_tfrecord")
File "Classifier.py", line 101, in build_stacked_ae
ae = StackedAutoencoder(train,5)
TypeError: __init__() takes exactly 4 arguments (3 given)
I am not a Python person, but is looks to me like you are passing two parameters - the "train" tuple and "5" -to the constructor/initialization function of StackedAutoencoder. You need to pass 3 - features, labels, num_labels, in addition to the implicit self variable.
No, I entred the ouput of train which are features and labels and as you can see TypeError: __init__() takes exactly 4 arguments (3 given) so I give 3 arguments my problem is how to initialize the self argument
no, you don't initialize self. It is initialized when you created an instance of that class. self will point to that instance. self is a very first argument passed to know which is the actual instance, but you do not need to take care about it. It is done automatically. So you need actually pass 3 parameters to the constructor. If 3 given that means you passed 2.
you do not initialize 'self'. This is done internally by python. You did pass, in fact, two arguments. The output says you passed 3 because 'self' was also passed automatically. Here is some further info:
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.