def reccomandation(self, x):
""""""
y = np.array([[math.nan] * nombre_films()])
for key in self.films:
y[0][self.conv.renvoyer_index(key)] = self.films[key]
max_i = 0
n_max = 0
t = np.dot(x, self._theta.T)
print(t)
for i, el in enumerate(y[0]):
if np.isnan(el) and t[i, 0] > n_max:
print("film : ", self.conv.renvoyer_nom_index(i), "note :", n_max)
n_max = t[i, 0]
max_i = i
print(t)
print(self._theta)
return self.conv.renvoyer_nom_index(max_i)
python类isnan()的实例源码
def sous_ensemble():
"""Renvoie un sous_tableau sans nan en regardant les films les plus regardes et prend
les utlisateurs present
dans ces films"""
tableau = tableau_des_notes()
reduit = [(tableau[:,i][~np.isnan(tableau[:,i])], i) for i in range(9125)]
trie = sorted(reduit, reverse=True, key=lambda entree: len(entree[0]))
utilisateurs_ayant_vu_le_premier_film = [i for i, u in enumerate(tableau[: ,trie[0][1]]) \
if not math.isnan(u)]
utilisateurs_ayant_vu_les_film = [u for u in utilisateurs_ayant_vu_le_premier_film \
if a_vu_tout_les_films(u, trie, tableau)]
index_11_premiers_films = [trie[i][1] for i in range(11)]
tableau_concentre = [[note for i, note in enumerate(tableau[u]) if\
(i in index_11_premiers_films)] \
for u in utilisateurs_ayant_vu_les_film]
return tableau_concentre
def reccomandation(self, x):
""""""
y = np.array([[math.nan] * nombre_films()])
for key in self.films:
y[0][self.conv.renvoyer_index(key)] = self.films[key]
max_i = 0
n_max = 0
t = np.dot(x, self._theta.T)
print(t)
for i, el in enumerate(y[0]):
if np.isnan(el) and t[i, 0] > n_max:
print("film : ", self.conv.renvoyer_nom_index(i), "note :", n_max)
n_max = t[i, 0]
max_i = i
print(t)
print(self._theta)
return self.conv.renvoyer_nom_index(max_i)
def generate_data_fn2(rows, cnt, x_low, x_high, fn):
x_array = []
y_array = []
while (len(x_array) < rows):
args = []
for i in range(cnt):
args.append(np.random.uniform(x_low, x_high))
try:
y = fn(*args)
if not math.isnan(y):
x_array.append(args)
y_array.append(y)
except (ValueError, ZeroDivisionError):
pass
return np.array(x_array, dtype=np.float32), np.array(y_array, dtype=np.float32)
# Generate data for the ratio experiment
def runScript(query_dist,dm_dict,pears_ids):
best_pears=[]
#############################################################
#Calculate score for each pear in relation to the user query
#############################################################
if len(query_dist) > 0:
pears_scores={}
for pear_name,v in pears_ids.items():
scoreSIM = 0.0 #Initialise score for similarity
score=cosine_similarity(np.array(v),query_dist)
if not isnan(score):
pears_scores[pear_name]=score
print pear_name,score
best_pears=outputBestPears(pears_scores)
return best_pears
def getColorEntry(val, args):
if not args.colorized:
return ""
if not isinstance(val, float) or math.isnan(val):
return colors.ENDC
if (val < .20):
return colors.RED
elif (val < .40):
return colors.YELLOW
elif (val < .60):
return colors.BLUE
elif (val < .80):
return colors.CYAN
else:
return colors.GREEN
# Cityscapes files have a typical filename structure
# <city>_<sequenceNb>_<frameNb>_<type>[_<type2>].<ext>
# This class contains the individual elements as members
# For the sequence and frame number, the strings are returned, including leading zeros
def __init__(self, lower, upper=None, msg=None, **kwds):
lower, upper, msg = _normalize_deviation_args(lower, upper, msg)
normalize_numbers = lambda x: x if x else 0
def function(diff):
if not isinstance(diff, xDeviation):
return False
value = normalize_numbers(diff.value) # Closes over normalize_numbers().
required = normalize_numbers(diff.required)
if isnan(value) or isnan(required):
return False
if value != 0 and required == 0:
return False
percent = value / required if required else 0 # % error calc.
return lower <= percent <= upper # Closes over *lower* and *upper*.
function.__name__ = self.__class__.__name__
super(allow_percent_deviation, self).__init__(function, msg, **kwds)
#_prettify_deviation_signature(allow_percent_deviation.__init__)
def percent_deviation(self):
expected = self.expected
if isinstance(expected, float):
expected = Decimal.from_float(expected)
else:
expected = Decimal(expected if expected else 0)
deviation = self.deviation
if isinstance(deviation, float):
deviation = Decimal.from_float(deviation)
else:
deviation = Decimal(deviation if deviation else 0)
if isnan(expected) or isnan(deviation):
return Decimal('NaN')
return deviation / expected if expected else Decimal(0) # % error calc.
def _from_float(cls, f):
if isinstance(f, int): # handle integer inputs
return cls(f)
if not isinstance(f, float):
raise TypeError("argument must be int or float.")
if _math.isinf(f) or _math.isnan(f):
return cls(repr(f))
if _math.copysign(1.0, f) == 1.0:
sign = 0
else:
sign = 1
n, d = abs(f).as_integer_ratio()
#k = d.bit_length() - 1
k = _bit_length(d) - 1
result = _dec_from_triple(sign, str(n*5**k), -k)
if cls is Decimal:
return result
else:
return cls(result)
def assertFloatIdentical(self, x, y):
"""Fail unless floats x and y are identical, in the sense that:
(1) both x and y are nans, or
(2) both x and y are infinities, with the same sign, or
(3) both x and y are zeros, with the same sign, or
(4) x and y are both finite and nonzero, and x == y
"""
msg = 'floats {!r} and {!r} are not identical'
if math.isnan(x) or math.isnan(y):
if math.isnan(x) and math.isnan(y):
return
elif x == y:
if x != 0.0:
return
# both zero; check that signs match
elif math.copysign(1.0, x) == math.copysign(1.0, y):
return
else:
msg += ': zeros have different signs'
self.fail(msg.format(x, y))
def testCeil(self):
self.assertRaises(TypeError, math.ceil)
self.assertEqual(int, type(math.ceil(0.5)))
self.ftest('ceil(0.5)', math.ceil(0.5), 1)
self.ftest('ceil(1.0)', math.ceil(1.0), 1)
self.ftest('ceil(1.5)', math.ceil(1.5), 2)
self.ftest('ceil(-0.5)', math.ceil(-0.5), 0)
self.ftest('ceil(-1.0)', math.ceil(-1.0), -1)
self.ftest('ceil(-1.5)', math.ceil(-1.5), -1)
#self.assertEqual(math.ceil(INF), INF)
#self.assertEqual(math.ceil(NINF), NINF)
#self.assertTrue(math.isnan(math.ceil(NAN)))
class TestCeil:
def __ceil__(self):
return 42
class TestNoCeil:
pass
self.ftest('ceil(TestCeil())', math.ceil(TestCeil()), 42)
self.assertRaises(TypeError, math.ceil, TestNoCeil())
t = TestNoCeil()
t.__ceil__ = lambda *args: args
self.assertRaises(TypeError, math.ceil, t)
self.assertRaises(TypeError, math.ceil, t, 0)
def testFmod(self):
self.assertRaises(TypeError, math.fmod)
self.ftest('fmod(10,1)', math.fmod(10,1), 0)
self.ftest('fmod(10,0.5)', math.fmod(10,0.5), 0)
self.ftest('fmod(10,1.5)', math.fmod(10,1.5), 1)
self.ftest('fmod(-10,1)', math.fmod(-10,1), 0)
self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0)
self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1)
self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
self.assertTrue(math.isnan(math.fmod(1., NAN)))
self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
self.assertRaises(ValueError, math.fmod, 1., 0.)
self.assertRaises(ValueError, math.fmod, INF, 1.)
self.assertRaises(ValueError, math.fmod, NINF, 1.)
self.assertRaises(ValueError, math.fmod, INF, 0.)
self.assertEqual(math.fmod(3.0, INF), 3.0)
self.assertEqual(math.fmod(-3.0, INF), -3.0)
self.assertEqual(math.fmod(3.0, NINF), 3.0)
self.assertEqual(math.fmod(-3.0, NINF), -3.0)
self.assertEqual(math.fmod(0.0, 3.0), 0.0)
self.assertEqual(math.fmod(0.0, NINF), 0.0)
def testModf(self):
self.assertRaises(TypeError, math.modf)
def testmodf(name, result, expected):
(v1, v2), (e1, e2) = result, expected
if abs(v1-e1) > eps or abs(v2-e2):
self.fail('%s returned %r, expected %r'%\
(name, result, expected))
testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
self.assertEqual(math.modf(INF), (0.0, INF))
self.assertEqual(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
self.assertTrue(math.isnan(modf_nan[0]))
self.assertTrue(math.isnan(modf_nan[1]))
def assertFloatsAreIdentical(self, x, y):
"""assert that floats x and y are identical, in the sense that:
(1) both x and y are nans, or
(2) both x and y are infinities, with the same sign, or
(3) both x and y are zeros, with the same sign, or
(4) x and y are both finite and nonzero, and x == y
"""
msg = 'floats {!r} and {!r} are not identical'
if isnan(x) or isnan(y):
if isnan(x) and isnan(y):
return
elif x == y:
if x != 0.0:
return
# both zero; check that signs match
elif copysign(1.0, x) == copysign(1.0, y):
return
else:
msg += ': zeros have different signs'
self.fail(msg.format(x, y))
json_format.py 文件源码
项目:ios-xr-grpc-python
作者: cisco-grpc-connection-libs
项目源码
文件源码
阅读 37
收藏 0
点赞 0
评论 0
def _FieldToJsonObject(self, field, value):
"""Converts field value according to Proto3 JSON Specification."""
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
return self._MessageToJsonObject(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
enum_value = field.enum_type.values_by_number.get(value, None)
if enum_value is not None:
return enum_value.name
else:
raise SerializeToJsonError('Enum field contains an integer value '
'which can not mapped to an enum value.')
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
# Use base64 Data encoding for bytes
return base64.b64encode(value).decode('utf-8')
else:
return value
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
return bool(value)
elif field.cpp_type in _INT64_TYPES:
return str(value)
elif field.cpp_type in _FLOAT_TYPES:
if math.isinf(value):
if value < 0.0:
return _NEG_INFINITY
else:
return _INFINITY
if math.isnan(value):
return _NAN
return value
def format_value(value, format_type):
if format_type == 'string':
return str(value)
value = value if not math.isnan(float(value)) else 0
if format_type == 'percent':
return '{:.1%}'.format(float(value))
elif format_type == 'integer':
return '{:,d}'.format(int(value))
elif format_type[0] == '%':
return format_type % float(value)
raise Exception('Invalid format type: %s' % format_type)
def json_sanitize(data):
# This really doesn't make me happy. How many cases we we have to test?
if (type(data) == float) or (type(data) == numpy.float64):
# Handle floats specially
if math.isnan(data):
return "NaN";
if (data == float("+Inf")):
return "inf"
if (data == float("-Inf")):
return "-inf"
return data
elif hasattr(data, 'iterkeys'):
# Dictionary case
new_data = {}
for k in data.keys():
new_data[k] = json_sanitize(data[k])
return new_data
elif hasattr(data, '__iter__'):
# Anything else that looks like a list. N
new_data = []
for d in data:
new_data.append(json_sanitize(d))
return new_data
elif hasattr(data, 'shape') and data.shape == ():
# Numpy 0-d array
return np.asscalar(data)
else:
return data
def from_float(cls, f):
"""Converts a float to a decimal number, exactly.
Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
Since 0.1 is not exactly representable in binary floating point, the
value is stored as the nearest representable value which is
0x1.999999999999ap-4. The exact equivalent of the value in decimal
is 0.1000000000000000055511151231257827021181583404541015625.
>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(-float('inf'))
Decimal('-Infinity')
>>> Decimal.from_float(-0.0)
Decimal('-0')
"""
if isinstance(f, (int, long)): # handle integer inputs
return cls(f)
if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
return cls(repr(f))
if _math.copysign(1.0, f) == 1.0:
sign = 0
else:
sign = 1
n, d = abs(f).as_integer_ratio()
k = d.bit_length() - 1
result = _dec_from_triple(sign, str(n*5**k), -k)
if cls is Decimal:
return result
else:
return cls(result)
def from_float(cls, f):
"""Converts a finite float to a rational number, exactly.
Beware that Fraction.from_float(0.3) != Fraction(3, 10).
"""
if isinstance(f, numbers.Integral):
return cls(f)
elif not isinstance(f, float):
raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
(cls.__name__, f, type(f).__name__))
if math.isnan(f) or math.isinf(f):
raise TypeError("Cannot convert %r to %s." % (f, cls.__name__))
return cls(*f.as_integer_ratio())