numpy.testing.utils




参考  numpy.testing.utils - 云+社区 - 腾讯云
(val, msg='')

Assert that works in release mode.

assert_almost_equal(actual, desired, decimal=7, err_msg='', verbose=True)

Raise an assertion if two items are not equal up to desired precision.
 
The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal)
 
Given two objects (numbers or ndarrays), check that all elements of these
objects are almost equal. An exception is raised at conflicting values.
For ndarrays this delegates to assert_array_almost_equal
 
Parameters
----------
actual : number or ndarray
  The object to check.
desired : number or ndarray
  The expected object.
decimal : integer (decimal=7)
  desired precision
err_msg : string
  The error message to be printed in case of failure.
verbose : bool
  If True, the conflicting values are appended to the error message.
 
Raises
------
AssertionError
  If actual and desired are not equal up to specified precision.
 
See Also
--------
assert_array_almost_equal: compares array_like objects
assert_equal: tests objects for equality
 
 
Examples
--------
>>> npt.assert_almost_equal(2.3333333333333, 2.33333334)
>>> npt.assert_almost_equal(2.3333333333333, 2.33333334, decimal=10)
...
<type 'exceptions.AssertionError'>:
Items are not equal:
 ACTUAL: 2.3333333333333002
 DESIRED: 2.3333333399999998
 
>>> npt.assert_almost_equal(np.array([1.0,2.3333333333333]),
                    np.array([1.0,2.33333334]), decimal=9)
...
<type 'exceptions.AssertionError'>:
Arrays are not almost equal
<BLANKLINE>
(mismatch 50.0%)
 x: array([ 1.        ,  2.33333333])
 y: array([ 1.        ,  2.33333334])

assert_approx_equal(actual, desired, significant=7, err_msg='', verbose=True)

Raise an assertion if two items are not equal up to significant digits.
 
Given two numbers, check that they are approximately equal.
Approximately equal is defined as the number of significant digits
that agree.
 
Parameters
----------
actual : number
  The object to check.
desired : number
  The expected object.
significant : integer (significant=7)
  desired precision
err_msg : string
  The error message to be printed in case of failure.
verbose : bool
  If True, the conflicting values are appended to the error message.
 
Raises
------
AssertionError
  If actual and desired are not equal up to specified precision.
 
See Also
--------
assert_almost_equal: compares objects by decimals
assert_array_almost_equal: compares array_like objects by decimals
assert_equal: tests objects for equality
 
 
Examples
--------
>>> np.testing.assert_approx_equal(0.12345677777777e-20, 0.1234567e-20)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345671e-20,
                                   significant=8)
>>> np.testing.assert_approx_equal(0.12345670e-20, 0.12345672e-20,
                                   significant=8)
...
<type 'exceptions.AssertionError'>:
Items are not equal to 8 significant digits:
 ACTUAL: 1.234567e-021
 DESIRED: 1.2345672000000001e-021
 
the evaluated condition that raises the exception is
 
>>> abs(0.12345670e-20/1e-21 - 0.12345672e-20/1e-21) >= 10**-(8-1)
True

assert_array_almost_equal(x, y, decimal=6, err_msg='', verbose=True)

Raise an assertion if two objects are not equal up to desired precision.
 
The test verifies identical shapes and verifies values with
abs(desired-actual) < 0.5 * 10**(-decimal)
 
Given two array_like objects, check that the shape is equal and all
elements of these objects are almost equal. An exception is raised at
shape mismatch or conflicting values. In contrast to the standard usage
in numpy, NaNs are compared like numbers, no assertion is raised if
both objects have NaNs in the same positions.
 
Parameters
----------
x : array_like
  The actual object to check.
y : array_like
  The desired, expected object.
decimal : integer (decimal=6)
  desired precision
err_msg : string
  The error message to be printed in case of failure.
verbose : bool
    If True, the conflicting values are appended to the error message.
 
Raises
------
AssertionError
  If actual and desired are not equal up to specified precision.
 
See Also
--------
assert_almost_equal: simple version for comparing numbers
assert_array_equal: tests objects for equality
 
 
Examples
--------
the first assert does not raise an exception
 
>>> np.testing.assert_array_almost_equal([1.0,2.333,np.nan],
                                         [1.0,2.333,np.nan])
 
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
                    [1.0,2.33339,np.nan], decimal=5)
...
<type 'exceptions.AssertionError'>:
AssertionError:
Arrays are not almost equal
<BLANKLINE>
(mismatch 50.0%)
 x: array([ 1.     ,  2.33333,      NaN])
 y: array([ 1.     ,  2.33339,      NaN])
 
>>> np.testing.assert_array_almost_equal([1.0,2.33333,np.nan],
                    [1.0,2.33333, 5], decimal=5)
<type 'exceptions.ValueError'>:
ValueError:
Arrays are not almost equal
 x: array([ 1.     ,  2.33333,      NaN])
 y: array([ 1.     ,  2.33333,  5.     ])

assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='')

assert_array_equal(x, y, err_msg='', verbose=True)

Raise an assertion if two array_like objects are not equal.
 
Given two array_like objects, check that the shape is equal and all
elements of these objects are equal. An exception is raised at
shape mismatch or conflicting values. In contrast to the standard usage
in numpy, NaNs are compared like numbers, no assertion is raised if
both objects have NaNs in the same positions.
 
The usual caution for verifying equality with floating point numbers is
advised.
 
Parameters
----------
x : array_like
  The actual object to check.
y : array_like
  The desired, expected object.
err_msg : string
  The error message to be printed in case of failure.
verbose : bool
    If True, the conflicting values are appended to the error message.
 
Raises
------
AssertionError
  If actual and desired objects are not equal.
 
See Also
--------
assert_array_almost_equal: test objects for equality up to precision
assert_equal: tests objects for equality
 
 
Examples
--------
the first assert does not raise an exception
 
>>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
                    [np.exp(0),2.33333, np.nan])
 
assert fails with numerical inprecision with floats
 
>>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
                    [1, np.sqrt(np.pi)**2, np.nan])
...
<type 'exceptions.ValueError'>:
AssertionError:
Arrays are not equal
<BLANKLINE>
(mismatch 50.0%)
 x: array([ 1.        ,  3.14159265,         NaN])
 y: array([ 1.        ,  3.14159265,         NaN])
 
use assert_array_almost_equal for these cases instead
 
>>> np.testing.assert_array_almost_equal([1.0,np.pi,np.nan],
                    [1, np.sqrt(np.pi)**2, np.nan], decimal=15)

assert_array_less(x, y, err_msg='', verbose=True)

Raise an assertion if two array_like objects are not ordered by less than.
 
Given two array_like objects, check that the shape is equal and all
elements of the first object are strictly smaller than those of the
second object. An exception is raised at shape mismatch or incorrectly
ordered values. Shape mismatch does not raise if an object has zero
dimension. In contrast to the standard usage in numpy, NaNs are
compared, no assertion is raised if both objects have NaNs in the same
positions.
 
 
 
Parameters
----------
x : array_like
  The smaller object to check.
y : array_like
  The larger object to compare.
err_msg : string
  The error message to be printed in case of failure.
verbose : bool
    If True, the conflicting values are appended to the error message.
 
Raises
------
AssertionError
  If actual and desired objects are not equal.
 
See Also
--------
assert_array_equal: tests objects for equality
assert_array_almost_equal: test objects for equality up to precision
 
 
 
Examples
--------
>>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1.1, 2.0, np.nan])
>>> np.testing.assert_array_less([1.0, 1.0, np.nan], [1, 2.0, np.nan])
...
<type 'exceptions.ValueError'>:
Arrays are not less-ordered
(mismatch 50.0%)
 x: array([  1.,   1.,  NaN])
 y: array([  1.,   2.,  NaN])
 
>>> np.testing.assert_array_less([1.0, 4.0], 3)
...
<type 'exceptions.ValueError'>:
Arrays are not less-ordered
(mismatch 50.0%)
 x: array([ 1.,  4.])
 y: array(3)
 
>>> np.testing.assert_array_less([1.0, 2.0, 3.0], [4])
...
<type 'exceptions.ValueError'>:
Arrays are not less-ordered
(shapes (3,), (1,) mismatch)
 x: array([ 1.,  2.,  3.])
 y: array([4])

assert_equal(actual, desired, err_msg='', verbose=True)

Raise an assertion if two objects are not equal.
 
Given two objects (lists, tuples, dictionaries or numpy arrays), check
that all elements of these objects are equal. An exception is raised at
the first conflicting values.
 
Parameters
----------
actual : list, tuple, dict or ndarray
  The object to check.
desired : list, tuple, dict or ndarray
  The expected object.
err_msg : string
  The error message to be printed in case of failure.
verbose : bool
  If True, the conflicting values are appended to the error message.
 
Raises
------
AssertionError
  If actual and desired are not equal.
 
Examples
--------
>>> np.testing.assert_equal([4,5], [4,6])
...
<type 'exceptions.AssertionError'>:
Items are not equal:
item=1
 ACTUAL: 5
 DESIRED: 6

assert_raises(*args, **kwargs)

assert_raises(excecption_class, callable, *args, **kwargs)
 
Fail unless an exception of class exception_class is thrown
by callable when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.

assert_string_equal(actual, desired)

build_err_msg(arrays, err_msg, header='Items are not equal:', verbose=True, names=('ACTUAL', 'DESIRED'))

decorate_methods(cls, decorator, testmatch=None)

Apply decorator to all methods in class matching testmatch
 
Parameters
----------
cls : class
    Class to decorate methods for
decorator : function
    Decorator to apply to methods
