TypeError: __init__() got an unexpected keyword argument 'n_features_to_select' : - feature selection using forward selection - feature-selection

I am trying to do feature selection using feature forward method.
Tried previously answered questions but didn't get any proper solution. My code is as follows:
def forward_selection_rf(data, target, number_of_features=14):
# adapt number of features to select: if requested number
# is greater than features availabe, go for 75% of the
# features instead
if number_of_features > len(data.columns):
print("SFS: Wanted " + str(number_of_features) + " from " + str(len(data.columns)) + " featurs. Sanifying to 75%")
number_of_features = 0.75
# Sequential Forward Selection(sfs)
sfs1 = sfs(RandomForestClassifier(
n_estimators=70,
criterion='gini',
max_depth=15,
min_samples_split=2,
min_samples_leaf=1,
min_weight_fraction_leaf=0.0,
max_features='auto',
max_leaf_nodes=None,
min_impurity_decrease=0.0,
min_impurity_split=None,
bootstrap=True,
oob_score=False,
n_jobs=-1,
random_state=0,
verbose=0,
warm_start=False,
class_weight='balanced'
),
n_features_to_select=14,
direction='forward',
scoring = 'roc_auc',
cv = 5,
n_jobs = 3)
sfs1.fit(data, target)
return sfs1
compiler gives runtime error as follows:
forward_selection_rf(X, y, number_of_features=14)
Traceback (most recent call last):
File "C:\Users\drash\AppData\Local\Temp\ipykernel_37980\1091017691.py", line 1, in <module>
forward_selection_rf(X, y, number_of_features=14)
File "C:\Users\drash\OneDrive\Desktop\Howto Health\untitled3.py", line 102, in forward_selection_rf
TypeError: __init__() got an unexpected keyword argument 'n_features_to_select'

Related

Problems with "match" function in PyDroid3

Creating a todo list that uses the "match" function:
while True:
user_action = input("Type add, show, edit, or exit: ")
user_action = user_action.strip()
match user_action:
case "add":
todo = input("Enter a todo: ")
todos.append(todo)
file = open("todos.txt", "w")
file.writelines(todos)
Here is what happens:
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
File "<string>", line 7
match user_action:
^
SyntaxError: invalid syntax
I suspect that there is no "match" function in PyDroid. Sorry, but I'm quite new at this. Is there something I'm missing or some way I can make a work-around? Thanks in advance!
It seems the real problem here is that the version of PyDroid is 3.9.7, which is to say, it does not contain the "match" function.

possible fix of " enclose the batched tensor in a with pyro.plate(...): context "

In this example, the guide step is defined as follows
def guide(params):
# returns the Bernoulli probablility
alpha = pyro.param(
"alpha", torch.tensor(params[0]), constraint=constraints.positive
)
beta = pyro.param(
"beta", torch.tensor(params[1]), constraint=constraints.positive
)
return pyro.sample("beta_dist", dist.Beta(alpha, beta))
svi = pyro.infer.SVI(
model=conditioned_data_model,
guide=guide,
optim=pyro.optim.SGD({"lr": 0.001, "momentum": 0.8}),
loss=pyro.infer.Trace_ELBO(),
)
params_prior = [prior.concentration1, prior.concentration0]
# Iterate over all the data and store results
losses, alpha, beta = [], [], []
pyro.clear_param_store()
num_steps = 3000
for t in range(num_steps):
losses.append(svi.step(params_prior))
alpha.append(pyro.param("alpha").item())
beta.append(pyro.param("beta").item())
posterior_vi = dist.Beta(alpha[-1], beta[-1])
However, running the above step gives the following error, what does those hints of fix mean and how to fix it accordingly?
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [9], in <cell line: 15>()
14 num_steps = 3000
15 for t in range(num_steps):
---> 16 losses.append(svi.step(params_prior))
17 alpha.append(pyro.param("alpha").item())
18 beta.append(pyro.param("beta").item())
ValueError: at site "data_dist", invalid log_prob shape
Expected [], actual [100, 1]
Try one of the following fixes:
- enclose the batched tensor in a with pyro.plate(...): context
- .to_event(...) the distribution being sampled
- .permute() data dimensions

How to find expected value of np.array using scipy.stats?

