Python: How to properly call a method? - python-2.7

I have this class:
class Tumor(object):
"""
Wrapper for the tumor data points.
Attributes:
idNum = ID number for the tumor (is unique) (int)
malignant = label for this tumor (either 'M' for malignant
or 'B' for benign) (string)
featureNames = names of all features used in this Tumor
instance (list of strings)
featureVals = values of all features used in this Tumor
instance, same order as featureNames (list of floats)
"""
def __init__(self, idNum, malignant, featureNames, featureVals):
self.idNum = idNum
self.label = malignant
self.featureNames = featureNames
self.featureVals = featureVals
def distance(self, other):
dist = 0.0
for i in range(len(self.featureVals)):
dist += abs(self.featureVals[i] - other.featureVals[i])**2
return dist**0.5
def getLabel(self):
return self.label
def getFeatures(self):
return self.featureVals
def getFeatureNames(self):
return self.featureNames
def __str__(self):
return str(self.idNum) + ', ' + str(self.label) + ', ' \
+ str(self.featureVals)
and I am trying to use an instance of it in another function later in my code:
def train_model(train_set):
"""
Trains a logistic regression model with the given dataset
train_set (list): list of data points of type Tumor
Returns a model of type sklearn.linear_model.LogisticRegression
fit to the training data
"""
tumor = Tumor()
features = tumor.getFeatures()
labels = tumor.getLabel()
log_reg = sklearn.linear_model.LogisticRegression(train_set)
model = log_reg.fit(features, labels)
return model
However, I keep getting this error when I test my code:
TypeError: __init__() takes exactly 5 arguments (1 given)
I understand that I am not using the five arguments when I create the instance of Tumor in train_model , but how can I do so?

