python实现 设测试数据集的真实标签是[0, 0, 0, 1, 1, 1, 1, 0],根据模型预测得到的标签是[1, 0, 1, 0, 0, 1, 1, 1],请计算该预测模型的正确率、精准率、召回率、F1分数,并编码实现计算过程。
时间: 2023-10-03 10:01:49 浏览: 55
首先,需要将真实标签和预测标签转化为numpy数组。
```python
import numpy as np
true_labels = np.array([0, 0, 0, 1, 1, 1, 1, 0])
predicted_labels = np.array([1, 0, 1, 0, 0, 1, 1, 1])
```
接着,我们可以计算正确率(Accuracy),即预测正确的样本数占总样本数的比例。
```python
accuracy = np.mean(true_labels == predicted_labels)
print(f"Accuracy: {accuracy:.2f}")
```
输出:Accuracy: 0.62
然后,我们可以计算精准率(Precision)和召回率(Recall)。
```python
true_positives = np.sum((true_labels == 1) & (predicted_labels == 1))
false_positives = np.sum((true_labels == 0) & (predicted_labels == 1))
false_negatives = np.sum((true_labels == 1) & (predicted_labels == 0))
precision = true_positives / (true_positives + false_positives)
recall = true_positives / (true_positives + false_negatives)
print(f"Precision: {precision:.2f}")
print(f"Recall: {recall:.2f}")
```
输出:Precision: 0.75, Recall: 0.67
最后,我们可以计算F1分数(F1 Score),它是精准率和召回率的调和平均数。
```python
f1_score = 2 * precision * recall / (precision + recall)
print(f"F1 Score: {f1_score:.2f}")
```
输出:F1 Score: 0.71
完整代码如下:
```python
import numpy as np
true_labels = np.array([0, 0, 0, 1, 1, 1, 1, 0])
predicted_labels = np.array([1, 0, 1, 0, 0, 1, 1, 1])
accuracy = np.mean(true_labels == predicted_labels)
print(f"Accuracy: {accuracy:.2f}")
true_positives = np.sum((true_labels == 1) & (predicted_labels == 1))
false_positives = np.sum((true_labels == 0) & (predicted_labels == 1))
false_negatives = np.sum((true_labels == 1) & (predicted_labels == 0))
precision = true_positives / (true_positives + false_positives)
recall = true_positives / (true_positives + false_negatives)
print(f"Precision: {precision:.2f}")
print(f"Recall: {recall:.2f}")
f1_score = 2 * precision * recall / (precision + recall)
print(f"F1 Score: {f1_score:.2f}")
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)