How to use math function in Python - python

How to execute this code:
import numpy as np
import math
x = np.arange(1,9, 0.5)
k = math.cos(x)
print(x)
I got an error like this:
TypeError: only size-1 arrays can be converted to Python scalars
Thank you in advance.

So this is happening because math.cos doesn't accept numpy arrays larger than size 1. That's why if you had a np array of size 1, your approach would still work.
A simpler way you can achieve the result is to use np.cos(x) directly:
import numpy as np
x = np.arange(1,9, 0.5)
k = np.cos(x)
print(x)
print(k)
If you have to use the math module, you can try iterating through the array and applying math.cos to each member of the array:
import numpy as np
import math
x = np.arange(1,9,0.5)
for item in x:
k = math.cos(item)
print(k) # or add to a new array/list

You're looking for something like this?
import numpy as np
import math
x = np.arange(1,9, 0.5)
for ang in x:
k = math.cos(ang)
print(k)

You are trying to pass ndarray (returned by arange) to a function, which expects just real number. Use np.cos instead.

If you want pure-Python:
You can use math.fun in map like below:
import math
x = range(1,9)
print(list(map(math.cos, x)))
Output:
[0.5403023058681398, -0.4161468365471424, -0.9899924966004454, -0.6536436208636119, 0.2836621854632263, 0.9601702866503661, 0.7539022543433046, -0.14550003380861354]

Related

For loop alternitive to array subtraction

import numpy as np
x = np.array([[1,1,1],[2,2,2],[3,3,3]])
xt = np.array([1,2,3])
L = len(xt)
for i in range(0,L):
s = x-xt[i]
is there another way to get the same results without the use of a for loop, thanks.

How do I convert an array of numpy booleans to python booleans for serialization (e.g. for mongodb)?

I have a numpy array of booleans:
import numpy as np
x = np.zeros(100).astype(np.bool)
x[20] = True # say
When I try to insert this (one element per document) as part of an OrderedDict into mongodb, I get the following error:
InvalidDocument: cannot encode object: False, of type: <class 'numpy.bool_'>
This is a serialization issue I have encountered before for singleton numpy booleans.
How do I convert the numpy array into an array of python booleans for serialization?
The following did not work:
y = x.astype(bool)
You can use numpy.ndarray.tolist here.
import numpy as np
x = np.zeros(100).astype(np.bool)
y = x.tolist()
print(type(x))
# numpy.ndarray
print(type(x[0]))
# numpy.bool_
print(type(y))
# list
print(type(y[0]))
# bool
You can try numpy.asscalar
import numpy as np
x = np.zeros(100).astype(np.bool)
z = [np.asscalar(x_i) for x_i in x]
print(type(z))
You can also use item() which is a better option since asscalar is depreceted.
import numpy as np
x = np.zeros(100).astype(np.bool)
z = [x_i.item() for x_i in x]
print(type(z))
print(z)
For a longer list, tolist() is better option.
import numpy as np
import time
x = np.zeros(100000).astype(np.bool)
t1 = time.time()
z = [x_i.item() for x_i in x]
t2 = time.time()
print(t2-t1)
t1 = time.time()
z = x.tolist()
t2 = time.time()
print(t2-t1)
0.0519254207611084
0.0015206336975097656
So, I have just this week come across a solution to this (albeit my own) question from two years ago... Thanks SO!
I am going to invoke the brilliant numpyencoder (https://pypi.org/project/numpyencoder) as follows:
# Set up the problem
import numpy as np
x = np.zeros(100).astype(bool) # Note: bool <- np.bool is now deprecated!
x[20] = True
# Let's roll
import json
from numpyencoder import NumpyEncoder
sanitized_json_string = json.dumps(x, cls=NumpyEncoder)
# One could stop there since the payload is now ready to go - but just to confirm:
x_sanitized=json.loads(sanitized_json_string)
print(x_sanitized)

Python plot only part of data

I want to plot any part or the data
here is the code
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
... ...
xs = []
avg = []
for line in lines:
if len(line) > 1:
x, y1 = line.split(',')
xs.append(float(x))
avg.append(float(y1))
ax1.plot(xs, avg, label='avg')
I added some of the code so you can see the type of the variables
I tried :
ax1.plot(xs[avg>0], avg[avg>0], label='avg')
and didnt work
im matlab i would do some thing like :
Indxs=find (ys>0)
Plot(xs(indxs),ys(indxs))
The syntax is correct. The problem is that xs and avg are no numpy arrays. So you first need to convert those lists to numpy arrays, then the slicing will work as expected.
xs = np.array(xs)
avg = np.array(avg)
ax1.plot(xs[avg>0], avg[avg>0], label='avg')
What you doesen't work since your index (avg > 0) in python is a boolean. When you are used to Matlab then you should definitely try numpy Boolean indexing.
you can do:
import numpy as np
xs = numpy.asarray(x)
ys = numpy.asarray(y)
ys_filtered = ys[x > 0]

Matrix multiplication in Keras

I try to multiply two matrices in a python program using Keras.
import keras.backend as K
import numpy as np
A = np.random.rand(10,500)
B = np.random.rand(500,6000)
x = K.placeholder(shape=A.shape)
y = K.placeholder(shape=B.shape)
xy = K.dot(x, y)
xy.eval(A,B)
I know this cannot work, but I also don't know how I can make it work.
You need to use a variable instead of a place holder.
import keras.backend as K
import numpy as np
A = np.random.rand(10,500)
B = np.random.rand(500,6000)
x = K.variable(value=A)
y = K.variable(value=B)
z = K.dot(x,y)
# Here you need to use K.eval() instead of z.eval() because this uses the backend session
K.eval(z)

Use savefig in Python with string and iterative index in the name

I need to use the "savefig" in Python to save the plot of each iteration of a while loop, and I want that the name i give to the figure contains a literal part and a numerical part. This one comes out from an array or is the number associated to the index of iteration. I make a simple example:
# index.py
from numpy import *
from pylab import *
from matplotlib import *
from matplotlib.pyplot import *
import os
x=arange(0.12,60,0.12).reshape(100,5)
y=sin(x)
i=0
while i<99
figure()
a=x[:,i]
b=y[:,i]
c=a[0]
plot(x,y,label='%s%d'%('x=',c))
savefig(#???#) #I want the name is: x='a[0]'.png
#where 'a[0]' is the value of a[0]
thanks a lot.
Well, it should be simply this:
savefig(str(a[0]))
This is a toy example. Works for me.
import pylab as pl
import numpy as np
# some data
x = np.arange(10)
pl.figure()
pl.plot(x)
pl.savefig('x=' + str(10) + '.png')
I had the same demand recently and figured out the solution. I modify the given code and correct several explicit errors.
from pylab import *
import matplotlib.pyplot as plt
x = arange(0.12, 60, 0.12).reshape(100, 5)
y = sin(x)
i = 0
while i < 99:
figure()
a = x[i, :] # change each row instead of column
b = y[i, :]
i += 1 # make sure to exit the while loop
flag = 'x=%s' % str(a[0]) # use the first element of list a as the name
plot(a, b, label=flag)
plt.savefig("%s.png" % flag)
Hope it helps.
Since python 3.6 you can use f-strings to format strings dynamically:
import matplotlib.pyplot as plt
for i in range(99):
plt.figure()
a = x[:, i]
b = y[:, i]
c = a[0]
plt.plot(a, b, label=f'x={c}')
plt.savefig(f'x={c}.png')

Categories