I have a list:
q1 = [0,1.9488e-06,1.5473e-05,5.1829e-05,0.00012192,0.00023633,0.00040526,0.00063862,0.00094596,0.0013365,0.0018192,0.0024025,0.0030949,0.0039041,0.0048379,0.0059036]
which I am trying to integrate.
I have done the following:
def f(x):
if (np.abs(x)<1e-10):
res = x
else:
res = q2[:10]
return res
x = np.arange(0,10,0.001)
def F(x):
res = np.zeros_like(x)
for i,val in enumerate (x):
y,err = integrate.quad(f,0,val)
res[i] = y
return res
plt.plot(F(x))
when I try to run this code I get this error:
Traceback (most recent call last):
File "<ipython-input-88-ca3005760f4b>", line 19, in <module>
plt.plot(F(x))
File "<ipython-input-88-ca3005760f4b>", line 14, in F
y,err = integrate.quad(f,0,val)
File "C:\Anaconda2\lib\site-packages\scipy\integrate\quadpack.py", line 311,
in quad points)
File "C:\Anaconda2\lib\site-packages\scipy\integrate\quadpack.py", line 376,
in _quad
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
error: Supplied function does not return a valid float.
Can anyone help me understand why I am getting this error?
You're having this error because of these two lines in f:
else:
res = q2[:10]
Here, you're returning a slice of a list from the function. quad doesn't like that; according to its documentation, it expects a function that returns a double (i.e. Python float), not a list.
While your intended output isn't given in your question, changing that line to
res = q2[0]
or any other arbitrary index in q2 corrects the error.
Related
I am having the hardest time figuring out why i am getting this error. I have searched a lot but unable to fine any solution
import numpy as np
import warnings
from collections import Counter
import pandas as pd
def k_nearest_neighbors(data, predict, k=3):
if len(data) >= k:
warnings.warn('K is set to a value less than total voting groups!')
distances = []
for group in data:
for features in data[group]:
euclidean_distance = np.linalg.norm(np.array(features)-
np.array(predict))
distances.append([euclidean_distance,group])
votes = [i[1] for i in sorted(distances)[:k]]
vote_result = Counter(votes).most_common(1)[0][0]
return vote_result
df = pd.read_csv("data.txt")
df.replace('?',-99999, inplace=True)
df.drop(['id'], 1, inplace=True)
full_data = df.astype(float).values.tolist()
print(full_data)
After running. it gives error
Traceback (most recent call last):
File "E:\Jazab\Machine Learning\Lec18(Testing K Neatest Nerighbors
Classifier)\Lec18(Testing K Neatest Nerighbors
Classifier)\Lec18_Testing_K_Neatest_Nerighbors_Classifier_.py", line 25, in
<module>
full_data = df.astype(float).values.tolist()
File "C:\Python27\lib\site-packages\pandas\util\_decorators.py", line 91, in
wrapper
return func(*args, **kwargs)
File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 3299, in
astype
**kwargs)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 3224, in
astype
return self.apply('astype', dtype=dtype, **kwargs)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 3091, in
apply
applied = getattr(b, f)(**kwargs)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 471, in
astype
**kwargs)
File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 521, in
_astype
values = astype_nansafe(values.ravel(), dtype, copy=True)
File "C:\Python27\lib\site-packages\pandas\core\dtypes\cast.py", line 636,
in astype_nansafe
return arr.astype(dtype)
ValueError: invalid literal for float(): 3) <-----Reappears in Group 8 as:
Press any key to continue . . .
if i remove astype(float) program run fine
What should i need to do ?
There are bad data (3)), so need to_numeric with apply because need processes all columns.
Non numeric are converted to NaNs, which are replaced by fillna to some scalar, e.g. 0:
full_data = df.apply(pd.to_numeric, errors='coerce').fillna(0).values.tolist()
Sample:
df = pd.DataFrame({'A':[1,2,7], 'B':['3)',4,5]})
print (df)
A B
0 1 3)
1 2 4
2 7 5
full_data = df.apply(pd.to_numeric, errors='coerce').fillna(0).values.tolist()
print (full_data)
[[1.0, 0.0], [2.0, 4.0], [7.0, 5.0]]
It looks like you have 3) as an entry in your CSV file, and Pandas is complaining because it can't cast it to a float because of the ).
I'm trying to make a Seq2Seq Regression example for time-series analysis and I've used the Seq2Seq library as presented at the Dev Summit, which is currently the code on the Tensorflow GitHub branch r1.0.
I have difficulties understanding how the decoder function works for Seq2Seq, specifically for the "cell_output".
I understand that the num_decoder_symbols is the number of classes/words to decode at each time step. I have it working at a point where I can do training. However, I don't get why I can't just substitute the number of features (num_features) instead of num_decoder_symbols. Basically, I want to be able to run the decoder without teacher forcing, in other words pass the output of the previous time step as the input to the next time step.
with ops.name_scope(name, "simple_decoder_fn_inference",
[time, cell_state, cell_input, cell_output,
context_state]):
if cell_input is not None:
raise ValueError("Expected cell_input to be None, but saw: %s" %
cell_input)
if cell_output is None:
# invariant that this is time == 0
next_input_id = array_ops.ones([batch_size,], dtype=dtype) * (
start_of_sequence_id)
done = array_ops.zeros([batch_size,], dtype=dtypes.bool)
cell_state = encoder_state
cell_output = array_ops.zeros([num_decoder_symbols],
dtype=dtypes.float32)
Here is a link to the original code: https://github.com/tensorflow/tensorflow/blob/r1.0/tensorflow/contrib/seq2seq/python/ops/decoder_fn.py
Why don't I need to pass batch_size for the cell output?
cell_output = array_ops.zeros([batch_size, num_decoder_symbols],
dtype=dtypes.float32)
When trying to use this code to create my own regressive Seq2Seq example, where instead of having an output of probabilities/classes, I have a real valued vector of dimension num_features, instead of an array of probability of classes. As I understood, I thought I could replace num_decoder_symbols with num_features, like below:
def decoder_fn(time, cell_state, cell_input, cell_output, context_state):
"""
Again same as in simple_decoder_fn_inference but for regression on sequences with a fixed length
"""
with ops.name_scope(name, "simple_decoder_fn_inference", [time, cell_state, cell_input, cell_output, context_state]):
if cell_input is not None:
raise ValueError("Expected cell_input to be None, but saw: %s" % cell_input)
if cell_output is None:
# invariant that this is time == 0
next_input = array_ops.ones([batch_size, num_features], dtype=dtype)
done = array_ops.zeros([batch_size], dtype=dtypes.bool)
cell_state = encoder_state
cell_output = array_ops.zeros([num_features], dtype=dtypes.float32)
else:
cell_output = output_fn(cell_output)
done = math_ops.equal(0,1) # hardcoded hack just to properly define done
next_input = cell_output
# if time > maxlen, return all true vector
done = control_flow_ops.cond(math_ops.greater(time, maximum_length),
lambda: array_ops.ones([batch_size,], dtype=dtypes.bool),
lambda: done)
return (done, cell_state, next_input, cell_output, context_state)
return decoder_fn
But, I get the following error:
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/contrib/seq2seq/python/ops/seq2seq.py", line 212, in dynamic_rnn_decoder
swap_memory=swap_memory, scope=scope)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/rnn.py", line 1036, in raw_rnn
swap_memory=swap_memory)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2605, in while_loop
result = context.BuildLoop(cond, body, loop_vars, shape_invariants)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2438, in BuildLoop
pred, body, original_loop_vars, loop_vars, shape_invariants)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2388, in _BuildLoop
body_result = body(*packed_vars_for_body)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/rnn.py", line 980, in body
(next_output, cell_state) = cell(current_input, state)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py", line 327, in __call__
input_size = inputs.get_shape().with_rank(2)[1]
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/tensor_shape.py", line 635, in with_rank
raise ValueError("Shape %s must have rank %d" % (self, rank))
ValueError: Shape (100,) must have rank 2
As a result, I passed in the batch_size like this in order to get a Shape of rank 2:
cell_output = array_ops.zeros([batch_size, num_features],
dtype=dtypes.float32)
But I get the following error, where Shape is of rank 3 and wants a rank 2 instead:
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/contrib/seq2seq/python/ops/seq2seq.py", line 212, in dynamic_rnn_decoder
swap_memory=swap_memory, scope=scope)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/rnn.py", line 1036, in raw_rnn
swap_memory=swap_memory)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2605, in while_loop
result = context.BuildLoop(cond, body, loop_vars, shape_invariants)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2438, in BuildLoop
pred, body, original_loop_vars, loop_vars, shape_invariants)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/control_flow_ops.py", line 2388, in _BuildLoop
body_result = body(*packed_vars_for_body)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/rnn.py", line 980, in body
(next_output, cell_state) = cell(current_input, state)
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py", line 327, in __call__
input_size = inputs.get_shape().with_rank(2)[1]
File "/opt/DL/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/tensor_shape.py", line 635, in with_rank
raise ValueError("Shape %s must have rank %d" % (self, rank))
ValueError: Shape (10, 10, 100) must have rank 2
I am currently working on a backup program, I have run into errors while trying to gernate a unique file name with a given destination. I call this function in my code as: getFileUnique(f,pathtofile(backup+"/"+"../trash/")). f is the file path, the rest of the variables are pretty straight forward.
def getFileUnique(path,destination):
path = path.replace("\\","/")
p = path.split("/")[-1]
if not os.path.exists(join(destination,p)):
return destination+p
j = p.split(".")
counter = 0
print(j)
while os.path.exists(join(destination,j[:-1]+str(counter)+"."+j[-1])):
print(counter)
print("asdfsdf")
counter += 1
return destination+j[:-1]+str(counter)+"."+j[-1]
Error:
Traceback (most recent call last):
File "C:\Users\Owner\Google Drive\Programs\Dev Enviroment\python\backup\backup.py", line 76, in <module>
main("files","backup")
File "C:\Users\Owner\Google Drive\Programs\Dev Enviroment\python\backup\backup.py", line 73, in main
updateBackup(oldf,newf,reg,backup)
File "C:\Users\Owner\Google Drive\Programs\Dev Enviroment\python\backup\backup.py", line 65, in updateBackup
k = getFileUnique(f,pathtofile(backup+"/"+"../trash/"))
File "C:\Users\Owner\Google Drive\Programs\Dev Enviroment\python\backup\backup.py", line 41, in getFileUnique
while os.path.exists(join(destination,j[:-1]+str(counter)+"."+j[-1])):
TypeError: can only concatenate list (not "str") to list
return destination + '.'.join(j[:-1]) + str(counter) + "." + j[-1]
I am trying to evaluate a function (second derivative of another one) but Sympy seems to have a difficulty to do that... ?
from sympy import *
from sympy import Symbol
# Symbols
theta = Symbol('theta')
phi = Symbol('phi')
phi0 = Symbol('phi0')
H0 = Symbol('H0')
# Constants
a = 0.05
t = 100*1e-9
b = 0.05**2/(8*pi*1e-7)
c = 0.001/(4*pi*1e-7)
phi0 = 60*pi/180
H0 = -0.03/(4*pi*1e-7)
def m(theta,phi):
return Matrix([[sin(theta)*cos(phi), sin(theta)*cos(phi), cos(phi)]])
def h(phi0):
return Matrix([[cos(phi0), sin(phi0), 0]])
def k(theta,phi,phi0):
return m(theta,phi).dot(h(phi0))
def F(theta,phi,phi0,H0):
return -(t*a*H0)*k(theta,phi,phi0)+b*t*(cos(theta)**2)+c*t*(sin(2*theta)**2)+t*sin(theta)**4*sin(2*phi)**2
def F_theta(theta,phi,phi0,H0):
return simplify(diff(F(theta,phi,phi0,H0),theta))
def F_thetatheta(theta,phi,phi0,H0):
return simplify(diff(F_theta(theta,phi,phi0,H0),theta))
print F_thetatheta(theta,phi,phi0,H0), F_thetatheta(pi/2,phi,phi0,H0)
As seen below, the general function is evaluated but when I try to replace theta by pi/2 or another value, it does not work.
(4.0e-7*pi*sin(theta)**4*cos(2*phi)**2 - 4.0e-7*pi*sin(theta)**4 + 0.00125*sin(theta)**2 - 0.0001875*sqrt(3)*sin(theta)*cos(phi) - 0.0001875*sin(theta)*cos(phi) + 1.2e-6*pi*cos(2*phi)**2*cos(theta)**4 - 1.2e-6*pi*cos(2*phi)**2*cos(theta)**2 - 1.2e-6*pi*cos(theta)**4 + 1.2e-6*pi*cos(theta)**2 + 0.004*cos(2*theta)**2 - 0.002625)/pi
Traceback (most recent call last):
File "Test.py", line 46, in <module>
print F_thetatheta(theta,phi,phi0,H0), F_thetatheta(pi/2,phi,phi0,H0)
File "Test.py", line 29, in F_thetatheta
return simplify(diff(F_theta(theta,phi,phi0,H0),theta))
File "Test.py", line 27, in F_theta
return simplify(diff(F(theta,phi,phi0,H0),theta))
File "/usr/lib64/python2.7/site-packages/sympy/core/function.py", line 1418, in diff
return Derivative(f, *symbols, **kwargs)
File "/usr/lib64/python2.7/site-packages/sympy/core/function.py", line 852, in __new__
Can\'t differentiate wrt the variable: %s, %s''' % (v, count)))
ValueError:
Can't differentiate wrt the variable: pi/2, 1
The error means you can not differentiate with respect to a number, pi/2. Ie, you derive with respect to a variable (x, y...), not a number.
In an expression with several variables, you can substitute one of them (or more) by its value (or another expression) by using subs:
F_thetatheta(theta,phi,phi0,H0).subs(theta, pi/2)
Then, to evaluate it to the desired accuracy you can use evalf. Compare the two results:
F_thetatheta(theta,phi,phi0,H0).evalf(50, subs={theta:pi/2, phi:0})
F_thetatheta(theta,phi,phi0,H0).subs({theta: pi/2, phi:0})
You should probably have a look at the sympy documentation or follow the tutorial. The documentation is very good, and you can even try the examples in the browser and evaluate code.
I am just about done writing my first mergesort program and am running into trouble when compiling. I have done a bunch of research on this particular error and it seems I'm being non-specific somewhere in my code. I still cannot find said error and would love your help. I have attached the file contents, code, and traceback. Thanks again.
File:
999 Message C1
1033 Message C2
1054 Message C3
1056 Message C4
1086 Message C5
Code:
DEBUG = True
out = []
logs = open("C:\Users\----\Desktop\logs.txt", mode ="r")
lines = logs.readline()
def debug(s):
if DEBUG:
print "DEBUG: ", s
def get_t (line):
s = line
s = s.lstrip()
debug(s)
i = s.find(" ")
debug(s)
s = s[:i]
return int(s)
def get_lowest_i(logs):
lowest_i = -1
for i in range(len(logs)):
log = logs[i]
debug("log=" + repr(log))
if log:
t = get_t(log[0])
debug("t=" + repr(t))
if lowest_i == -1 or t < lowest_t:
lowest_i = i
lowest_t = t
return lowest_i
def get_line_lowest_t(logs):
while True:
i = get_lowest_i(logs)
if i == -1:
break
line = logs[i].pop(0)
def mergesort(logs):
while True:
line = get_line_lowest_t(logs)
if line == None:
break
out.append(line)
return out
print mergesort(logs)
f.close()
Traceback:
Traceback (most recent call last):
File "<module1>", line 50, in <module>
File "<module1>", line 44, in mergesort
File "<module1>", line 37, in get_line_lowest_t
File "<module1>", line 24, in get_lowest_i
TypeError: object of type 'file' has no len()
Thanks in advance.
TypeError: object of type 'file' has no len() the error says it all you are trying to read the length of a file object ... being that logs = open("C:\Users\----\Desktop\logs.txt", mode ="r") is a file maybe you mean to read the lines of the file and sort that ... lines = longs.readlines() print mergesort(lines)
file has no method len(). Put it into strings or arrays and then use len()
You are mergesorting the file, not the array called lines.