I am trying to get the expected value of a NumPy array but I am running into a problem when I pass my array into the function here is an example of what is happening:
a = np.ones(10)
stats.rv_continuous.expect(args=a)
I get this error:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
stats.rv_continuous.expect(args=a)
TypeError: expect() missing 1 required positional argument: 'self'
If I try stats.rv_continuous.expect(a) , I get this error:
'numpy.ndarray' object has no attribute '_argcheck'
Can someone tell me how to get scipy.stats to work with an array?
update:
following bob's comment I changed the code to:
st=stats.rv_continuous()
ev = st.expect(args=signal_array)
print(ev)
where signal_array is a numpy array. However I now get this error:
Traceback (most recent call last):
File "C:\Users\...\OneDrive\Área de Trabalho\TickingClock\Main.py", line 35, in <module>
ev = st.expect(args=signal_array)
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 2738, in expect
vals = integrate.quad(fun, lb, ub, **kwds)[0] / invfac
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\integrate\quadpack.py", line 351, in quad
retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\integrate\quadpack.py", line 465, in _quad
return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 2722, in fun
return x * self.pdf(x, *args, **lockwds)
File "C:\Users\...\AppData\Local\Programs\Python\Python39\lib\site-packages\scipy\stats\_distn_infrastructure.py", line 1866, in pdf
args, loc, scale = self._parse_args(*args, **kwds)
TypeError: _parse_args() got multiple values for argument 'loc'

How to convert mnist dataset in array

Hello consider following code
# load the mnist training data CSV file into a list
training_data_file = open("Training_Set/mnist_train_100.csv", 'r')
training_data_list = training_data_file.readlines()
training_data_file.close()
for record in training_data_list:
all_values = record.split(',')
x_inputs = (np.asfarray(all_values[1:]) / 255.0 * 0.99) + 0.01
print("xinput=" + str(x_inputs))
print(len(training_data_list))
MyCompleteInput = np.array(x_inputs,len(training_data_list))
I want to put x_inputs and len(training_data_list) into an array so if I print the shape of the array I get an output of (784,100).
But if I run my code I get following error:
TypeError Traceback (most recent call last)
<ipython-input-38-b0f129f57bcb> in <module>()
11 print("xinput=" + str(x_inputs))
12 print(len(training_data_list))
---> 13 MyCompleteInput = np.array(x_inputs,len(training_data_list))
14
15
TypeError: data type not understood
Can somebody help me out? tnx
The line will be
MyCompleteInput = np.array((x_inputs,len(training_data_list)))
Do this and your error will be gone. You need to add another set of parantheses for specifying the size.

Jython 2.5 isdigit

I am trying to add an isdigit() to the program so that I can verify what the user enters is valid. This is what I have so far. But when I run it an enter a character, say "f". It crashes and gives me the error which will be posted below the code. Any ideas?
def mirrorHorizontal(source):
userMirrorPoint = requestString("Enter a mirror point from 0 to halfway through the pitcure.") #asks user for an input
while (int(userMirrorPoint) < 0 or int(userMirrorPoint) > (int(getHeight(source) - 1)//2)) or not(userMirrorPoint.isdigit()):
userMirrorPoint = requestString("Enter a mirror point from 0 to halfway through the pitcure.")
height = getHeight(source)
mirrorPoint = int(userMirrorPoint)
for x in range(0, getWidth(source)):
for y in range(0, mirrorPoint):
topPixel = getPixel(source, x, y)
bottomPixel = getPixel(source, x, height-y-1)
color = getColor(topPixel)
setColor(bottomPixel, color)
The error was: f
Inappropriate argument value (of correct type).
An error occurred attempting to pass an argument to a function.
Please check line 182 of /Volumes/FLASHDRIVE2/College/Spring 16'/Programs - CPS 201/PA5Sikorski.py
isdigit() itself behaves itself in the 2.7.0 jython version I have locally
>>> '1'.isdigit()
True
>>> ''.isdigit()
False
>>> 'A'.isdigit()
False
>>> 'A2'.isdigit()
False
>>> '2'.isdigit()
True
>>> '22321'.isdigit()
True
Try breaking your big expression up, as typecasting to integers will throw errors for non-numeric strings. This is true across Python versions.
>>> int('b')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'b'
>>> int('2')
2
You probably want to be careful about the order of the parts of that long expression (this or that or ...). Breaking it up would also make it more readable.