I want to 2 decimal points result for predicts on Python - python

My outputs have too much decimal points. But I want to 2 points float results. Can you help me?
EX: 42.44468745 -> 42.44
y_pred=ml.predict(x_test)
print(y_pred)
Output:
[42.44468745 18.38280575 7.75539511 19.05326276 11.87002186 26.89180941
18.97589775 22.01291508 9.08079557 6.72623692 21.81657224 22.51415263
24.46456776 13.75392096 21.57583275 25.73401908 30.95880457 11.38970094
7.28188274 21.98202474 17.24708345 38.7390475 12.68345506 11.2247757
5.32814356 10.41623796 7.30681434]

Since you didn't post all of your code, I can only give you a general answer.
There are several ways to get two decimals.
For example:
num = 1.223362719
print('{:.2f}'.format(num))
print('%.2f' % num)
print(round(num, 2))
print(f"{num:.2f}")
You will get 1.22 as the result of any of these.
------------------Update------------------
Thanks for commenting, and I have updated to deal with your problem.
Using numpy could help you when your data OP is using an ndarray.
You can use data= np.around(a, n) # a is the data that needs to be decimal processed, and n is the reserved number.
Example:
import numpy as np
data= np.around(1.223362719, 2)
You will also get 1.22 as the result.

Use round(num, round_decimal)
For example:
num = 42.44468745
print(round(num, 2))
Output:
42.44

Related

Sum of matrices using np.add()

I have a list of n matrices where n = 5:
[matrix([[3.62425112, 0.00953506],
[0.00953506, 1.05054417]]), matrix([[4.15808905e+00, 9.27845937e-04],
[9.27845937e-04, 9.88509628e-01]]), matrix([[3.90560856, 0.0504297 ],
[0.0504297 , 0.92587046]]), matrix([[ 3.87347073, -0.12430547],
[-0.12430547, 1.09071475]]), matrix([[ 3.87697392, -0.00475038],
[-0.00475038, 1.01439917]])]
I want to do element-wise addition of these matrices:
I am trying this:
np.add(S_list[0], S_list[1], S_list[2], S_list[3], S_list[4])
It works but I don't want to fix n = 5
Can anyone please help? Thank you.
by the documentation, np.add should add only two matrices.
However np.add.reduce(S_list) or just sum(S_list) will give you what you want.
You could just use Python's built-in function sum
sum(S_list)
Output:
[[19.43839338 -0.06816324]
[-0.06816324 5.07003818]]
Are you sure that np.add(S_list[0], S_list[1], S_list[2], S_list[3], S_list[4]) works ? Because np.add() takes as input arguments two arrays . Anyway , the following code does the work if you want to use np.add():
sum = np.add(S_list[0],S_list[1])
for i in range(len(S_list) - 2):
sum = np.add(sum,S_list[i+2])
print(sum)

What do I need to add or rearrange so there is another decimal place?

I'm in my first year of CS and we use Python3. I managed to code properly and submitted it into gradescope, but it was incorrect because one decimal was missing (the 4 at the end). My professor told me to rearrange the equation, so I tried swapping the numbers around, but it still didn't give me the answer I want.
I swapped the multiplied numbers with the one beside it, but it only threw off the number more.
import math
import stdio
import sys
theta = float(sys.argv[1])
n1 = float(sys.argv[2])
n2 = float(sys.argv[3])
theta1_rad = theta1*math.pi/180
theta2_rad = math.asin(n1*math.sin(theta1_rad)/n2)
theta2 = theta2_rad*180/math.pi
print(theta2)
When I plug in $ python3 snell.py 58 1 1.52 into the terminal, I expect the output of 33.912513998258994, but the actual output I get is 33.91251399825899.
import math
import sys
theta = float(sys.argv[1])
n1 = float(sys.argv[2])
n2 = float(sys.argv[3])
theta1_rad = round(theta*math.pi/180,15)
theta2_rad = round(math.asin(n1*math.sin(theta1_rad)/n2),15)
theta2 = round(theta2_rad*180/math.pi,15)
print(theta2)
Try this hopefully it will work according to your expectation!
As stated in this answer in a similar question, try using numpy.float128. Or you could go for Decimal datatype as stated in the accepted answer.