testmatch : compiled regexp or string to compile to regexp
    Decorators are applied if testmatch.search(methodname)
    is not None.  Default value is
    re.compile(r'(?:^|[\b_\.%s-])[Tt]est' % os.sep)
    (the default for nose)

jiffies(_proc_pid_stat='/proc/17578/stat', _load_time=[])

Return number of jiffies (1/100ths of a second) that this
process has been scheduled in user mode. See man 5 proc.

measure(code_str, times=1, label=None)

Return elapsed time for executing code_str in the
namespace of the caller for given times.

memusage(_proc_pid_stat='/proc/17578/stat')

Return virtual memory size in bytes of the running python.

print_assert_equal(test_string, actual, desired)

raises(*args, **kwargs)

rand(*args)

Returns an array of random numbers with the given shape.
 
This only uses the standard library, so it is useful for testing purposes.

rundocs(filename=None)

Run doc string tests found in filename.

runstring(astr, dict)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
import numpy as np import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt Let us define a plt function for simplicity def plt_loss(x,training_metric,testing_metric,ax,colors = ['b']): ax.plot(x,training_metric,'b',label = 'Train') ax.plot(x,testing_metric,'k',label = 'Test') ax.set_xlabel('Epochs') ax.set_ylabel('Accuracy') plt.legend() plt.grid() plt.show() tf.keras.utils.set_random_seed(1) We import the Minist Dataset using Keras.datasets (train_data, train_labels), (test_data, test_labels) = keras.datasets.mnist.load_data() We first vectorize the image (28*28) into a vector (784) train_data = train_data.reshape(train_data.shape[0],train_data.shape[1]train_data.shape[2]) # 60000784 test_data = test_data.reshape(test_data.shape[0],test_data.shape[1]test_data.shape[2]) # 10000784 We next change label number to a 10 dimensional vector, e.g., 1-> train_labels = keras.utils.to_categorical(train_labels,10) test_labels = keras.utils.to_categorical(test_labels,10) start to build a MLP model N_batch_size = 5000 N_epochs = 100 lr = 0.01 we build a three layer model, 784 -> 64 -> 10 MLP_3 = keras.models.Sequential([ keras.layers.Dense(128, input_shape=(784,),activation='relu'), keras.layers.Dense(64, activation='relu'), keras.layers.Dense(10,activation='softmax') ]) MLP_3.compile( optimizer=keras.optimizers.Adam(lr), loss= 'categorical_crossentropy', metrics = ['accuracy'] ) History = MLP_3.fit(train_data,train_labels, batch_size = N_batch_size, epochs = N_epochs,validation_data=(test_data,test_labels), shuffle=False) train_acc = History.history['accuracy'] test_acc = History.history对于该模型,使用不同数量的训练数据(5000,10000,15000,…,60000,公差=5000的等差数列),绘制训练集和测试集准确率(纵轴)关于训练数据大小(横轴)的曲线
06-01
import numpy as np import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt ## Let us define a plt function for simplicity def plt_loss(x,training_metric,testing_metric,ax,colors = ['b']): ax.plot(x,training_metric,'b',label = 'Train') ax.plot(x,testing_metric,'k',label = 'Test') ax.set_xlabel('Epochs') ax.set_ylabel('Accuarcy')# ax.set_ylabel('Categorical Crossentropy Loss') plt.legend() plt.grid() plt.show() tf.keras.utils.set_random_seed(1) ## We import the Minist Dataset using Keras.datasets (train_data, train_labels), (test_data, test_labels) = keras.datasets.mnist.load_data() ## We first vectorize the image (28*28) into a vector (784) train_data = train_data.reshape(train_data.shape[0],train_data.shape[1]*train_data.shape[2]) # 60000*784 test_data = test_data.reshape(test_data.shape[0],test_data.shape[1]*test_data.shape[2]) # 10000*784 ## We next change label number to a 10 dimensional vector, e.g., 1->[0,1,0,0,0,0,0,0,0,0] train_labels = keras.utils.to_categorical(train_labels,10) test_labels = keras.utils.to_categorical(test_labels,10) ## start to build a MLP model N_batch_size = 5000 N_epochs = 100 lr = 0.01 # ## we build a three layer model, 784 -> 64 -> 10 MLP_3 = keras.models.Sequential([ keras.layers.Dense(64, input_shape=(784,),activation='relu'), keras.layers.Dense(10,activation='softmax') ]) MLP_3.compile( optimizer=keras.optimizers.Adam(lr), loss= 'categorical_crossentropy', metrics = ['accuracy'] ) History = MLP_3.fit(train_data,train_labels, batch_size = N_batch_size, epochs = N_epochs,validation_data=(test_data,test_labels), shuffle=False) train_acc = History.history['accuracy'] test_acc = History.history['val_accuracy']模仿此段代码,写一个双隐层感知器(输入层784,第一隐层128,第二隐层64,输出层10)
06-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wanderer001

ROIAlign原理

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值