RuntimeWarning: divide by zero encountered in divide average_loss1=np.sum(np.abs((predict-testY)/testY))/p
时间: 2024-04-30 20:22:29 浏览: 209
This warning occurs when the code tries to divide a number by zero. In this case, it is likely that the testY data contains some values that are zero, causing the division to fail. To avoid this warning, you can add a check to ensure that the denominator is not zero before dividing. For example:
```
mask = testY != 0
average_loss1 = np.sum(np.abs((predict-testY)/testY[mask])) / np.sum(mask)
```
This code creates a boolean mask to identify the non-zero values in testY, and then uses this mask to calculate the average loss only for those values.
相关问题
RuntimeWarning: divide by zero encountered in power d_inv_sqrt = np.power(rowsum, -0.5).flatten()
这个警告是因为有些行的元素和为0,导致在计算倒数平方根时出现了除以0的情况。你可以在代码中加入判断,避免除以0的情况发生,例如:
```python
rowsum = np.sum(adj_matrix, axis=1)
rowsum[rowsum == 0] = 1 # 避免除以0的情况
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
```
这样就可以避免出现警告了。
怎么修改m_lr_i = np.log(numerator / denominator),避免发生RuntimeWarning: divide by zero encountered in scalar divide m_lr_i = np.log(numerator / denominator)
可以使用类似第一段代码的方式来修改 `m_lr_i = np.log(numerator / denominator)`,避免出现 `RuntimeWarning: divide by zero encountered in scalar divide` 错误。具体来说,可以将代码修改为:
```
m_lr_i = np.log(np.divide(numerator, denominator, out=np.zeros_like(numerator), where=denominator!=0))
```
这样做的意义和第一段代码的意义是一样的,即先将分母中为0的元素替换成一个很小的非零数,然后进行除法运算并取对数。这样做能够避免分母为0导致的错误。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![whl](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![whl](https://img-home.csdnimg.cn/images/20250102104920.png)