How to specify a scalar multiplier for units when using Quantities?

The objective is to handle cell densities expressed as "1000/mm^3", i.e. thousands per cubic millimeter.
Currently I do this to handle "1/mm^3":
import quantities as pq
d1 = pq.Quantity(500000, "1/mm**3")
which gives:
array(500000) * 1/mm**3
But what I really need to do is to accept the values with units of "1000/mm^3". This should also be the form in which values are printed. When I try something like:
d1 = pq.Quantity(5, 1000/pq.mm**3)
I get the following error:
ValueError: units must be a scalar Quantity with unit magnitude, got 1000.0 1/mm**3
And if I try:
a = pq.Quantity(500, "1000/mm**3")
The output is:
array(500) * 1/mm**3
i.e. The 1000 just gets ignored.
Any idea how can I fix this? Any workaround?
(The requirement arises from the standard practice followed in the domain.)
One possible solution I have found is to create new units such as this:
k_per_mm3 = pq.UnitQuantity('1000/mm3', 1e3/pq.mm**3, symbol='1000/mm3')
d1 = pq.Quantity(500, k_per_mm3)
Then on printing 'd1', I get:
array(500) * 1000/mm3
which is what I required.
Is this the only way to do this? Or can the same be achieved with existing units (which is preferable)?

Not aligned Sympy's nice pritting of division

