import argparse
import json
import shutil
from django.utils import timezone
import torch.nn.functional as F
import numpy as np
import torch
from torchvision.models import resnet50
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views import View
from django.conf import settings
from django.core.files.storage import FileSystemStorage
import os
from detection.cts_predict import svm_predict, load_config, load_data, load_model
from detection.getTestInfo import getFileImgsNum, flattenList, classify_Img_byPatient, deal_patient_result, print_patientInfo, print_fault_patientInfo
from detection.model import ResNet50
from detection.resnet50_predict import resnet50_main
log_file = ''
resistance = '0'
# 上传测试集,接收测试集
class Upload(View):
"""预测功能:上传测试集"""
def get(self, request):
img_path = os.path.join(settings.MEDIA_ROOT, 'test')
if os.listdir(img_path):
# 检测之前情况上一次检测的残留图片
for f in os.listdir(img_path):
file_p = os.path.join(img_path, f)
try:
if os.path.isdir(file_p):
shutil.rmtree(file_p)
except:
pass
return render(request, 'detection/detection-upload.html', context={'message': "上传数据"})
def post(self, request):
try:
global resistance
# 将文件夹中的每一张图片都写入
resistance = request.POST.get('resistance') # 是否耐药
folder_name = request.POST.get('folder_name') # 患者姓名设置为文件夹名称
if resistance == '1':
fs = FileSystemStorage(location=settings.MEDIA_ROOT + '/test/Rifampicin-intolerant/' + folder_name)
elif resistance == '0':
fs = FileSystemStorage(location=settings.MEDIA_ROOT + '/test/Nelrifampicin/' + folder_name)
files = request.FILES.getlist('files')
for file in files:
fs.save(file.name, file)
return redirect('detection:execute_detection')
except Exception as e:
print(e)
return render(request, 'detection/detection-upload.html', context={'message': '上传出错,请重新上传'})
def execute_detection(request):
global log_file
# 创建日志文件
log_file_path = os.path.join(settings.STATICFILES_DIRS[0], 'predict_res')
if not os.path.exists(log_file_path):
os.makedirs(log_file_path)
log_file = log_file_path + '/predict.txt'
if not os.path.exists(log_file):
with open(log_file, 'a') as f:
f.write('[]')
# 获取参数
cst_args = load_config()
# 导入模型
resnet50_model = load_resnet_model()
# 加载数据集
test_dataset, test_loader = load_data(cst_args)
# 类别个数
num_classes = 2
# 获取当前数据集的图片大小维度
data, target = next(iter(test_loader))
# 初始化cst_model的参数
resolution = (data.shape[2], data.shape[3])
# 定义创建cst模型
cst_model = ResNet50(num_classes=num_classes, resolution=resolution, heads=4)
# 加载预训练权重
cst_model, svm_model = load_model(cst_args, cst_model)
# 获取数据集信息
file_datas = getFileImgsNum(test_dataset, os.path.join(cst_args.get('data_path'), 'test'))
predictions, labels, infos = predict(test_loader, resnet50_model, cst_model, svm_model, cst_args, file_datas)
# 每张图的预测结果统计
num1 = 0
num0 = 0
acc = 0
correct_count = int(request.COOKIES.get('correct'))
error_count = int(request.COOKIES.get('error'))
for cont in predictions[0]:
if cont:
num1 += 1
else:
num0 += 1
if resistance == '1':
print(f'患者{infos}应该是不耐药的')
result = '耐药' if num0 >= num1 else '不耐药'
if result == '不耐药':
correct_count += 1
acc = 1
print('预测正确')
else:
error_count += 1
acc = 0
print('预测错误')
elif resistance == '0':
print(f'患者{infos}应该是耐药的')
result = '耐药' if num0 >= num1 else '不耐药'
if result == '耐药':
correct_count += 1
acc = 1
print('预测正确')
else:
error_count += 1
acc = 0
print('预测错误')
# 返回预测结果到结果可视化界面
context = {
'predictions': predictions[0],
'labels': labels[0],
'x_label': [num0, num1],
'infos': infos,
'max': len(predictions[0]),
'result': '耐药' if num0 >= num1 else '不耐药',
'acc': '预测正确' if acc else '预测错误',
}
with open(log_file, 'r') as f:
text = f.read()
print('text', text)
json_data = json.loads(text)
print(json_data)
json_data.append({
"name": infos,
"acc": acc,
"datetime": timezone.now().strftime("%Y-%m-%d %H:%M:%S"),
})
with open(log_file, 'w') as f:
f.write(json.dumps(json_data))
response = render(request, 'detection/detection-visualization.html', context=context)
predict_count = int(request.COOKIES.get('predict'))
predict_count += 1
response.set_cookie('predict', predict_count)
response.set_cookie('correct', correct_count)
response.set_cookie('error', error_count)
return response
def predict(test_loader, resnet50_model, cst_model, svm_model, args, file_datas):
global log_file
resnet50_model.eval()
cst_model.eval()
acc = 0.
predicted_result = []
labels_result = []
# svm_mode = SVM_model(kernel='rbf', C=1.0, class_weight ='balanced')
with torch.no_grad():
for data, target in test_loader:
if args.get('cuda'):
data, target = data.cuda(), target.cuda()
output_resnet50 = resnet50_model(data)
output_cst = cst_model(data)
# 权重效果
# cst:275
# 0.1:0.9 Test Acc: 80.352
# 0.2:0.8 Test Acc: 81.496
# 0.3:0.7 Test Acc: 82.459
# 0.4:0.6 Test Acc: 83.112
# 0.5:0.5 Test Acc: 83.494
# 0.6:0.4 Test Acc: 83.657
# 0.7:0.3 Test Acc: 83.893 效果最好
# 0.8:0.2 Test Acc: 83.766
# 0.9:0.1 Test Acc: 83.131
resnet_b = 0.7
cts_b = 0.3
output = resnet_b*output_resnet50 + cts_b*output_cst
# SVM----------------------------------
# y_pred = svm_predict(output, data, target, svm_model, isTrain=False)
# target_numpy = target.cpu().numpy()
# ac = svm_mode.accuracy(target_numpy, y_pred)
# acc_current = np.count_nonzero(y_pred == target_numpy)
# acc += acc_current
# SVM----------------------------------
_, y_pred = F.softmax(output, dim=-1).max(1)
acc += y_pred.eq(target).sum().item()
# acc += acc_current
# 将predicted和labels转换为列表,并添加到对应的子列表中
predicted_result.append(y_pred.tolist())
labels_result.append(target.tolist())
# 将predicted_result中的多个子列表展开成一个平面列表
predicted_result, labels_result = flattenList(labels_result, predicted_result)
# 重新对结果进行分类,按照病人进行分类
predicted_result, labels_result = classify_Img_byPatient(file_datas, labels_result, predicted_result)
# 输出结果
# 最后的参数是阈值
correct_patient_labels, total_patient_labels, \
Filter_unqualified_data_infos, Filter_unqualified_data_Predictions,\
Filter_unqualified_data_Labels, Fil
没有合适的资源?快使用搜索试试~ 我知道了~
Python基于改进ResNet50的结核病基因耐药检测系统源代码
共837个文件
js:399个
css:203个
png:101个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
0 下载量 40 浏览量
2024-05-01
14:13:30
上传
评论
收藏 95.89MB ZIP 举报
温馨提示
介绍 本项目旨在改进ResNet50模型,设计一个CTS模型,该模型能够快速、经济且准确地利用CT肺部图像来评估结核病的耐药性。 系统架构 使用Django框架
资源推荐
资源详情
资源评论
收起资源包目录
Python基于改进ResNet50的结核病基因耐药检测系统源代码 (837个子文件)
bootstrap.min1.css 118KB
bootstrap.min2.css 118KB
bootstrap.min3.css 118KB
bootstrap.min4.css 118KB
main1.css 102KB
main2.css 95KB
main5.css 95KB
main3.css 95KB
main4.css 95KB
theme.css 93KB
animate2.css 68KB
animate.css 68KB
animate1.css 68KB
animate3.css 68KB
icomoon3.css 66KB
icomoon.css 36KB
icomoon1.css 33KB
icomoon4.css 33KB
icomoon2.css 33KB
font-awesome.css 33KB
font-awesome2.css 33KB
font-awesome3.css 33KB
font-awesome1.css 33KB
datepicker.css 22KB
datepicker4.css 21KB
datepicker3.css 21KB
datepicker2.css 21KB
datepicker1.css 21KB
_all11.css 20KB
_all7.css 20KB
_all3.css 20KB
_all15.css 20KB
lobipanel.css 15KB
lobipanel1.css 15KB
lobipanel3.css 15KB
lobipanel4.css 15KB
lobipanel2.css 15KB
fullcalendar.min2.css 15KB
fullcalendar.min3.css 15KB
fullcalendar.min1.css 15KB
fullcalendar.min.css 15KB
_all12.css 14KB
_all8.css 14KB
_all.css 14KB
_all16.css 14KB
_all4.css 14KB
_all5.css 14KB
_all17.css 14KB
_all1.css 14KB
_all13.css 14KB
_all9.css 14KB
custom3.css 13KB
custom4.css 13KB
custom2.css 13KB
custom1.css 13KB
custom.css 13KB
_all18.css 13KB
_all6.css 13KB
_all2.css 13KB
_all10.css 13KB
_all14.css 13KB
nv.d31.css 11KB
nv.d3.css 11KB
nv.d32.css 11KB
nv.d34.css 11KB
nv.d33.css 11KB
users3.css 10KB
users4.css 9KB
users2.css 9KB
custom-calendar3.css 8KB
custom-calendar1.css 8KB
custom-calendar4.css 8KB
custom-calendar.css 8KB
users.css 7KB
users1.css 7KB
custom-calendar2.css 7KB
main.css 6KB
pricing.css 6KB
login.css 6KB
login3.css 6KB
login1.css 6KB
bootstrap.min.css 6KB
coming-soon3.css 6KB
coming-soon2.css 6KB
editor1.css 6KB
editor3.css 6KB
editor.css 6KB
editor4.css 6KB
editor2.css 6KB
bar-indicator2.css 5KB
bar-indicator3.css 5KB
bar-indicator1.css 5KB
bar-indicator.css 5KB
coming-soon.css 5KB
coming-soon1.css 5KB
login2.css 5KB
timeline1.css 5KB
timeline.css 5KB
pricing3.css 5KB
pricing1.css 5KB
共 837 条
- 1
- 2
- 3
- 4
- 5
- 6
- 9
资源评论
程序员柳
- 粉丝: 6335
- 资源: 1373
下载权益
C知道特权
VIP文章
课程特权
开通VIP
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功