Arguments to the __init__ (or __new__, if you're using that) just go, predictably, where you create the instance in train_model:
tumor = Tumor(idNum, malignant, featureNames, featureVals)
Of course, you actually need values for all of these, as they are all required arguments.
You don't need to include self, however, as that first argument is taken care of automatically.

Related

How do I solve Error retrieving component IndexedVar[1]: The component has not been constructed

I'm getting this error (Error retrieving component IndexedVar[1]: The component has not been constructed.), and I can't figure out where I went wrong with my code below, I'm coding a linear program in pyomo, I'm not versed in python, I'm basically repeating when I learned for linear programming. Can you help me out? The error seems to be in the line defining the objective function... please help
'''
#!/usr/bin/env python3
-- coding: utf-8 --
"""
Created on Sun Jun 12 20:01:39 2022
#author: israathiab
"""
import pyomo.environ as pyo
def pyomoresults(QEMCAProfitModel): # define a function to print optimization results
""""Print results of the optimization of model 'QEMCAProfitModel' including
objective value at optimum, optimal decision variable values and
dual/slack information on constraints"""
print('')
print('=========================')
print('QEMCAProfitModel Maximization Solution')
print('=========================')
print('')
print('Objective Function Value at Optimum')
# loop over objective objects in the model
for f in QEMCAProfitModel.component_objects(pyo.Objective, active=True):
print ('Objective', f) # print the name of the objective
# loop over subobjectives (in this course we will only have one)
for index in f:
print (' ', index, pyo.value(f[index]))
print('')
print('Decision Variable Values at Optimum')
# loop over decision variable objects in model
for v in QEMCAProfitModel.component_objects(pyo.Var, active=True):
print ('Variable', v) # print variable name
for index in v: # loop over index of variable object
# print index/optimal values
print (' ', index, pyo.value(v[index]))
print('')
print ('Duals/Shadow Prices at Optimum')
# loop over constraint objects in model
for d in QEMCAProfitModel.component_objects(pyo.Constraint, active=True):
print ('Constraint',d) # print constraint name
for index in d: # loop over index of constraint object
# print dual value of constraint
print (' ', index, QEMCAProfitModel.dual[d[index]])
print('')
print ("Slack at Optimum")
# loop over constraint objects in model
for i in QEMCAProfitModel.component_objects(pyo.Constraint, active=True):
print (" Constraint",Ci) # print constraint name
for index in Ci: # loop over index of constraint object
# print constraint slack information
print (" ", index, Ci[index].lslack(), ' - ', Ci[index].uslack())
#Define Concrete model
QEMCAProfitModel = pyo.ConcreteModel
#Define variable dictionary for decision variable index
#Crop index
I = [1,2,3,4,5,6]
#Define parameters
#Define mean profit per crop - ETB
mPi = {1:15635.2, 2:9571.36, 3:13392.6, 4:39834.6, 5:49074.1, 6:11365.6}
#Define mean cost per hectar of crop - ETB/Hecatre
Ci = {1:10467.37, 2:8160.47, 3:12392.22, 4:5702.01, 5:8265.88, 6:8514.31}
#Define objective function
QEMCAProfitModel.L = pyo.Var(I,within=pyo.NonNegativeReals)
QEMCAProfitModel.Profit = pyo.Objective(expr=sum(mPi[i] * QEMCAProfitModel.L[i] for i `in I), sense=pyo.maximize)`
#Profit un EBT
#Define constraints
def Budget_rule(QEMCAProfitModel, i):
return sum(Ci[i] * QEMCAProfitModel.L[i] for i in I) <= 850636
QEMCAProfitModel.Budget_rule = pyo.Constraint(I, rule=Budget_rule)
def Land_rule(QEMCAProfitModel, i):
return sum(QEMCAProfitModel.L[i] for i in I) <= 47.77
QEMCAProfitModel.Land_rule = pyo.Constraint(I, rule=Land_rule)
def Land_rule_min(QEMCAProfitModel, i):
return sum(QEMCAProfitModel.L[i] for i in I) >= 0
QEMCAProfitModel.Land_rule_min = pyo.Constraint(I, rule=Land_rule_min)
def Consumption_rule_1(QEMCAProfitModel, i):
return 4560.64 * QEMCAProfitModel.L[1] >= 51250
QEMCAProfitModel.Consumption_rule_1 = pyo.Constraint(I, rule=Consumption_rule_1)
def Consumption_rule_2(QEMCAProfitModel, i):
return 5764.71 * QEMCAProfitModel.L[2] >= 36710
QEMCAProfitModel.Consumption_rule_2 = pyo.Constraint(I, rule=Consumption_rule_2)
def Consumption_rule_3(QEMCAProfitModel, i):
return 9908.3 * QEMCAProfitModel.L[3] >= 30316
QEMCAProfitModel.Consumption_rule_3 = pyo.Constraint(I, rule=Consumption_rule_3)
def Consumption_rule_4(QEMCAProfitModel, i):
return 16614.81 * QEMCAProfitModel.L[4] >= 4850
QEMCAProfitModel.Consumption_rule_4 = pyo.Constraint(I, rule=Consumption_rule_4)
def Consumption_rule_5(QEMCAProfitModel, i):
return 20323.81 * QEMCAProfitModel.L[5] >= 4450
QEMCAProfitModel.Consumption_rule_5 = pyo.Constraint(I, rule=Consumption_rule_5)
def Consumption_rule_6(QEMCAProfitModel, i):
return 4400 * QEMCAProfitModel.L[6] >= 7100
QEMCAProfitModel.Consumption_rule_6 = pyo.Constraint(I, rule=Consumption_rule_6)
QEMCAProfitModel.pprint()
QEMCAProfitModel.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)
opt = pyo.SolverFactory('glpk')
results = opt.solve(QEMCAProfitModel)
QEMCAProfitModel.display()
QEMCAProfitModel.dual.display()
pyomoresults(QEMCAProfitModel)
'''
You are missing parens when defining the model object:
QEMCAProfitModel = pyo.ConcreteModel
should be
QEMCAProfitModel = pyo.ConcreteModel()
Without the parens, QEMCAProfitModel is the class ConcreteModel instead of an instance of the class. The "magic" that triggers component "construction" (the __setattr__ method on Block data instances) only works on Block instances (and a model is a block).
Note that the same method is also responsible for copying the attribute name to the component name. Since that is not being triggered, you are seeing the default component name (the class name, IndexedVar) in the error message.

What does does if self.transforms mean?

What does
if self.transforms:
data = self.transforms(data)
do? I don't understand the logic behind this line - what is the condition the line is using?
I'm reading an article on creating a custom dataset with pytorch based on the below implementation:
#custom dataset
class MNISTDataset(Dataset):
def __init__(self, images, labels=None, transforms=None):
self.X = images
self.y = labels
self.transforms = transforms
def __len__(self):
return (len(self.X))
def __getitem__(self, i):
data = self.X.iloc[i, :]
data = np.asarray(data).astype(np.uint8).reshape(28, 28, 1)
if self.transforms:
data = self.transforms(data)
if self.y is not None:
return (data, self.y[i])
else:
return data
train_data = MNISTDataset(train_images, train_labels, transform)
test_data = MNISTDataset(test_images, test_labels, transform)
# dataloaders
trainloader = DataLoader(train_data, batch_size=128, shuffle=True)
testloader = DataLoader(test_data, batch_size=128, shuffle=True)
thank you! i'm basically trying to understand why it works & how it applies transforms to the data.
The dataset MNISTDataset can optionnaly be initialized with a transform function. If such transform function is given it be saved in self.transforms else it will keep its default values None. When calling a new item with __getitem__, it first checks if the transform is a truthy value, in this case it checks if self.transforms can be coerced to True which is the case for a callable object. Otherwise it means self.transforms hasn't been provided in the first place and no transform function is applied on data.
Here's a general example, out of a torch/torchvision context:
def do(x, callback=None):
if callback: # will be True if callback is a function/lambda
return callback(x)
return x
do(2) # returns 2
do(2, callback=lambda x: 2*x) # returns 4

Practice assignment AWS Computer Vision : get_Cifar10_dataset

I have problem with this methode which should return both the training and the validation dataset and examine it to return the index that corresponds to the first occurrence of each class in CIFAR10.
this is code:
def get_cifar10_dataset(): """ Should create the cifar 10 network and identify the dataset index of the first time each new class
appears
:return: tuple of training and validation dataset as well as label indices
:rtype: (gluon.data.Dataset, 'dict_values' object is not subscriptable, gluon.data.Dataset,
dict[int:int])
"""
train_data = None
val_data = None
# YOUR CODE HERE
train_data = datasets.CIFAR10(train=True, root=M5_IMAGES)
val_data = datasets.CIFAR10(train=False, root=M5_IMAGES)
You are asked to return a dictionary with labels and the corresponding indexes. Using the following function can solve your problem.
def get_idx_dict(data):
lis = []
idx = []
indices = {}
for i in range(len(data)):
if data[i][1] not in lis:
lis.append(data[i][1])
idx.append(i)
indices = {lis[i]: idx[i] for i in range(len(lis))}
return indices
The function returns a dictionary with desired output. Use this function on data from train and validation set.
train_indices = get_idx_dict(train_data)
val_indices = get_idx_dict(val_data)
You can do it this
def get_cifar10_dataset():
"""
Should create the cifar 10 network and identify the dataset index of the first time each new class appears
:return: tuple of training and validation dataset as well as label indices
:rtype: (gluon.data.Dataset, dict[int:int], gluon.data.Dataset, dict[int:int])
"""
train_data = None
val_data = None
train_indices = {}
val_indices = {}
# Use `root=M5_IMAGES` for your dataset
train_data = gluon.data.vision.datasets.CIFAR10(train=True, root=M5_IMAGES)
val_data = gluon.data.vision.datasets.CIFAR10(train=False, root=M5_IMAGES)
#for train
for i in range(len(train_data)):
if train_data[i][1] not in train_indices:
train_indices[train_data[i][1]] = i
#for valid
for i in range(len(val_data)):
if val_data[i][1] not in val_indices:
val_indices[val_data[i][1]] = i
#raise NotImplementedError()
return train_data, train_indices, val_data, val_indices

Django: Filter & function

I have currently these to utils functions.
The only difference between unique_account_link_generator and unique_order_id is what they filter within qs_exists. It's either .filter(slug=new_id) or .filter(order_id=new_id)
I now wonder is there a way to combine them and then being able to define the filter method when I call the function: unique_id_generator(instance, _filter = "order_id")
import random
import string
def random_string_generator(size=10, chars=string.ascii_lowercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
def unique_account_link_generator(instance):
"""
1. Generates random string
2. Check if string unique in database
3. If already exists, generate new string
"""
new_id = random_string_generator()
myClass = instance.__class__
qs_exists = myClass.objects.filter(slug=new_id).exists()
if qs_exists:
return unique_account_link_generator(instance)
return new_id
# How to send field_name via function?
def unique_id_generator(instance):
"""
1. Generates random string
2. Check if string unique in database
3. If already exists, generate new string
"""
new_id = random_string_generator()
myClass = instance.__class__
qs_exists = myClass.objects.filter(order_id=new_id).exists()
if qs_exists:
return unique_id_generator(instance)
return new_id
Not sure I understood the question, as the answer is very simple:
def unique_id_generator(instance, _filter="order_id"):
new_id = random_string_generator()
myClass = instance.__class__
qs_exists = myClass.objects.filter(**{_filter:new_id}).exists()
if qs_exists:
return unique_id_generator(instance, _filter)
return new_id
I want to give you an answer to your question in the comments. Since the comment section doesn't allow much text I would like to attach this as an addition to the accepted answer.
It's actually correct that **{_filter:new_id} will unpack what's inside the _filter parameter
If you call the function with (instance, _filter="order_id")
this part **{_filter:new_id} will look like this **{"order_id":"randomGeneratedCode123"}
Now you have a dictionary with the key "order_id" and the value "randomGeneratedCode123"
You goal is to transform the key "order_id" to a parameter name and the value of the "order_id" key to the value of the parameter order_id
order_id = "randomGeneratedCode123"
As you already said you can unpack a dictionary with the double stars **
After unpacking it, the keys in the dictionary will be your parameter names and the values of the keys the parameter values
Here is a small example for better understanding:
Let's say you have a dictionary and a function
dict = {'a': 1, 'b': 2}
def example(a, b):
print("Variable a is {}, b is {}".format(a, b))
example(**dict)
**dict is converted to:
a = 1, b = 2 so the function will be called with
example(a = 1, b = 2)
It's important that the keys in your dictionary have the same name as your function parameter names
So this wouldn't work:
dict = {'a': 1, 'c': 2}
example(**dict)
because it's "translated " as
example(a = 1, c = 2)
and the function doesn't have a parameter with the name c

Storing and ordering by an array/list of integers in a Django model

I have a vector of three numbers as a name for a model.
i.e. 12-1-120 12-1-139 12-1-9 etc.
I wanted to sort instances of the model in descending order, using Django to display 12-1-139, 12-1-120, 12-1-9.
Except it always acts like a string, hence displaying 12-1-9, 12-1-139, 12-1-120.
I've tried using the 'CommaSeparatedIntegerField' yet it's totally useless and still acts the same way.
The only way that I know of, that would technically work, is by having three separate "IntegerField"s and ordering it by the combination, which I think is too impractical.
Any pointers, or am I stuck with this impractical method?
I forgot to mention that I also needed to sometimes call this object using a string and I didn't want to constantly convert the string to an int so I did it the other way around and stored the bunch of ints into a string using somewhat of a calculated field.
Here's my basic code:
class MyModelName(models.Model):
name = models.CharField(max_length=15)
x = models.IntegerField(max_length=200)
y = models.IntegerField(max_length=200)
z = models.IntegerField(max_length=200)
def save(self, *args, **kwargs):
self.name = '-'.join([str(self.x), str(self.y), str(self.z)])
super(MyModelName, self).save(*args, **kwargs)
class Meta:
ordering = ["-x","-y","-z"]
Three integer fields is the way to go.
If you want to name your objects that way, you could always add a unicode function to your model...
class Thing(models.Model):
x = models.IntegerField()
y = models.IntegerField()
z = models.IntegerField()
def __unicode__(self):
"""
Return a human-readable representation of the object.
"""
return '-'.join(self.x, self.y, self.z)
https://docs.djangoproject.com/en/dev/ref/models/instances/#unicode
get_or_create example:
s = '12-1-9'
x, y, z = [int(c) for c in s.split('-')]
thing, created = Thing.objects.get_or_create(x=x, y=y, z=z)
custom get or create method
class ThingManager(models.Manager):
def from_string(s):
x, y, z = [int(c) for c in s.split('-')]
obj, created = self.get_or_create(x=x, y=y, z=z)
return obj, created
class Thing(models.Model):
objects = ThingManager()
# Snip
--
my_new_thing, created = Thing.objects.from_string('12-1-9')