I'm trying to nice print some divisions with Sympy but I noticed it didn't display aligned.
import sympy
sympy.init_printing(use_unicode=True)
sympy.pprint(sympy.Mul(-1, sympy.Pow(-5, -1, evaluate=False), evaluate=False))
# Output:
# -1
# ───
# -5 # Note that "-5" is displayed slightly more on the right than "-1".
Reason/fix for this?
EDIT: I did a lot of reverse-engineering using inspect.getsource and inspect.getsourcefile but it didn't really help out in the end.
Pretty Printing in Sympy seems to be relying on the Prettyprinter by Jurjen Bos.
import sympy
from sympy.printing.pretty.stringpict import *
sympy.init_printing(use_unicode=True)
prettyForm("-1")/prettyForm("-5")
# Displays:
# -1
# --
# -5
So it does display aligned, but I can't get it to use unicode.
The PrettyPrinter is called from the file sympy/printing/pretty/pretty.py in the method PrettyPrinter._print_Mul which simply return prettyForm.__mul__(*a)/prettyForm.__mul__(*b) with, I thought, a and b simply being ['-1'] and ['-5'] but it wouldn't work.
Found out where the weird part is coming from:
stringpict.py line 417:
if num.binding==prettyForm.NEG:
num = num.right(" ")[0]
This is being done ONLY for the numerator. It adds a space after the numerator if the numerator is negative… Weird!
I'm not sure if there can be a fixed other than directly editing the file. I'm going to report this on Github.
Thanks all for your help and suggestion.
PS: In the end, I used pdb to help me debug and figure out what was actually going out!
EDIT: Hotfix if you can't / don't want to edit the code source:
import sympy
sympy.init_printing(use_unicode=True)
from sympy.printing.pretty.stringpict import prettyForm, stringPict
def newDiv(self, den, slashed=False):
if slashed:
raise NotImplementedError("Can't do slashed fraction yet")
num = self
if num.binding == prettyForm.DIV:
num = stringPict(*num.parens())
if den.binding == prettyForm.DIV:
den = stringPict(*den.parens())
return prettyForm(binding=prettyForm.DIV, *stringPict.stack(
num,
stringPict.LINE,
den))
prettyForm.__div__ = newDiv
sympy.pprint(sympy.Mul(-1, sympy.Pow(-5, -1, evaluate=False), evaluate=False))
# Displays properly:
# -1
# ──
# -5
I just copied the function from the code source and removed the incriminated line.
Possible improvement could be to functools.wraps the new function with the original one.
Negative denominators are not standard and badly handled. If you really need them, you can modify the string outpout given by the pretty function :
import sympy
sympy.init_printing(use_unicode=True)
def ppprint(expr):
p=sympy.pretty(expr)
s=p.split('\n')
if len(s)==3 and int(s[2])<0:
s[0]=" "+s[0]
s[1]=s[1][0]+s[1]
p2="\n".join(s)
print(p2)
else: print(p)
This extend the bar and the numerator of one unit for negative denominators. No warranty of robustness on big expressions.
>>>> ppprint(sympy.Mul(sympy.Pow(-5, -1,evaluate=False),-1,evaluate=False))
-1
────
-5
I was not quite sure what you are searching for, but I think I was dealing with something similar a while ago.
I got a comprehension list and used this for printing.
You may find it useful.
x = amp * np.sin( 2 * np.pi * 200 * times ) + nse1
x2 = np.array_split(x,epochs(
Rxy[i], freqs_xy = mlab.csd(x2[i], y2[i], NFFT=nfft, Fs=sfreq)
Rxy_mean0 = [complex(sum(x)/len(x)) for x in Rxy]
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(Rxy_mean0)

Round in numpy to Nearest Step

I would like to know how I can round a number in numpy to an upper or lower threshold which is function of predefined step size. Hopefully stated in a clearer way, if I have the number 123 and a step size equal to 50, I need to round 123 to the closest of either 150 or 100, in this case 100. I came out with function below which does the work but I wonder if there is a better, more succint, way to do this.
Thanks in advance,
Paolo
def getRoundedThresholdv1(a, MinClip):
import numpy as np
import math
digits = int(math.log10(MinClip))+1
b = np.round(a, -digits)
if b > a: # rounded-up
c = b - MinClip
UpLow = np.array((b,c))
else: # rounded-down
c = b + MinClip
UpLow = np.array((c,b))
AbsDelta = np.abs(a - UpLow)
return UpLow[AbsDelta.argmin()]
getRoundedThresholdv1(143, 50)
The solution by pb360 is much better, using the second argument of builtin round in python3.
I think you don't need numpy:
def getRoundedThresholdv1(a, MinClip):
return round(float(a) / MinClip) * MinClip
here a is a single number, if you want to vectorize this function you only need to replace round with np.round and float(a) with np.array(a, dtype=float)
Summary: This is a correct way to do it, the top answer has cases that do not work:
def round_step_size(quantity: Union[float, Decimal], step_size: Union[float, Decimal]) -> float:
"""Rounds a given quantity to a specific step size
:param quantity: required
:param step_size: required
:return: decimal
"""
precision: int = int(round(-math.log(step_size, 10), 0))
return float(round(quantity, precision))
My reputation is too low to post a comment on the top answer from Ruggero Turra and point out the issue. However it has cases which did not work for example:
def getRoundedThresholdv1(a, MinClip):
return round(float(a) / MinClip) * MinClip
getRoundedThresholdv1(quantity=13.200000000000001, step_size=0.0001)
Returns 13.200000000000001 right back whether using numpy or the standard library round. I didn't even find this by stress testing the function. It just came up when using it in production code and spat an error.
Note full credit for this answer comes out of an open source github repo which is not mine found here
Note that round() in Ruggero Turra his answer rounds to the nearest even integer. Meaning:
a= 0.5
round(a)
Out: 0
Which may not be what you expect.
In case you want 'classical' rounding, you can use this function, which supports both scalars and Numpy arrays:
import Numpy as np
def getRoundedThresholdv1(a, MinClip):
scaled = a/MinClip
return np.where(scaled % 1 >= 0.5, np.ceil(scaled), np.floor(scaled))*MinClip
Alternatively, you could use Numpy's method digitize. It requires you to define the array of your steps. digitize will kind of ceil your value to the next step. So in order to round in a 'classical' way we need an intermediate step.
You can use this:
import Numpy as np
def getRoundedThresholdv1(a, MinClipBins):
intermediate = (MinClipBins[1:] + MinClipBins[:-1])/2
return MinClipBins[np.discritize(a, intermediate)]
You can then call it like:
bins = np.array([0, 50, 100, 150])
test1 = getRoundedThresholdv1(74, bins)
test2 = getRoundedThresholdv1(125, bins)
Which gives:
test1 = 50
test2 = 150

Categories

Resources