代码之家  ›  专栏  ›  技术社区  ›  Andre Araujo

我可以在unittest中比较两个浮点数的相似性而不是相等性吗?

  •  2
  • Andre Araujo  · 技术社区  · 7 年前

    我在上面做了这个测试。我的问题是,在训练我的机器学习模型之后,每次的结果都有点不同。

    所以,我想在我的Flask api中,当它们相似时,断言TRUE。

    这个 ChangeToSurvive 是一个 float ,有时也是如此 29.2 训练后再次换上 30.5 或者其他号码。

    def test_by_name(self):
        post_data = {
            'name': 'Andre'
        }
        resp = self.app.post('/survivals',
                             data=json.dumps(post_data),
                             content_type='application/json')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.content_type, 'application/json')
    
        content = json.loads(resp.get_data(as_text=True))
        size = len(content['Passengers'])
        self.assertEqual(size, 2)
    
        self.maxDiff = None 
    
        expected = {
    "Passengers": [
        {
            "SibSp": 1,
            "Sex": "0",
            "PassengerId": 925,
            "Survived": 1,
            "Parch": 2,
            "Age": 1,
            "Name": "Johnston, Mrs. Andrew G (Elizabeth Lily\" Watson)\"",
            "ChangeToSurvive": 74.7,
            "Embarked": "0"
        },
        {
            "SibSp": 0,
            "Sex": "1",
            "PassengerId": 1096,
            "Survived": 0,
            "Parch": 0,
            "Age": 1,
            "Name": "Andrew, Mr. Frank Thomas",
            "ChangeToSurvive": 29.2,
            "Embarked": "0"
        }
    ]
    }
        self.assertEqual(content, expected)   # each train in a model the ChangeToSurvive can a little diferrent
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   BartoszKP    7 年前

    unittest assertAlmostEqual 用于此目的的方法:

    actual_value = # extract float value from content
    expected_value = # extract float value from expected
    delta = 1.7
    self.assertAlmostEqual(actual_value, expected_value, delta = delta)
    

    你需要对你想要验证的字典中的所有值重复这个步骤。最好用测试实用程序方法来包装它。