项目初次搭建
This commit is contained in:
19
app/api/common/upload_file.py
Normal file
19
app/api/common/upload_file.py
Normal file
@ -0,0 +1,19 @@
|
||||
from typing import List
|
||||
|
||||
from fastapi import APIRouter
|
||||
from fastapi import UploadFile
|
||||
import os
|
||||
|
||||
upload = APIRouter()
|
||||
|
||||
|
||||
@upload.post("/")
|
||||
def upload_file(files: List[UploadFile]):
|
||||
paths = []
|
||||
for file in files:
|
||||
path = os.path.join("images", file.filename)
|
||||
with open(path, "wb") as f:
|
||||
for line in file.file:
|
||||
f.write(line)
|
||||
paths.append(path)
|
||||
return paths
|
34
app/api/sys/login_api.py
Normal file
34
app/api/sys/login_api.py
Normal file
@ -0,0 +1,34 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from app.db.db_session import get_db
|
||||
from app.model.schemas.sys_user_schemas import SysUserLogin
|
||||
from app.common import reponse_code as rc
|
||||
from app.model.crud import sys_user_crud as us
|
||||
from app.common.bcrypt_pw import verify_password
|
||||
from app.common.jwt_check import generate_token
|
||||
from app.common.redis_cli import redis_conn
|
||||
"""
|
||||
用户登录统一接口
|
||||
"""
|
||||
|
||||
login = APIRouter()
|
||||
|
||||
|
||||
@login.post("/")
|
||||
def login_check(user: SysUserLogin, session: Session = Depends(get_db)):
|
||||
"""
|
||||
登录验证,并返回token
|
||||
:param session:
|
||||
:param user: 登录参数信息
|
||||
:return: response
|
||||
"""
|
||||
query_user = us.get_user_by_username(username=user.username, session=session)
|
||||
if query_user is None:
|
||||
return rc.response_error('您输入的用户名不正确')
|
||||
if not verify_password(user.password, query_user.password):
|
||||
return rc.response_error("您输入的密码不正确")
|
||||
if not query_user.user_status == '0':
|
||||
return rc.response_error(msg="登录失败,账号已被禁用,请联系管理员")
|
||||
token = generate_token(query_user.id, query_user.username)
|
||||
redis_conn.set(query_user.id, token)
|
||||
return rc.response_success(msg="登录成功", data=token)
|
84
app/api/sys/sys_user_api.py
Normal file
84
app/api/sys/sys_user_api.py
Normal file
@ -0,0 +1,84 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from app.model.schemas.sys_user_schemas import SysUserOut, SysUserIN, SysUserPager
|
||||
from app.common import reponse_code as rc
|
||||
from app.model.crud import sys_user_crud as us
|
||||
from app.model.model import SysUser
|
||||
from app.common.redis_cli import redis_conn
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from app.db.db_session import get_db
|
||||
"""
|
||||
用户管理模块
|
||||
"""
|
||||
user = APIRouter()
|
||||
|
||||
|
||||
@user.post("/pager")
|
||||
def user_pager(user: SysUserPager, session: Session = Depends(get_db)):
|
||||
pager = us.user_pager(user, session)
|
||||
return rc.response_success_pager(pager)
|
||||
|
||||
|
||||
@user.post("/")
|
||||
def add_user(user: SysUserIN, session: Session = Depends(get_db)):
|
||||
"""
|
||||
新增用户
|
||||
:param session:
|
||||
:param user: 用户信息
|
||||
:return:
|
||||
"""
|
||||
if us.check_username(user.username, session):
|
||||
return rc.response_error(msg="该用户名已存在!")
|
||||
else:
|
||||
user_in= SysUser(**user.dict())
|
||||
user_in.user_status = '0'
|
||||
if us.add_user(user_in, session):
|
||||
return rc.response_success(msg="保存成功")
|
||||
else:
|
||||
return rc.response_error(msg="保存失败")
|
||||
|
||||
|
||||
@user.get("/{id}")
|
||||
def get_user(id: int, session: Session = Depends(get_db)):
|
||||
"""
|
||||
根据用户id获取用户信息
|
||||
:param session:
|
||||
:param id: 用户id
|
||||
:return: 用户信息
|
||||
"""
|
||||
user = us.get_user_by_id(id, session)
|
||||
if user is None:
|
||||
return rc.response_success(data=None)
|
||||
user_out = SysUserOut(**dict(user))
|
||||
return rc.response_success(data=user_out.dict())
|
||||
|
||||
|
||||
@user.post("/stop/{id}")
|
||||
def stop_user(id: int, session: Session = Depends(get_db)):
|
||||
"""
|
||||
停用用户。修改用户状态,并删除保存过的登录redis
|
||||
:param session:
|
||||
:param id:
|
||||
:return:
|
||||
"""
|
||||
user = us.get_user_by_id(id, session)
|
||||
if user is None:
|
||||
return rc.response_error("用户查询错误,请稍后再试")
|
||||
us.stop_user(user)
|
||||
redis_conn.delete(id)
|
||||
return rc.response_success("停用用户成功")
|
||||
|
||||
|
||||
@user.post("/start/{id}")
|
||||
def start_user(id: int, session: Session = Depends(get_db)):
|
||||
"""
|
||||
启用用户。修改用户状态
|
||||
:param session:
|
||||
:param id:
|
||||
:return:
|
||||
"""
|
||||
user = us.get_user_by_id(id, session)
|
||||
if user is None:
|
||||
return rc.response_error("用户查询错误,请稍后再试")
|
||||
us.start_user(user)
|
||||
return rc.response_success("启用用户成功")
|
23
app/application/app.py
Normal file
23
app/application/app.py
Normal file
@ -0,0 +1,23 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.application.token_middleware import TokenMiddleware
|
||||
from app.application.logger_middleware import LoggerMiddleware
|
||||
|
||||
my_app = FastAPI()
|
||||
|
||||
|
||||
'''
|
||||
添加CROS中间件,允许跨域请求
|
||||
'''
|
||||
my_app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
#注意中间的顺序,这个地方是倒序执行的
|
||||
my_app.add_middleware(LoggerMiddleware)
|
||||
my_app.add_middleware(TokenMiddleware)
|
23
app/application/logger_middleware.py
Normal file
23
app/application/logger_middleware.py
Normal file
@ -0,0 +1,23 @@
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from urllib.request import Request
|
||||
|
||||
from app.common.jwt_check import check_token
|
||||
|
||||
from app.common.logger_config import logger_http
|
||||
|
||||
|
||||
class LoggerMiddleware(BaseHTTPMiddleware):
|
||||
def __init__(self, app):
|
||||
super().__init__(app)
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
method = request.method
|
||||
path = request.url.path
|
||||
token = request.headers.get("Authorization")
|
||||
user_id = None
|
||||
if token:
|
||||
decoded_payload = check_token(token)
|
||||
user_id = decoded_payload['user_id']
|
||||
logger_http.info(f"Path: {path},UserId: {user_id}, Method: {method}")
|
||||
response = await call_next(request)
|
||||
return response
|
33
app/application/token_middleware.py
Normal file
33
app/application/token_middleware.py
Normal file
@ -0,0 +1,33 @@
|
||||
from fastapi import status
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from urllib.request import Request
|
||||
from jwt import PyJWTError
|
||||
from common import reponse_code as rc
|
||||
from common import jwt_check as jc
|
||||
|
||||
|
||||
|
||||
class TokenMiddleware(BaseHTTPMiddleware):
|
||||
|
||||
def __init__(self, app):
|
||||
super().__init__(app)
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
"""
|
||||
验证token中间件
|
||||
:param request: Request请求
|
||||
:param call_next:
|
||||
:return:
|
||||
"""
|
||||
token = request.headers.get('Authorization')
|
||||
path = request.url.path
|
||||
if '/login' in path:
|
||||
response = await call_next(request)
|
||||
return response
|
||||
if not token:
|
||||
return rc.response_code_view(status.HTTP_401_UNAUTHORIZED, "缺少Token,请重新验证")
|
||||
try:
|
||||
jc.check_token(token)
|
||||
return await call_next(request)
|
||||
except PyJWTError as error:
|
||||
return rc.response_code_view(status.HTTP_401_UNAUTHORIZED, "Token错误或失效,请重新验证")
|
13
app/common/bcrypt_pw.py
Normal file
13
app/common/bcrypt_pw.py
Normal file
@ -0,0 +1,13 @@
|
||||
import bcrypt
|
||||
|
||||
#使用bcrypt对密码进行加密
|
||||
def hash_password(password):
|
||||
# 生成盐值并使用 bcrypt 加密密码
|
||||
salt = bcrypt.gensalt()
|
||||
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
|
||||
return hashed
|
||||
|
||||
|
||||
def verify_password(provided_password, stored_password):
|
||||
# 验证提供的密码是否与存储的哈希值匹配
|
||||
return bcrypt.checkpw(provided_password.encode('utf-8'), stored_password.encode('utf-8'))
|
50
app/common/jwt_check.py
Normal file
50
app/common/jwt_check.py
Normal file
@ -0,0 +1,50 @@
|
||||
import datetime
|
||||
|
||||
import jwt
|
||||
from app.common.redis_cli import redis_conn
|
||||
|
||||
# 过期时间,单位S
|
||||
exp = 6000
|
||||
|
||||
# 加密秘钥
|
||||
secret_key = 'syg15684712291'
|
||||
|
||||
|
||||
def generate_token(user_id: int, username: str):
|
||||
"""
|
||||
根据用户id和用户名生成一个token
|
||||
:param user_id: 用户id
|
||||
:param username: 用户名
|
||||
:return: token
|
||||
"""
|
||||
payload = {
|
||||
'user_id': user_id,
|
||||
'username': username,
|
||||
'exp': datetime.datetime.utcnow() + datetime.timedelta(exp)
|
||||
}
|
||||
|
||||
# 生成token
|
||||
token = jwt.encode(payload, secret_key, algorithm='HS256')
|
||||
|
||||
return token
|
||||
|
||||
|
||||
def check_token(token: str):
|
||||
"""
|
||||
验证token
|
||||
:param token: token
|
||||
:return: True or False
|
||||
"""
|
||||
try:
|
||||
decoded_payload = jwt.decode(token, secret_key, algorithms=['HS256'])
|
||||
user_id = decoded_payload['user_id']
|
||||
token_redis = redis_conn.get(user_id)
|
||||
if token_redis is None:
|
||||
raise jwt.ExpiredSignatureError("Expired Token")
|
||||
if token_redis != token:
|
||||
raise jwt.ExpiredSignatureError("Invalid Token")
|
||||
return decoded_payload
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise jwt.ExpiredSignatureError("Expired Token")
|
||||
except jwt.InvalidTokenError:
|
||||
raise jwt.InvalidTokenError("Invalid Token")
|
33
app/common/logger_config.py
Normal file
33
app/common/logger_config.py
Normal file
@ -0,0 +1,33 @@
|
||||
import logging
|
||||
import os
|
||||
from logging.handlers import TimedRotatingFileHandler
|
||||
|
||||
from app.config.config_reader import log_dir
|
||||
|
||||
|
||||
file_suffix = "%Y-%m-%d"
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
|
||||
#所有http请求的日志
|
||||
logger_http = logging.getLogger("api_log")
|
||||
logger_http.setLevel(logging.DEBUG)
|
||||
# 创建一个TimedRotatingFileHandler,指定日志文件名、轮转周期和备份数量
|
||||
api_log_file = os.path.join(log_dir, 'api.log')
|
||||
api_handler = TimedRotatingFileHandler(api_log_file, when="midnight", interval=1, backupCount=30)
|
||||
api_handler.setFormatter(formatter)
|
||||
api_handler.suffix = file_suffix # 日志文件的后缀为日期格式
|
||||
logger_http.addHandler(api_handler)
|
||||
|
||||
#所有sqlalchemy打印的日志
|
||||
logger_sql = logging.getLogger("sqlalchemy.engine.Engine")
|
||||
logger_sql.setLevel(logging.DEBUG)
|
||||
# 创建文件处理器并设置级别
|
||||
sql_log_file = os.path.join(log_dir, 'sql.log')
|
||||
sql_handler = TimedRotatingFileHandler(sql_log_file, when="midnight", interval=1, backupCount=30)
|
||||
sql_handler.setFormatter(formatter)
|
||||
sql_handler.suffix = file_suffix # 日志文件的后缀为日期格式
|
||||
logger_sql.addHandler(sql_handler)
|
||||
|
||||
|
4
app/common/redis_cli.py
Normal file
4
app/common/redis_cli.py
Normal file
@ -0,0 +1,4 @@
|
||||
import redis
|
||||
from app.config.config_reader import redis_db, redis_password, redis_port, redis_host
|
||||
|
||||
redis_conn = redis.Redis(host=redis_host, port=redis_port, db=redis_db, password=redis_password, decode_responses=True)
|
46
app/common/reponse_code.py
Normal file
46
app/common/reponse_code.py
Normal file
@ -0,0 +1,46 @@
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from fastapi import status
|
||||
from app.db.page_util import Pager
|
||||
|
||||
|
||||
def response_code_view(code: int,msg: str) -> Response:
|
||||
return JSONResponse(
|
||||
status_code=code,
|
||||
content={
|
||||
'code': code,
|
||||
'msg': msg
|
||||
}
|
||||
)
|
||||
|
||||
def response_success(msg: str = "查询成功", data: object = None):
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_200_OK,
|
||||
content={
|
||||
'code': 200,
|
||||
'msg': msg,
|
||||
'data': data,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def response_success_pager(pager: Pager):
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_200_OK,
|
||||
content={
|
||||
'code': 200,
|
||||
'msg': "查询成功",
|
||||
'data': pager.data,
|
||||
'total': pager.total
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def response_error(msg:str):
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_200_OK,
|
||||
content={
|
||||
'code': 500,
|
||||
'msg': msg,
|
||||
'data': None,
|
||||
}
|
||||
)
|
11
app/config/application_config_dev.ini
Normal file
11
app/config/application_config_dev.ini
Normal file
@ -0,0 +1,11 @@
|
||||
[mysql]
|
||||
database_url = mysql+pymysql://root:root@localhost:3306/aicheckv2
|
||||
|
||||
[redis]
|
||||
host = localhost
|
||||
port = 6379
|
||||
db = 0
|
||||
password = sdust2020
|
||||
|
||||
[log]
|
||||
dir = D:\syg\workspace\logs
|
11
app/config/application_config_pro.ini
Normal file
11
app/config/application_config_pro.ini
Normal file
@ -0,0 +1,11 @@
|
||||
[mysql]
|
||||
database_url = mysql+pymysql://root:root@localhost:3306/sun
|
||||
|
||||
[redis]
|
||||
host = localhost
|
||||
port = 6379
|
||||
db = 0
|
||||
password = 123456
|
||||
|
||||
[log]
|
||||
dir = /Users/macbookpro/sunyg/workspace/logs
|
21
app/config/config_reader.py
Normal file
21
app/config/config_reader.py
Normal file
@ -0,0 +1,21 @@
|
||||
import configparser
|
||||
import os
|
||||
|
||||
env = "dev"
|
||||
|
||||
|
||||
script_directory = os.path.dirname(os.path.abspath(__file__))
|
||||
config_path = os.path.join(script_directory, f'application_config_{env}.ini')
|
||||
|
||||
config = configparser.ConfigParser()
|
||||
config.read(config_path)
|
||||
|
||||
|
||||
database_url = config['mysql']['database_url']
|
||||
|
||||
redis_host = config.get('redis', 'host')
|
||||
redis_port = config.get('redis', 'port')
|
||||
redis_db = config.get('redis', 'db')
|
||||
redis_password = config.get('redis', 'password')
|
||||
|
||||
log_dir = config.get('log', 'dir')
|
20
app/db/db_base.py
Normal file
20
app/db/db_base.py
Normal file
@ -0,0 +1,20 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base, declared_attr
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
import datetime
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class DbCommon(Base):
|
||||
__abstract__ = True
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
create_time: Mapped[datetime.datetime] = mapped_column(default=datetime.datetime.utcnow())
|
||||
update_time: Mapped[datetime.datetime] = mapped_column(default=datetime.datetime.utcnow(), onupdate=datetime.datetime.utcnow())
|
||||
|
||||
def keys(self):
|
||||
return ["id", "create_time", "update_time"]
|
||||
|
||||
|
||||
@declared_attr
|
||||
def __tablename__(cls):
|
||||
return cls.__name__.lower()
|
9
app/db/db_engine.py
Normal file
9
app/db/db_engine.py
Normal file
@ -0,0 +1,9 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, scoped_session
|
||||
from app.config.config_reader import database_url
|
||||
|
||||
|
||||
db_engine = create_engine(database_url, echo=True, echo_pool=True)
|
||||
|
||||
db_session = sessionmaker(bind=db_engine, autoflush=False, autocommit=False, expire_on_commit=True)
|
||||
session = scoped_session(db_session)
|
9
app/db/db_session.py
Normal file
9
app/db/db_session.py
Normal file
@ -0,0 +1,9 @@
|
||||
from app.db.db_engine import db_session
|
||||
|
||||
|
||||
def get_db():
|
||||
session = db_session()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
26
app/db/page_util.py
Normal file
26
app/db/page_util.py
Normal file
@ -0,0 +1,26 @@
|
||||
from sqlalchemy.orm.query import Query
|
||||
|
||||
|
||||
def get_pager(query: Query, pagerNum: int, pagerSize: int, ):
|
||||
total = query.count()
|
||||
data = query.limit(pagerSize).offset((pagerNum - 1) * pagerSize).all()
|
||||
pager = Pager(total, data)
|
||||
return pager
|
||||
|
||||
|
||||
class Pager:
|
||||
def __init__(self, total: int, data: object):
|
||||
self.total = total
|
||||
self.data = data
|
||||
|
||||
def keys(self):
|
||||
keys = ["total", "data"]
|
||||
return keys
|
||||
|
||||
def __getitem__(self, item):
|
||||
'''
|
||||
内置方法, 当使用obj['name']的形式的时候, 将调用这个方法, 这里返回的结果就是值
|
||||
:param item:
|
||||
:return:
|
||||
'''
|
||||
return getattr(self, item, None)
|
5
app/main.py
Normal file
5
app/main.py
Normal file
@ -0,0 +1,5 @@
|
||||
import uvicorn
|
||||
from app.application.app import my_app
|
||||
|
||||
if __name__ == '__main__':
|
||||
uvicorn.run("main:my_app", port=8080, reload=True)
|
67
app/model/crud/sys_user_crud.py
Normal file
67
app/model/crud/sys_user_crud.py
Normal file
@ -0,0 +1,67 @@
|
||||
from app.model.model import SysUser
|
||||
from app.model.schemas.sys_user_schemas import SysUserPager, SysUserOut
|
||||
from app.common.bcrypt_pw import hash_password
|
||||
from app.db.page_util import get_pager
|
||||
|
||||
from sqlalchemy import and_, desc
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
def user_pager(user: SysUserPager, session: Session):
|
||||
query = session.query(SysUser).order_by(desc(SysUser.id))
|
||||
filters = []
|
||||
if user.username is not None:
|
||||
filters.append(SysUser.username.ilike(f"%{user.username}%"))
|
||||
if user.dept_id is not None:
|
||||
filters.append(SysUser.dept_id == user.dept_id)
|
||||
if len(filters) > 0:
|
||||
query.filter(and_(*filters))
|
||||
pager = get_pager(query, user.pagerNum, user.pagerSize)
|
||||
pager.data = [SysUserOut.from_orm(user) for user in pager.data]
|
||||
return pager
|
||||
|
||||
|
||||
def add_user(user: SysUser, session: Session):
|
||||
user.password = hash_password(user.password)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def get_user_by_id(id: int, session: Session):
|
||||
user = session.query(SysUser).filter(SysUser.id == id).first()
|
||||
return user
|
||||
|
||||
|
||||
def stop_user(user: SysUser, session: Session):
|
||||
user.user_status = "1"
|
||||
session.commit();
|
||||
return user
|
||||
|
||||
|
||||
def start_user(user: SysUser, session: Session):
|
||||
user.user_status = "0"
|
||||
session.commit();
|
||||
return user
|
||||
|
||||
|
||||
def get_user_by_username(username: str, session: Session):
|
||||
user = session.query(SysUser).filter(SysUser.username == username).first()
|
||||
return user
|
||||
|
||||
|
||||
# 验证username的唯一性
|
||||
def check_username(username: str, session: Session):
|
||||
count = session.query(SysUser).filter(SysUser.username == username).count()
|
||||
if count > 0:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
# 修改密码
|
||||
def update_pw(user: SysUser, session: Session):
|
||||
session.query(SysUser).filter_by(id=user.id).update({
|
||||
"password": user.password
|
||||
})
|
||||
session.commit()
|
29
app/model/model.py
Normal file
29
app/model/model.py
Normal file
@ -0,0 +1,29 @@
|
||||
from app.db.db_base import DbCommon
|
||||
from sqlalchemy import String,Integer
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
|
||||
class SysUser(DbCommon):
|
||||
|
||||
__tablename__ = "sys_user"
|
||||
username: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
|
||||
password: Mapped[str] = mapped_column(String(255))
|
||||
dept_id: Mapped[int] = mapped_column(Integer)
|
||||
login_name: Mapped[str] = mapped_column(String(255))
|
||||
avatar: Mapped[str] = mapped_column(String(255))
|
||||
user_status: Mapped[str] = mapped_column(String(10))
|
||||
|
||||
|
||||
def keys(self):
|
||||
keys = ["username", "password", "dept_id", "login_name", "avatar", "user_status"]
|
||||
keys.extend(super().keys())
|
||||
return keys
|
||||
|
||||
|
||||
def __getitem__(self, item):
|
||||
'''
|
||||
内置方法, 当使用obj['name']的形式的时候, 将调用这个方法, 这里返回的结果就是值
|
||||
:param item:
|
||||
:return:
|
||||
'''
|
||||
return getattr(self, item, None)
|
43
app/model/schemas/sys_user_schemas.py
Normal file
43
app/model/schemas/sys_user_schemas.py
Normal file
@ -0,0 +1,43 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
|
||||
|
||||
# 用户相关的原型
|
||||
class SysUserIN(BaseModel):
|
||||
username: Optional[str] = Field(..., description="用户名", max_length=50)
|
||||
password: Optional[str] = Field(..., description="密码", max_length=30, min_length=6)
|
||||
dept_id: Optional[str] = Field(None, description="部门id")
|
||||
login_name: Optional[str] = Field(None, description="昵称", max_length=20)
|
||||
|
||||
|
||||
class SysUserLogin(BaseModel):
|
||||
username: Optional[str] = Field(..., description="用户名", max_length=50)
|
||||
password: Optional[str] = Field(..., description="密码", max_length=30, min_length=6)
|
||||
|
||||
|
||||
class SysUserOut(BaseModel):
|
||||
id: Optional[int] = Field(..., description="id")
|
||||
username: Optional[str] = Field(..., description="用户名")
|
||||
dept_id: Optional[str] = Field(None, description="部门id")
|
||||
dept_name: Optional[str] = Field(None, description="部门名称")
|
||||
login_name: Optional[str] = Field(None, description="昵称")
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
|
||||
|
||||
class SysUserUpdatePw(BaseModel):
|
||||
id: Optional[int] = Field(..., description="id")
|
||||
new_password: Optional[str] = Field(..., description="新密码", max_length=30, min_length=8)
|
||||
original_password: Optional[str] = Field(..., description="旧密码", max_length=30, min_length=8)
|
||||
|
||||
|
||||
class SysUserPager(BaseModel):
|
||||
username: Optional[str] = Field(None, description="用户名")
|
||||
dept_id: Optional[str] = Field(None, description="部门id")
|
||||
login_name: Optional[str] = Field(None, description="昵称")
|
||||
pagerNum: Optional[int] = Field(1, description="当前页码")
|
||||
pagerSize: Optional[int] = Field(10, description="每页数量")
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
39
requirements.txt
Normal file
39
requirements.txt
Normal file
@ -0,0 +1,39 @@
|
||||
# aicheck_base requirements
|
||||
# Usage: pip install -r requirements.txt
|
||||
|
||||
# API -------------------------------------------------------------------------
|
||||
fastapi~=0.74.1 # fastapi基础包
|
||||
pydantic~=1.9.0 # pydantic
|
||||
email-validator==1.1.3
|
||||
PyJWT~=2.3.0
|
||||
python-multipart==0.0.5
|
||||
redis~=4.1.4
|
||||
SQLAlchemy~=2.0.34
|
||||
uvicorn~=0.17.5
|
||||
loguru~=0.6.0
|
||||
xlrd~=2.0.1
|
||||
bcrypt==3.2.0
|
||||
pymysql==1.0.2
|
||||
pynvml==12.0.0
|
||||
requests-toolbelt==1.0.0
|
||||
|
||||
# YOLOV5 ----------------------------------------------------------------------
|
||||
# BASE ------------------------------------------------------------------------
|
||||
gitpython>=3.1.30
|
||||
matplotlib>=3.3
|
||||
numpy==2.0.2
|
||||
opencv-python>=4.1.1
|
||||
pillow>=10.3.0
|
||||
psutil # system resources
|
||||
PyYAML>=5.3.1
|
||||
requests>=2.32.2
|
||||
scipy==1.13.1
|
||||
thop>=0.1.1 # FLOPs computation
|
||||
torch>=1.8.0 # see https://pytorch.org/get-started/locally (recommended)
|
||||
torchvision>=0.9.0
|
||||
tqdm>=4.66.3
|
||||
ultralytics>=8.2.34 # https://ultralytics.com
|
||||
|
||||
# Plotting --------------------------------------------------------------------
|
||||
pandas==2.2.3
|
||||
seaborn>=0.11.0
|
0
yolov5/__init__.py
Normal file
0
yolov5/__init__.py
Normal file
294
yolov5/benchmarks.py
Normal file
294
yolov5/benchmarks.py
Normal file
@ -0,0 +1,294 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""
|
||||
Run YOLOv5 benchmarks on all supported export formats.
|
||||
|
||||
Format | `export.py --include` | Model
|
||||
--- | --- | ---
|
||||
PyTorch | - | yolov5s.pt
|
||||
TorchScript | `torchscript` | yolov5s.torchscript
|
||||
ONNX | `onnx` | yolov5s.onnx
|
||||
OpenVINO | `openvino` | yolov5s_openvino_model/
|
||||
TensorRT | `engine` | yolov5s.engine
|
||||
CoreML | `coreml` | yolov5s.mlpackage
|
||||
TensorFlow SavedModel | `saved_model` | yolov5s_saved_model/
|
||||
TensorFlow GraphDef | `pb` | yolov5s.pb
|
||||
TensorFlow Lite | `tflite` | yolov5s.tflite
|
||||
TensorFlow Edge TPU | `edgetpu` | yolov5s_edgetpu.tflite
|
||||
TensorFlow.js | `tfjs` | yolov5s_web_model/
|
||||
|
||||
Requirements:
|
||||
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU
|
||||
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU
|
||||
$ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
|
||||
|
||||
Usage:
|
||||
$ python benchmarks.py --weights yolov5s.pt --img 640
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import platform
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
FILE = Path(__file__).resolve()
|
||||
ROOT = FILE.parents[0] # YOLOv5 root directory
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.append(str(ROOT)) # add ROOT to PATH
|
||||
# ROOT = ROOT.relative_to(Path.cwd()) # relative
|
||||
|
||||
import export
|
||||
from models.experimental import attempt_load
|
||||
from models.yolo import SegmentationModel
|
||||
from segment.val import run as val_seg
|
||||
from utils import notebook_init
|
||||
from utils.general import LOGGER, check_yaml, file_size, print_args
|
||||
from utils.torch_utils import select_device
|
||||
from val import run as val_det
|
||||
|
||||
|
||||
def run(
|
||||
weights=ROOT / "yolov5s.pt", # weights path
|
||||
imgsz=640, # inference size (pixels)
|
||||
batch_size=1, # batch size
|
||||
data=ROOT / "data/coco128.yaml", # dataset.yaml path
|
||||
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
||||
half=False, # use FP16 half-precision inference
|
||||
test=False, # test exports only
|
||||
pt_only=False, # test PyTorch only
|
||||
hard_fail=False, # throw error on benchmark failure
|
||||
):
|
||||
"""
|
||||
Run YOLOv5 benchmarks on multiple export formats and log results for model performance evaluation.
|
||||
|
||||
Args:
|
||||
weights (Path | str): Path to the model weights file (default: ROOT / "yolov5s.pt").
|
||||
imgsz (int): Inference size in pixels (default: 640).
|
||||
batch_size (int): Batch size for inference (default: 1).
|
||||
data (Path | str): Path to the dataset.yaml file (default: ROOT / "data/coco128.yaml").
|
||||
device (str): CUDA device, e.g., '0' or '0,1,2,3' or 'cpu' (default: "").
|
||||
half (bool): Use FP16 half-precision inference (default: False).
|
||||
test (bool): Test export formats only (default: False).
|
||||
pt_only (bool): Test PyTorch format only (default: False).
|
||||
hard_fail (bool): Throw an error on benchmark failure if True (default: False).
|
||||
|
||||
Returns:
|
||||
None. Logs information about the benchmark results, including the format, size, mAP50-95, and inference time.
|
||||
|
||||
Notes:
|
||||
Supported export formats and models include PyTorch, TorchScript, ONNX, OpenVINO, TensorRT, CoreML,
|
||||
TensorFlow SavedModel, TensorFlow GraphDef, TensorFlow Lite, and TensorFlow Edge TPU. Edge TPU and TF.js
|
||||
are unsupported.
|
||||
|
||||
Example:
|
||||
```python
|
||||
$ python benchmarks.py --weights yolov5s.pt --img 640
|
||||
```
|
||||
|
||||
Usage:
|
||||
Install required packages:
|
||||
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU support
|
||||
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU support
|
||||
$ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
|
||||
|
||||
Run benchmarks:
|
||||
$ python benchmarks.py --weights yolov5s.pt --img 640
|
||||
"""
|
||||
y, t = [], time.time()
|
||||
device = select_device(device)
|
||||
model_type = type(attempt_load(weights, fuse=False)) # DetectionModel, SegmentationModel, etc.
|
||||
for i, (name, f, suffix, cpu, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, CPU, GPU)
|
||||
try:
|
||||
assert i not in (9, 10), "inference not supported" # Edge TPU and TF.js are unsupported
|
||||
assert i != 5 or platform.system() == "Darwin", "inference only supported on macOS>=10.13" # CoreML
|
||||
if "cpu" in device.type:
|
||||
assert cpu, "inference not supported on CPU"
|
||||
if "cuda" in device.type:
|
||||
assert gpu, "inference not supported on GPU"
|
||||
|
||||
# Export
|
||||
if f == "-":
|
||||
w = weights # PyTorch format
|
||||
else:
|
||||
w = export.run(
|
||||
weights=weights, imgsz=[imgsz], include=[f], batch_size=batch_size, device=device, half=half
|
||||
)[-1] # all others
|
||||
assert suffix in str(w), "export failed"
|
||||
|
||||
# Validate
|
||||
if model_type == SegmentationModel:
|
||||
result = val_seg(data, w, batch_size, imgsz, plots=False, device=device, task="speed", half=half)
|
||||
metric = result[0][7] # (box(p, r, map50, map), mask(p, r, map50, map), *loss(box, obj, cls))
|
||||
else: # DetectionModel:
|
||||
result = val_det(data, w, batch_size, imgsz, plots=False, device=device, task="speed", half=half)
|
||||
metric = result[0][3] # (p, r, map50, map, *loss(box, obj, cls))
|
||||
speed = result[2][1] # times (preprocess, inference, postprocess)
|
||||
y.append([name, round(file_size(w), 1), round(metric, 4), round(speed, 2)]) # MB, mAP, t_inference
|
||||
except Exception as e:
|
||||
if hard_fail:
|
||||
assert type(e) is AssertionError, f"Benchmark --hard-fail for {name}: {e}"
|
||||
LOGGER.warning(f"WARNING ⚠️ Benchmark failure for {name}: {e}")
|
||||
y.append([name, None, None, None]) # mAP, t_inference
|
||||
if pt_only and i == 0:
|
||||
break # break after PyTorch
|
||||
|
||||
# Print results
|
||||
LOGGER.info("\n")
|
||||
parse_opt()
|
||||
notebook_init() # print system info
|
||||
c = ["Format", "Size (MB)", "mAP50-95", "Inference time (ms)"] if map else ["Format", "Export", "", ""]
|
||||
py = pd.DataFrame(y, columns=c)
|
||||
LOGGER.info(f"\nBenchmarks complete ({time.time() - t:.2f}s)")
|
||||
LOGGER.info(str(py if map else py.iloc[:, :2]))
|
||||
if hard_fail and isinstance(hard_fail, str):
|
||||
metrics = py["mAP50-95"].array # values to compare to floor
|
||||
floor = eval(hard_fail) # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n
|
||||
assert all(x > floor for x in metrics if pd.notna(x)), f"HARD FAIL: mAP50-95 < floor {floor}"
|
||||
return py
|
||||
|
||||
|
||||
def test(
|
||||
weights=ROOT / "yolov5s.pt", # weights path
|
||||
imgsz=640, # inference size (pixels)
|
||||
batch_size=1, # batch size
|
||||
data=ROOT / "data/coco128.yaml", # dataset.yaml path
|
||||
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
||||
half=False, # use FP16 half-precision inference
|
||||
test=False, # test exports only
|
||||
pt_only=False, # test PyTorch only
|
||||
hard_fail=False, # throw error on benchmark failure
|
||||
):
|
||||
"""
|
||||
Run YOLOv5 export tests for all supported formats and log the results, including export statuses.
|
||||
|
||||
Args:
|
||||
weights (Path | str): Path to the model weights file (.pt format). Default is 'ROOT / "yolov5s.pt"'.
|
||||
imgsz (int): Inference image size (in pixels). Default is 640.
|
||||
batch_size (int): Batch size for testing. Default is 1.
|
||||
data (Path | str): Path to the dataset configuration file (.yaml format). Default is 'ROOT / "data/coco128.yaml"'.
|
||||
device (str): Device for running the tests, can be 'cpu' or a specific CUDA device ('0', '0,1,2,3', etc.). Default is an empty string.
|
||||
half (bool): Use FP16 half-precision for inference if True. Default is False.
|
||||
test (bool): Test export formats only without running inference. Default is False.
|
||||
pt_only (bool): Test only the PyTorch model if True. Default is False.
|
||||
hard_fail (bool): Raise error on export or test failure if True. Default is False.
|
||||
|
||||
Returns:
|
||||
pd.DataFrame: DataFrame containing the results of the export tests, including format names and export statuses.
|
||||
|
||||
Examples:
|
||||
```python
|
||||
$ python benchmarks.py --weights yolov5s.pt --img 640
|
||||
```
|
||||
|
||||
Notes:
|
||||
Supported export formats and models include PyTorch, TorchScript, ONNX, OpenVINO, TensorRT, CoreML, TensorFlow
|
||||
SavedModel, TensorFlow GraphDef, TensorFlow Lite, and TensorFlow Edge TPU. Edge TPU and TF.js are unsupported.
|
||||
|
||||
Usage:
|
||||
Install required packages:
|
||||
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime openvino-dev tensorflow-cpu # CPU support
|
||||
$ pip install -r requirements.txt coremltools onnx onnx-simplifier onnxruntime-gpu openvino-dev tensorflow # GPU support
|
||||
$ pip install -U nvidia-tensorrt --index-url https://pypi.ngc.nvidia.com # TensorRT
|
||||
Run export tests:
|
||||
$ python benchmarks.py --weights yolov5s.pt --img 640
|
||||
"""
|
||||
y, t = [], time.time()
|
||||
device = select_device(device)
|
||||
for i, (name, f, suffix, gpu) in export.export_formats().iterrows(): # index, (name, file, suffix, gpu-capable)
|
||||
try:
|
||||
w = (
|
||||
weights
|
||||
if f == "-"
|
||||
else export.run(weights=weights, imgsz=[imgsz], include=[f], device=device, half=half)[-1]
|
||||
) # weights
|
||||
assert suffix in str(w), "export failed"
|
||||
y.append([name, True])
|
||||
except Exception:
|
||||
y.append([name, False]) # mAP, t_inference
|
||||
|
||||
# Print results
|
||||
LOGGER.info("\n")
|
||||
parse_opt()
|
||||
notebook_init() # print system info
|
||||
py = pd.DataFrame(y, columns=["Format", "Export"])
|
||||
LOGGER.info(f"\nExports complete ({time.time() - t:.2f}s)")
|
||||
LOGGER.info(str(py))
|
||||
return py
|
||||
|
||||
|
||||
def parse_opt():
|
||||
"""
|
||||
Parses command-line arguments for YOLOv5 model inference configuration.
|
||||
|
||||
Args:
|
||||
weights (str): The path to the weights file. Defaults to 'ROOT / "yolov5s.pt"'.
|
||||
imgsz (int): Inference size in pixels. Defaults to 640.
|
||||
batch_size (int): Batch size. Defaults to 1.
|
||||
data (str): Path to the dataset YAML file. Defaults to 'ROOT / "data/coco128.yaml"'.
|
||||
device (str): CUDA device, e.g., '0' or '0,1,2,3' or 'cpu'. Defaults to an empty string (auto-select).
|
||||
half (bool): Use FP16 half-precision inference. This is a flag and defaults to False.
|
||||
test (bool): Test exports only. This is a flag and defaults to False.
|
||||
pt_only (bool): Test PyTorch only. This is a flag and defaults to False.
|
||||
hard_fail (bool | str): Throw an error on benchmark failure. Can be a boolean or a string representing a minimum
|
||||
metric floor, e.g., '0.29'. Defaults to False.
|
||||
|
||||
Returns:
|
||||
argparse.Namespace: Parsed command-line arguments encapsulated in an argparse Namespace object.
|
||||
|
||||
Notes:
|
||||
The function modifies the 'opt.data' by checking and validating the YAML path using 'check_yaml()'.
|
||||
The parsed arguments are printed for reference using 'print_args()'.
|
||||
"""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt", help="weights path")
|
||||
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=640, help="inference size (pixels)")
|
||||
parser.add_argument("--batch-size", type=int, default=1, help="batch size")
|
||||
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="dataset.yaml path")
|
||||
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
||||
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
|
||||
parser.add_argument("--test", action="store_true", help="test exports only")
|
||||
parser.add_argument("--pt-only", action="store_true", help="test PyTorch only")
|
||||
parser.add_argument("--hard-fail", nargs="?", const=True, default=False, help="Exception on error or < min metric")
|
||||
opt = parser.parse_args()
|
||||
opt.data = check_yaml(opt.data) # check YAML
|
||||
print_args(vars(opt))
|
||||
return opt
|
||||
|
||||
|
||||
def main(opt):
|
||||
"""
|
||||
Executes YOLOv5 benchmark tests or main training/inference routines based on the provided command-line arguments.
|
||||
|
||||
Args:
|
||||
opt (argparse.Namespace): Parsed command-line arguments including options for weights, image size, batch size, data
|
||||
configuration, device, and other flags for inference settings.
|
||||
|
||||
Returns:
|
||||
None: This function does not return any value. It leverages side-effects such as logging and running benchmarks.
|
||||
|
||||
Example:
|
||||
```python
|
||||
if __name__ == "__main__":
|
||||
opt = parse_opt()
|
||||
main(opt)
|
||||
```
|
||||
|
||||
Notes:
|
||||
- For a complete list of supported export formats and their respective requirements, refer to the
|
||||
[Ultralytics YOLOv5 Export Formats](https://github.com/ultralytics/yolov5#export-formats).
|
||||
- Ensure that you have installed all necessary dependencies by following the installation instructions detailed in
|
||||
the [main repository](https://github.com/ultralytics/yolov5#installation).
|
||||
|
||||
```shell
|
||||
# Running benchmarks on default weights and image size
|
||||
$ python benchmarks.py --weights yolov5s.pt --img 640
|
||||
```
|
||||
"""
|
||||
test(**vars(opt)) if opt.test else run(**vars(opt))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
opt = parse_opt()
|
||||
main(opt)
|
35
yolov5/data/hyps/hyp.Objects365.yaml
Normal file
35
yolov5/data/hyps/hyp.Objects365.yaml
Normal file
@ -0,0 +1,35 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Hyperparameters for Objects365 training
|
||||
# python train.py --weights yolov5m.pt --data Objects365.yaml --evolve
|
||||
# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials
|
||||
|
||||
lr0: 0.00258
|
||||
lrf: 0.17
|
||||
momentum: 0.779
|
||||
weight_decay: 0.00058
|
||||
warmup_epochs: 1.33
|
||||
warmup_momentum: 0.86
|
||||
warmup_bias_lr: 0.0711
|
||||
box: 0.0539
|
||||
cls: 0.299
|
||||
cls_pw: 0.825
|
||||
obj: 0.632
|
||||
obj_pw: 1.0
|
||||
iou_t: 0.2
|
||||
anchor_t: 3.44
|
||||
anchors: 3.2
|
||||
fl_gamma: 0.0
|
||||
hsv_h: 0.0188
|
||||
hsv_s: 0.704
|
||||
hsv_v: 0.36
|
||||
degrees: 0.0
|
||||
translate: 0.0902
|
||||
scale: 0.491
|
||||
shear: 0.0
|
||||
perspective: 0.0
|
||||
flipud: 0.0
|
||||
fliplr: 0.5
|
||||
mosaic: 1.0
|
||||
mixup: 0.0
|
||||
copy_paste: 0.0
|
41
yolov5/data/hyps/hyp.VOC.yaml
Normal file
41
yolov5/data/hyps/hyp.VOC.yaml
Normal file
@ -0,0 +1,41 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Hyperparameters for VOC training
|
||||
# python train.py --batch 128 --weights yolov5m6.pt --data VOC.yaml --epochs 50 --img 512 --hyp hyp.scratch-med.yaml --evolve
|
||||
# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials
|
||||
|
||||
# YOLOv5 Hyperparameter Evolution Results
|
||||
# Best generation: 467
|
||||
# Last generation: 996
|
||||
# metrics/precision, metrics/recall, metrics/mAP_0.5, metrics/mAP_0.5:0.95, val/box_loss, val/obj_loss, val/cls_loss
|
||||
# 0.87729, 0.85125, 0.91286, 0.72664, 0.0076739, 0.0042529, 0.0013865
|
||||
|
||||
lr0: 0.00334
|
||||
lrf: 0.15135
|
||||
momentum: 0.74832
|
||||
weight_decay: 0.00025
|
||||
warmup_epochs: 3.3835
|
||||
warmup_momentum: 0.59462
|
||||
warmup_bias_lr: 0.18657
|
||||
box: 0.02
|
||||
cls: 0.21638
|
||||
cls_pw: 0.5
|
||||
obj: 0.51728
|
||||
obj_pw: 0.67198
|
||||
iou_t: 0.2
|
||||
anchor_t: 3.3744
|
||||
fl_gamma: 0.0
|
||||
hsv_h: 0.01041
|
||||
hsv_s: 0.54703
|
||||
hsv_v: 0.27739
|
||||
degrees: 0.0
|
||||
translate: 0.04591
|
||||
scale: 0.75544
|
||||
shear: 0.0
|
||||
perspective: 0.0
|
||||
flipud: 0.0
|
||||
fliplr: 0.5
|
||||
mosaic: 0.85834
|
||||
mixup: 0.04266
|
||||
copy_paste: 0.0
|
||||
anchors: 3.412
|
36
yolov5/data/hyps/hyp.no-augmentation.yaml
Normal file
36
yolov5/data/hyps/hyp.no-augmentation.yaml
Normal file
@ -0,0 +1,36 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Hyperparameters when using Albumentations frameworks
|
||||
# python train.py --hyp hyp.no-augmentation.yaml
|
||||
# See https://github.com/ultralytics/yolov5/pull/3882 for YOLOv5 + Albumentations Usage examples
|
||||
|
||||
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
||||
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
|
||||
momentum: 0.937 # SGD momentum/Adam beta1
|
||||
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
||||
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
||||
warmup_momentum: 0.8 # warmup initial momentum
|
||||
warmup_bias_lr: 0.1 # warmup initial bias lr
|
||||
box: 0.05 # box loss gain
|
||||
cls: 0.3 # cls loss gain
|
||||
cls_pw: 1.0 # cls BCELoss positive_weight
|
||||
obj: 0.7 # obj loss gain (scale with pixels)
|
||||
obj_pw: 1.0 # obj BCELoss positive_weight
|
||||
iou_t: 0.20 # IoU training threshold
|
||||
anchor_t: 4.0 # anchor-multiple threshold
|
||||
# anchors: 3 # anchors per output layer (0 to ignore)
|
||||
# this parameters are all zero since we want to use albumentation framework
|
||||
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
||||
hsv_h: 0 # image HSV-Hue augmentation (fraction)
|
||||
hsv_s: 0 # image HSV-Saturation augmentation (fraction)
|
||||
hsv_v: 0 # image HSV-Value augmentation (fraction)
|
||||
degrees: 0.0 # image rotation (+/- deg)
|
||||
translate: 0 # image translation (+/- fraction)
|
||||
scale: 0 # image scale (+/- gain)
|
||||
shear: 0 # image shear (+/- deg)
|
||||
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
||||
flipud: 0.0 # image flip up-down (probability)
|
||||
fliplr: 0.0 # image flip left-right (probability)
|
||||
mosaic: 0.0 # image mosaic (probability)
|
||||
mixup: 0.0 # image mixup (probability)
|
||||
copy_paste: 0.0 # segment copy-paste (probability)
|
35
yolov5/data/hyps/hyp.scratch-high.yaml
Normal file
35
yolov5/data/hyps/hyp.scratch-high.yaml
Normal file
@ -0,0 +1,35 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Hyperparameters for high-augmentation COCO training from scratch
|
||||
# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300
|
||||
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
||||
|
||||
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
||||
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
|
||||
momentum: 0.937 # SGD momentum/Adam beta1
|
||||
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
||||
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
||||
warmup_momentum: 0.8 # warmup initial momentum
|
||||
warmup_bias_lr: 0.1 # warmup initial bias lr
|
||||
box: 0.05 # box loss gain
|
||||
cls: 0.3 # cls loss gain
|
||||
cls_pw: 1.0 # cls BCELoss positive_weight
|
||||
obj: 0.7 # obj loss gain (scale with pixels)
|
||||
obj_pw: 1.0 # obj BCELoss positive_weight
|
||||
iou_t: 0.20 # IoU training threshold
|
||||
anchor_t: 4.0 # anchor-multiple threshold
|
||||
# anchors: 3 # anchors per output layer (0 to ignore)
|
||||
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
||||
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
||||
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
||||
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
||||
degrees: 0.0 # image rotation (+/- deg)
|
||||
translate: 0.1 # image translation (+/- fraction)
|
||||
scale: 0.9 # image scale (+/- gain)
|
||||
shear: 0.0 # image shear (+/- deg)
|
||||
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
||||
flipud: 0.0 # image flip up-down (probability)
|
||||
fliplr: 0.5 # image flip left-right (probability)
|
||||
mosaic: 1.0 # image mosaic (probability)
|
||||
mixup: 0.1 # image mixup (probability)
|
||||
copy_paste: 0.1 # segment copy-paste (probability)
|
35
yolov5/data/hyps/hyp.scratch-low.yaml
Normal file
35
yolov5/data/hyps/hyp.scratch-low.yaml
Normal file
@ -0,0 +1,35 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Hyperparameters for low-augmentation COCO training from scratch
|
||||
# python train.py --batch 64 --cfg yolov5n6.yaml --weights '' --data coco.yaml --img 640 --epochs 300 --linear
|
||||
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
||||
|
||||
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
||||
lrf: 0.01 # final OneCycleLR learning rate (lr0 * lrf)
|
||||
momentum: 0.937 # SGD momentum/Adam beta1
|
||||
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
||||
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
||||
warmup_momentum: 0.8 # warmup initial momentum
|
||||
warmup_bias_lr: 0.1 # warmup initial bias lr
|
||||
box: 0.05 # box loss gain
|
||||
cls: 0.5 # cls loss gain
|
||||
cls_pw: 1.0 # cls BCELoss positive_weight
|
||||
obj: 1.0 # obj loss gain (scale with pixels)
|
||||
obj_pw: 1.0 # obj BCELoss positive_weight
|
||||
iou_t: 0.20 # IoU training threshold
|
||||
anchor_t: 4.0 # anchor-multiple threshold
|
||||
# anchors: 3 # anchors per output layer (0 to ignore)
|
||||
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
||||
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
||||
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
||||
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
||||
degrees: 0.0 # image rotation (+/- deg)
|
||||
translate: 0.1 # image translation (+/- fraction)
|
||||
scale: 0.5 # image scale (+/- gain)
|
||||
shear: 0.0 # image shear (+/- deg)
|
||||
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
||||
flipud: 0.0 # image flip up-down (probability)
|
||||
fliplr: 0.5 # image flip left-right (probability)
|
||||
mosaic: 1.0 # image mosaic (probability)
|
||||
mixup: 0.0 # image mixup (probability)
|
||||
copy_paste: 0.0 # segment copy-paste (probability)
|
35
yolov5/data/hyps/hyp.scratch-med.yaml
Normal file
35
yolov5/data/hyps/hyp.scratch-med.yaml
Normal file
@ -0,0 +1,35 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Hyperparameters for medium-augmentation COCO training from scratch
|
||||
# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300
|
||||
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
||||
|
||||
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
||||
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
|
||||
momentum: 0.937 # SGD momentum/Adam beta1
|
||||
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
||||
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
||||
warmup_momentum: 0.8 # warmup initial momentum
|
||||
warmup_bias_lr: 0.1 # warmup initial bias lr
|
||||
box: 0.05 # box loss gain
|
||||
cls: 0.3 # cls loss gain
|
||||
cls_pw: 1.0 # cls BCELoss positive_weight
|
||||
obj: 0.7 # obj loss gain (scale with pixels)
|
||||
obj_pw: 1.0 # obj BCELoss positive_weight
|
||||
iou_t: 0.20 # IoU training threshold
|
||||
anchor_t: 4.0 # anchor-multiple threshold
|
||||
# anchors: 3 # anchors per output layer (0 to ignore)
|
||||
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
||||
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
||||
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
||||
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
||||
degrees: 0.0 # image rotation (+/- deg)
|
||||
translate: 0.1 # image translation (+/- fraction)
|
||||
scale: 0.9 # image scale (+/- gain)
|
||||
shear: 0.0 # image shear (+/- deg)
|
||||
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
||||
flipud: 0.0 # image flip up-down (probability)
|
||||
fliplr: 0.5 # image flip left-right (probability)
|
||||
mosaic: 1.0 # image mosaic (probability)
|
||||
mixup: 0.1 # image mixup (probability)
|
||||
copy_paste: 0.0 # segment copy-paste (probability)
|
22
yolov5/data/scripts/download_weights.sh
Normal file
22
yolov5/data/scripts/download_weights.sh
Normal file
@ -0,0 +1,22 @@
|
||||
#!/bin/bash
|
||||
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
|
||||
# Download latest models from https://github.com/ultralytics/yolov5/releases
|
||||
# Example usage: bash data/scripts/download_weights.sh
|
||||
# parent
|
||||
# └── yolov5
|
||||
# ├── yolov5s.pt ← downloads here
|
||||
# ├── yolov5m.pt
|
||||
# └── ...
|
||||
|
||||
python - <<EOF
|
||||
from utils.downloads import attempt_download
|
||||
|
||||
p5 = list('nsmlx') # P5 models
|
||||
p6 = [f'{x}6' for x in p5] # P6 models
|
||||
cls = [f'{x}-cls' for x in p5] # classification models
|
||||
seg = [f'{x}-seg' for x in p5] # classification models
|
||||
|
||||
for x in p5 + p6 + cls + seg:
|
||||
attempt_download(f'weights/yolov5{x}.pt')
|
||||
|
||||
EOF
|
438
yolov5/detect.py
Normal file
438
yolov5/detect.py
Normal file
@ -0,0 +1,438 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""
|
||||
Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
|
||||
|
||||
Usage - sources:
|
||||
$ python detect.py --weights yolov5s.pt --source 0 # webcam
|
||||
img.jpg # image
|
||||
vid.mp4 # video
|
||||
screen # screenshot
|
||||
path/ # directory
|
||||
list.txt # list of images
|
||||
list.streams # list of streams
|
||||
'path/*.jpg' # glob
|
||||
'https://youtu.be/LNwODJXcvt4' # YouTube
|
||||
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
|
||||
|
||||
Usage - formats:
|
||||
$ python detect.py --weights yolov5s.pt # PyTorch
|
||||
yolov5s.torchscript # TorchScript
|
||||
yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
||||
yolov5s_openvino_model # OpenVINO
|
||||
yolov5s.engine # TensorRT
|
||||
yolov5s.mlpackage # CoreML (macOS-only)
|
||||
yolov5s_saved_model # TensorFlow SavedModel
|
||||
yolov5s.pb # TensorFlow GraphDef
|
||||
yolov5s.tflite # TensorFlow Lite
|
||||
yolov5s_edgetpu.tflite # TensorFlow Edge TPU
|
||||
yolov5s_paddle_model # PaddlePaddle
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
FILE = Path(__file__).resolve()
|
||||
ROOT = FILE.parents[0] # YOLOv5 root directory
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.append(str(ROOT)) # add ROOT to PATH
|
||||
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
||||
|
||||
from ultralytics.utils.plotting import Annotator, colors, save_one_box
|
||||
|
||||
from models.common import DetectMultiBackend
|
||||
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
|
||||
from utils.general import (
|
||||
LOGGER,
|
||||
Profile,
|
||||
check_file,
|
||||
check_img_size,
|
||||
check_imshow,
|
||||
check_requirements,
|
||||
colorstr,
|
||||
cv2,
|
||||
increment_path,
|
||||
non_max_suppression,
|
||||
print_args,
|
||||
scale_boxes,
|
||||
strip_optimizer,
|
||||
xyxy2xywh,
|
||||
)
|
||||
from utils.torch_utils import select_device, smart_inference_mode
|
||||
|
||||
|
||||
@smart_inference_mode()
|
||||
def run(
|
||||
weights=ROOT / "yolov5s.pt", # model path or triton URL
|
||||
source=ROOT / "data/images", # file/dir/URL/glob/screen/0(webcam)
|
||||
data=ROOT / "data/coco128.yaml", # dataset.yaml path
|
||||
imgsz=(640, 640), # inference size (height, width)
|
||||
conf_thres=0.25, # confidence threshold
|
||||
iou_thres=0.45, # NMS IOU threshold
|
||||
max_det=1000, # maximum detections per image
|
||||
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
||||
view_img=False, # show results
|
||||
save_txt=False, # save results to *.txt
|
||||
save_format=0, # save boxes coordinates in YOLO format or Pascal-VOC format (0 for YOLO and 1 for Pascal-VOC)
|
||||
save_csv=False, # save results in CSV format
|
||||
save_conf=False, # save confidences in --save-txt labels
|
||||
save_crop=False, # save cropped prediction boxes
|
||||
nosave=False, # do not save images/videos
|
||||
classes=None, # filter by class: --class 0, or --class 0 2 3
|
||||
agnostic_nms=False, # class-agnostic NMS
|
||||
augment=False, # augmented inference
|
||||
visualize=False, # visualize features
|
||||
update=False, # update all models
|
||||
project=ROOT / "runs/detect", # save results to project/name
|
||||
name="exp", # save results to project/name
|
||||
exist_ok=False, # existing project/name ok, do not increment
|
||||
line_thickness=3, # bounding box thickness (pixels)
|
||||
hide_labels=False, # hide labels
|
||||
hide_conf=False, # hide confidences
|
||||
half=False, # use FP16 half-precision inference
|
||||
dnn=False, # use OpenCV DNN for ONNX inference
|
||||
vid_stride=1, # video frame-rate stride
|
||||
):
|
||||
"""
|
||||
Runs YOLOv5 detection inference on various sources like images, videos, directories, streams, etc.
|
||||
|
||||
Args:
|
||||
weights (str | Path): Path to the model weights file or a Triton URL. Default is 'yolov5s.pt'.
|
||||
source (str | Path): Input source, which can be a file, directory, URL, glob pattern, screen capture, or webcam
|
||||
index. Default is 'data/images'.
|
||||
data (str | Path): Path to the dataset YAML file. Default is 'data/coco128.yaml'.
|
||||
imgsz (tuple[int, int]): Inference image size as a tuple (height, width). Default is (640, 640).
|
||||
conf_thres (float): Confidence threshold for detections. Default is 0.25.
|
||||
iou_thres (float): Intersection Over Union (IOU) threshold for non-max suppression. Default is 0.45.
|
||||
max_det (int): Maximum number of detections per image. Default is 1000.
|
||||
device (str): CUDA device identifier (e.g., '0' or '0,1,2,3') or 'cpu'. Default is an empty string, which uses the
|
||||
best available device.
|
||||
view_img (bool): If True, display inference results using OpenCV. Default is False.
|
||||
save_txt (bool): If True, save results in a text file. Default is False.
|
||||
save_csv (bool): If True, save results in a CSV file. Default is False.
|
||||
save_conf (bool): If True, include confidence scores in the saved results. Default is False.
|
||||
save_crop (bool): If True, save cropped prediction boxes. Default is False.
|
||||
nosave (bool): If True, do not save inference images or videos. Default is False.
|
||||
classes (list[int]): List of class indices to filter detections by. Default is None.
|
||||
agnostic_nms (bool): If True, perform class-agnostic non-max suppression. Default is False.
|
||||
augment (bool): If True, use augmented inference. Default is False.
|
||||
visualize (bool): If True, visualize feature maps. Default is False.
|
||||
update (bool): If True, update all models' weights. Default is False.
|
||||
project (str | Path): Directory to save results. Default is 'runs/detect'.
|
||||
name (str): Name of the current experiment; used to create a subdirectory within 'project'. Default is 'exp'.
|
||||
exist_ok (bool): If True, existing directories with the same name are reused instead of being incremented. Default is
|
||||
False.
|
||||
line_thickness (int): Thickness of bounding box lines in pixels. Default is 3.
|
||||
hide_labels (bool): If True, do not display labels on bounding boxes. Default is False.
|
||||
hide_conf (bool): If True, do not display confidence scores on bounding boxes. Default is False.
|
||||
half (bool): If True, use FP16 half-precision inference. Default is False.
|
||||
dnn (bool): If True, use OpenCV DNN backend for ONNX inference. Default is False.
|
||||
vid_stride (int): Stride for processing video frames, to skip frames between processing. Default is 1.
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Examples:
|
||||
```python
|
||||
from ultralytics import run
|
||||
|
||||
# Run inference on an image
|
||||
run(source='data/images/example.jpg', weights='yolov5s.pt', device='0')
|
||||
|
||||
# Run inference on a video with specific confidence threshold
|
||||
run(source='data/videos/example.mp4', weights='yolov5s.pt', conf_thres=0.4, device='0')
|
||||
```
|
||||
"""
|
||||
source = str(source)
|
||||
save_img = not nosave and not source.endswith(".txt") # save inference images
|
||||
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
||||
is_url = source.lower().startswith(("rtsp://", "rtmp://", "http://", "https://"))
|
||||
webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
|
||||
screenshot = source.lower().startswith("screen")
|
||||
if is_url and is_file:
|
||||
source = check_file(source) # download
|
||||
|
||||
# Directories
|
||||
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
||||
(save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
||||
|
||||
# Load model
|
||||
device = select_device(device)
|
||||
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
|
||||
stride, names, pt = model.stride, model.names, model.pt
|
||||
imgsz = check_img_size(imgsz, s=stride) # check image size
|
||||
|
||||
# Dataloader
|
||||
bs = 1 # batch_size
|
||||
if webcam:
|
||||
view_img = check_imshow(warn=True)
|
||||
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
|
||||
bs = len(dataset)
|
||||
elif screenshot:
|
||||
dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
|
||||
else:
|
||||
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
|
||||
vid_path, vid_writer = [None] * bs, [None] * bs
|
||||
|
||||
# Run inference
|
||||
model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup
|
||||
seen, windows, dt = 0, [], (Profile(device=device), Profile(device=device), Profile(device=device))
|
||||
for path, im, im0s, vid_cap, s in dataset:
|
||||
with dt[0]:
|
||||
im = torch.from_numpy(im).to(model.device)
|
||||
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
|
||||
im /= 255 # 0 - 255 to 0.0 - 1.0
|
||||
if len(im.shape) == 3:
|
||||
im = im[None] # expand for batch dim
|
||||
if model.xml and im.shape[0] > 1:
|
||||
ims = torch.chunk(im, im.shape[0], 0)
|
||||
|
||||
# Inference
|
||||
with dt[1]:
|
||||
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
|
||||
if model.xml and im.shape[0] > 1:
|
||||
pred = None
|
||||
for image in ims:
|
||||
if pred is None:
|
||||
pred = model(image, augment=augment, visualize=visualize).unsqueeze(0)
|
||||
else:
|
||||
pred = torch.cat((pred, model(image, augment=augment, visualize=visualize).unsqueeze(0)), dim=0)
|
||||
pred = [pred, None]
|
||||
else:
|
||||
pred = model(im, augment=augment, visualize=visualize)
|
||||
# NMS
|
||||
with dt[2]:
|
||||
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
|
||||
|
||||
# Second-stage classifier (optional)
|
||||
# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
|
||||
|
||||
# Define the path for the CSV file
|
||||
csv_path = save_dir / "predictions.csv"
|
||||
|
||||
# Create or append to the CSV file
|
||||
def write_to_csv(image_name, prediction, confidence):
|
||||
"""Writes prediction data for an image to a CSV file, appending if the file exists."""
|
||||
data = {"Image Name": image_name, "Prediction": prediction, "Confidence": confidence}
|
||||
file_exists = os.path.isfile(csv_path)
|
||||
with open(csv_path, mode="a", newline="") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=data.keys())
|
||||
if not file_exists:
|
||||
writer.writeheader()
|
||||
writer.writerow(data)
|
||||
|
||||
# Process predictions
|
||||
for i, det in enumerate(pred): # per image
|
||||
seen += 1
|
||||
if webcam: # batch_size >= 1
|
||||
p, im0, frame = path[i], im0s[i].copy(), dataset.count
|
||||
s += f"{i}: "
|
||||
else:
|
||||
p, im0, frame = path, im0s.copy(), getattr(dataset, "frame", 0)
|
||||
|
||||
p = Path(p) # to Path
|
||||
save_path = str(save_dir / p.name) # im.jpg
|
||||
txt_path = str(save_dir / "labels" / p.stem) + ("" if dataset.mode == "image" else f"_{frame}") # im.txt
|
||||
s += "{:g}x{:g} ".format(*im.shape[2:]) # print string
|
||||
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
||||
imc = im0.copy() if save_crop else im0 # for save_crop
|
||||
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
|
||||
if len(det):
|
||||
# Rescale boxes from img_size to im0 size
|
||||
det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()
|
||||
|
||||
# Print results
|
||||
for c in det[:, 5].unique():
|
||||
n = (det[:, 5] == c).sum() # detections per class
|
||||
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
|
||||
|
||||
# Write results
|
||||
for *xyxy, conf, cls in reversed(det):
|
||||
c = int(cls) # integer class
|
||||
label = names[c] if hide_conf else f"{names[c]}"
|
||||
confidence = float(conf)
|
||||
confidence_str = f"{confidence:.2f}"
|
||||
|
||||
if save_csv:
|
||||
write_to_csv(p.name, label, confidence_str)
|
||||
|
||||
if save_txt: # Write to file
|
||||
if save_format == 0:
|
||||
coords = (
|
||||
(xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
|
||||
) # normalized xywh
|
||||
else:
|
||||
coords = (torch.tensor(xyxy).view(1, 4) / gn).view(-1).tolist() # xyxy
|
||||
line = (cls, *coords, conf) if save_conf else (cls, *coords) # label format
|
||||
with open(f"{txt_path}.txt", "a") as f:
|
||||
f.write(("%g " * len(line)).rstrip() % line + "\n")
|
||||
|
||||
if save_img or save_crop or view_img: # Add bbox to image
|
||||
c = int(cls) # integer class
|
||||
label = None if hide_labels else (names[c] if hide_conf else f"{names[c]} {conf:.2f}")
|
||||
annotator.box_label(xyxy, label, color=colors(c, True))
|
||||
if save_crop:
|
||||
save_one_box(xyxy, imc, file=save_dir / "crops" / names[c] / f"{p.stem}.jpg", BGR=True)
|
||||
|
||||
# Stream results
|
||||
im0 = annotator.result()
|
||||
if view_img:
|
||||
if platform.system() == "Linux" and p not in windows:
|
||||
windows.append(p)
|
||||
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
|
||||
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
|
||||
cv2.imshow(str(p), im0)
|
||||
cv2.waitKey(1) # 1 millisecond
|
||||
|
||||
# Save results (image with detections)
|
||||
if save_img:
|
||||
if dataset.mode == "image":
|
||||
cv2.imwrite(save_path, im0)
|
||||
else: # 'video' or 'stream'
|
||||
if vid_path[i] != save_path: # new video
|
||||
vid_path[i] = save_path
|
||||
if isinstance(vid_writer[i], cv2.VideoWriter):
|
||||
vid_writer[i].release() # release previous video writer
|
||||
if vid_cap: # video
|
||||
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
||||
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
else: # stream
|
||||
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
||||
save_path = str(Path(save_path).with_suffix(".mp4")) # force *.mp4 suffix on results videos
|
||||
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
|
||||
vid_writer[i].write(im0)
|
||||
|
||||
# Print time (inference-only)
|
||||
LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1e3:.1f}ms")
|
||||
|
||||
# Print results
|
||||
t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image
|
||||
LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}" % t)
|
||||
if save_txt or save_img:
|
||||
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ""
|
||||
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
||||
if update:
|
||||
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
|
||||
|
||||
|
||||
def parse_opt():
|
||||
"""
|
||||
Parse command-line arguments for YOLOv5 detection, allowing custom inference options and model configurations.
|
||||
|
||||
Args:
|
||||
--weights (str | list[str], optional): Model path or Triton URL. Defaults to ROOT / 'yolov5s.pt'.
|
||||
--source (str, optional): File/dir/URL/glob/screen/0(webcam). Defaults to ROOT / 'data/images'.
|
||||
--data (str, optional): Dataset YAML path. Provides dataset configuration information.
|
||||
--imgsz (list[int], optional): Inference size (height, width). Defaults to [640].
|
||||
--conf-thres (float, optional): Confidence threshold. Defaults to 0.25.
|
||||
--iou-thres (float, optional): NMS IoU threshold. Defaults to 0.45.
|
||||
--max-det (int, optional): Maximum number of detections per image. Defaults to 1000.
|
||||
--device (str, optional): CUDA device, i.e., '0' or '0,1,2,3' or 'cpu'. Defaults to "".
|
||||
--view-img (bool, optional): Flag to display results. Defaults to False.
|
||||
--save-txt (bool, optional): Flag to save results to *.txt files. Defaults to False.
|
||||
--save-csv (bool, optional): Flag to save results in CSV format. Defaults to False.
|
||||
--save-conf (bool, optional): Flag to save confidences in labels saved via --save-txt. Defaults to False.
|
||||
--save-crop (bool, optional): Flag to save cropped prediction boxes. Defaults to False.
|
||||
--nosave (bool, optional): Flag to prevent saving images/videos. Defaults to False.
|
||||
--classes (list[int], optional): List of classes to filter results by, e.g., '--classes 0 2 3'. Defaults to None.
|
||||
--agnostic-nms (bool, optional): Flag for class-agnostic NMS. Defaults to False.
|
||||
--augment (bool, optional): Flag for augmented inference. Defaults to False.
|
||||
--visualize (bool, optional): Flag for visualizing features. Defaults to False.
|
||||
--update (bool, optional): Flag to update all models in the model directory. Defaults to False.
|
||||
--project (str, optional): Directory to save results. Defaults to ROOT / 'runs/detect'.
|
||||
--name (str, optional): Sub-directory name for saving results within --project. Defaults to 'exp'.
|
||||
--exist-ok (bool, optional): Flag to allow overwriting if the project/name already exists. Defaults to False.
|
||||
--line-thickness (int, optional): Thickness (in pixels) of bounding boxes. Defaults to 3.
|
||||
--hide-labels (bool, optional): Flag to hide labels in the output. Defaults to False.
|
||||
--hide-conf (bool, optional): Flag to hide confidences in the output. Defaults to False.
|
||||
--half (bool, optional): Flag to use FP16 half-precision inference. Defaults to False.
|
||||
--dnn (bool, optional): Flag to use OpenCV DNN for ONNX inference. Defaults to False.
|
||||
--vid-stride (int, optional): Video frame-rate stride, determining the number of frames to skip in between
|
||||
consecutive frames. Defaults to 1.
|
||||
|
||||
Returns:
|
||||
argparse.Namespace: Parsed command-line arguments as an argparse.Namespace object.
|
||||
|
||||
Example:
|
||||
```python
|
||||
from ultralytics import YOLOv5
|
||||
args = YOLOv5.parse_opt()
|
||||
```
|
||||
"""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s.pt", help="model path or triton URL")
|
||||
parser.add_argument("--source", type=str, default=ROOT / "data/images", help="file/dir/URL/glob/screen/0(webcam)")
|
||||
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="(optional) dataset.yaml path")
|
||||
parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[640], help="inference size h,w")
|
||||
parser.add_argument("--conf-thres", type=float, default=0.25, help="confidence threshold")
|
||||
parser.add_argument("--iou-thres", type=float, default=0.45, help="NMS IoU threshold")
|
||||
parser.add_argument("--max-det", type=int, default=1000, help="maximum detections per image")
|
||||
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
||||
parser.add_argument("--view-img", action="store_true", help="show results")
|
||||
parser.add_argument("--save-txt", action="store_true", help="save results to *.txt")
|
||||
parser.add_argument(
|
||||
"--save-format",
|
||||
type=int,
|
||||
default=0,
|
||||
help="whether to save boxes coordinates in YOLO format or Pascal-VOC format when save-txt is True, 0 for YOLO and 1 for Pascal-VOC",
|
||||
)
|
||||
parser.add_argument("--save-csv", action="store_true", help="save results in CSV format")
|
||||
parser.add_argument("--save-conf", action="store_true", help="save confidences in --save-txt labels")
|
||||
parser.add_argument("--save-crop", action="store_true", help="save cropped prediction boxes")
|
||||
parser.add_argument("--nosave", action="store_true", help="do not save images/videos")
|
||||
parser.add_argument("--classes", nargs="+", type=int, help="filter by class: --classes 0, or --classes 0 2 3")
|
||||
parser.add_argument("--agnostic-nms", action="store_true", help="class-agnostic NMS")
|
||||
parser.add_argument("--augment", action="store_true", help="augmented inference")
|
||||
parser.add_argument("--visualize", action="store_true", help="visualize features")
|
||||
parser.add_argument("--update", action="store_true", help="update all models")
|
||||
parser.add_argument("--project", default=ROOT / "runs/detect", help="save results to project/name")
|
||||
parser.add_argument("--name", default="exp", help="save results to project/name")
|
||||
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
|
||||
parser.add_argument("--line-thickness", default=3, type=int, help="bounding box thickness (pixels)")
|
||||
parser.add_argument("--hide-labels", default=False, action="store_true", help="hide labels")
|
||||
parser.add_argument("--hide-conf", default=False, action="store_true", help="hide confidences")
|
||||
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
|
||||
parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference")
|
||||
parser.add_argument("--vid-stride", type=int, default=1, help="video frame-rate stride")
|
||||
opt = parser.parse_args()
|
||||
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
||||
print_args(vars(opt))
|
||||
return opt
|
||||
|
||||
|
||||
def main(opt):
|
||||
"""
|
||||
Executes YOLOv5 model inference based on provided command-line arguments, validating dependencies before running.
|
||||
|
||||
Args:
|
||||
opt (argparse.Namespace): Command-line arguments for YOLOv5 detection. See function `parse_opt` for details.
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Note:
|
||||
This function performs essential pre-execution checks and initiates the YOLOv5 detection process based on user-specified
|
||||
options. Refer to the usage guide and examples for more information about different sources and formats at:
|
||||
https://github.com/ultralytics/ultralytics
|
||||
|
||||
Example usage:
|
||||
|
||||
```python
|
||||
if __name__ == "__main__":
|
||||
opt = parse_opt()
|
||||
main(opt)
|
||||
```
|
||||
"""
|
||||
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
|
||||
run(**vars(opt))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
opt = parse_opt()
|
||||
main(opt)
|
1546
yolov5/export.py
Normal file
1546
yolov5/export.py
Normal file
File diff suppressed because it is too large
Load Diff
510
yolov5/hubconf.py
Normal file
510
yolov5/hubconf.py
Normal file
@ -0,0 +1,510 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""
|
||||
PyTorch Hub models https://pytorch.org/hub/ultralytics_yolov5.
|
||||
|
||||
Usage:
|
||||
import torch
|
||||
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # official model
|
||||
model = torch.hub.load('ultralytics/yolov5:master', 'yolov5s') # from branch
|
||||
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.pt') # custom/local model
|
||||
model = torch.hub.load('.', 'custom', 'yolov5s.pt', source='local') # local repo
|
||||
"""
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def _create(name, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True, device=None):
|
||||
"""
|
||||
Creates or loads a YOLOv5 model, with options for pretrained weights and model customization.
|
||||
|
||||
Args:
|
||||
name (str): Model name (e.g., 'yolov5s') or path to the model checkpoint (e.g., 'path/to/best.pt').
|
||||
pretrained (bool, optional): If True, loads pretrained weights into the model. Defaults to True.
|
||||
channels (int, optional): Number of input channels the model expects. Defaults to 3.
|
||||
classes (int, optional): Number of classes the model is expected to detect. Defaults to 80.
|
||||
autoshape (bool, optional): If True, applies the YOLOv5 .autoshape() wrapper for various input formats. Defaults to True.
|
||||
verbose (bool, optional): If True, prints detailed information during the model creation/loading process. Defaults to True.
|
||||
device (str | torch.device | None, optional): Device to use for model parameters (e.g., 'cpu', 'cuda'). If None, selects
|
||||
the best available device. Defaults to None.
|
||||
|
||||
Returns:
|
||||
(DetectMultiBackend | AutoShape): The loaded YOLOv5 model, potentially wrapped with AutoShape if specified.
|
||||
|
||||
Examples:
|
||||
```python
|
||||
import torch
|
||||
from ultralytics import _create
|
||||
|
||||
# Load an official YOLOv5s model with pretrained weights
|
||||
model = _create('yolov5s')
|
||||
|
||||
# Load a custom model from a local checkpoint
|
||||
model = _create('path/to/custom_model.pt', pretrained=False)
|
||||
|
||||
# Load a model with specific input channels and classes
|
||||
model = _create('yolov5s', channels=1, classes=10)
|
||||
```
|
||||
|
||||
Notes:
|
||||
For more information on model loading and customization, visit the
|
||||
[YOLOv5 PyTorch Hub Documentation](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading).
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
from models.common import AutoShape, DetectMultiBackend
|
||||
from models.experimental import attempt_load
|
||||
from models.yolo import ClassificationModel, DetectionModel, SegmentationModel
|
||||
from utils.downloads import attempt_download
|
||||
from utils.general import LOGGER, ROOT, check_requirements, intersect_dicts, logging
|
||||
from utils.torch_utils import select_device
|
||||
|
||||
if not verbose:
|
||||
LOGGER.setLevel(logging.WARNING)
|
||||
check_requirements(ROOT / "requirements.txt", exclude=("opencv-python", "tensorboard", "thop"))
|
||||
name = Path(name)
|
||||
path = name.with_suffix(".pt") if name.suffix == "" and not name.is_dir() else name # checkpoint path
|
||||
try:
|
||||
device = select_device(device)
|
||||
if pretrained and channels == 3 and classes == 80:
|
||||
try:
|
||||
model = DetectMultiBackend(path, device=device, fuse=autoshape) # detection model
|
||||
if autoshape:
|
||||
if model.pt and isinstance(model.model, ClassificationModel):
|
||||
LOGGER.warning(
|
||||
"WARNING ⚠️ YOLOv5 ClassificationModel is not yet AutoShape compatible. "
|
||||
"You must pass torch tensors in BCHW to this model, i.e. shape(1,3,224,224)."
|
||||
)
|
||||
elif model.pt and isinstance(model.model, SegmentationModel):
|
||||
LOGGER.warning(
|
||||
"WARNING ⚠️ YOLOv5 SegmentationModel is not yet AutoShape compatible. "
|
||||
"You will not be able to run inference with this model."
|
||||
)
|
||||
else:
|
||||
model = AutoShape(model) # for file/URI/PIL/cv2/np inputs and NMS
|
||||
except Exception:
|
||||
model = attempt_load(path, device=device, fuse=False) # arbitrary model
|
||||
else:
|
||||
cfg = list((Path(__file__).parent / "models").rglob(f"{path.stem}.yaml"))[0] # model.yaml path
|
||||
model = DetectionModel(cfg, channels, classes) # create model
|
||||
if pretrained:
|
||||
ckpt = torch.load(attempt_download(path), map_location=device) # load
|
||||
csd = ckpt["model"].float().state_dict() # checkpoint state_dict as FP32
|
||||
csd = intersect_dicts(csd, model.state_dict(), exclude=["anchors"]) # intersect
|
||||
model.load_state_dict(csd, strict=False) # load
|
||||
if len(ckpt["model"].names) == classes:
|
||||
model.names = ckpt["model"].names # set class names attribute
|
||||
if not verbose:
|
||||
LOGGER.setLevel(logging.INFO) # reset to default
|
||||
return model.to(device)
|
||||
|
||||
except Exception as e:
|
||||
help_url = "https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading"
|
||||
s = f"{e}. Cache may be out of date, try `force_reload=True` or see {help_url} for help."
|
||||
raise Exception(s) from e
|
||||
|
||||
|
||||
def custom(path="path/to/model.pt", autoshape=True, _verbose=True, device=None):
|
||||
"""
|
||||
Loads a custom or local YOLOv5 model from a given path with optional autoshaping and device specification.
|
||||
|
||||
Args:
|
||||
path (str): Path to the custom model file (e.g., 'path/to/model.pt').
|
||||
autoshape (bool): Apply YOLOv5 .autoshape() wrapper to model if True, enabling compatibility with various input
|
||||
types (default is True).
|
||||
_verbose (bool): If True, prints all informational messages to the screen; otherwise, operates silently
|
||||
(default is True).
|
||||
device (str | torch.device | None): Device to load the model on, e.g., 'cpu', 'cuda', torch.device('cuda:0'), etc.
|
||||
(default is None, which automatically selects the best available device).
|
||||
|
||||
Returns:
|
||||
torch.nn.Module: A YOLOv5 model loaded with the specified parameters.
|
||||
|
||||
Notes:
|
||||
For more details on loading models from PyTorch Hub:
|
||||
https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading
|
||||
|
||||
Examples:
|
||||
```python
|
||||
# Load model from a given path with autoshape enabled on the best available device
|
||||
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.pt')
|
||||
|
||||
# Load model from a local path without autoshape on the CPU device
|
||||
model = torch.hub.load('.', 'custom', 'yolov5s.pt', source='local', autoshape=False, device='cpu')
|
||||
```
|
||||
"""
|
||||
return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
|
||||
|
||||
|
||||
def yolov5n(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
||||
"""
|
||||
Instantiates the YOLOv5-nano model with options for pretraining, input channels, class count, autoshaping,
|
||||
verbosity, and device.
|
||||
|
||||
Args:
|
||||
pretrained (bool): If True, loads pretrained weights into the model. Defaults to True.
|
||||
channels (int): Number of input channels for the model. Defaults to 3.
|
||||
classes (int): Number of classes for object detection. Defaults to 80.
|
||||
autoshape (bool): If True, applies the YOLOv5 .autoshape() wrapper to the model for various formats (file/URI/PIL/
|
||||
cv2/np) and non-maximum suppression (NMS) during inference. Defaults to True.
|
||||
_verbose (bool): If True, prints detailed information to the screen. Defaults to True.
|
||||
device (str | torch.device | None): Specifies the device to use for model computation. If None, uses the best device
|
||||
available (i.e., GPU if available, otherwise CPU). Defaults to None.
|
||||
|
||||
Returns:
|
||||
DetectionModel | ClassificationModel | SegmentationModel: The instantiated YOLOv5-nano model, potentially with
|
||||
pretrained weights and autoshaping applied.
|
||||
|
||||
Notes:
|
||||
For further details on loading models from PyTorch Hub, refer to [PyTorch Hub models](https://pytorch.org/hub/
|
||||
ultralytics_yolov5).
|
||||
|
||||
Examples:
|
||||
```python
|
||||
import torch
|
||||
from ultralytics import yolov5n
|
||||
|
||||
# Load the YOLOv5-nano model with defaults
|
||||
model = yolov5n()
|
||||
|
||||
# Load the YOLOv5-nano model with a specific device
|
||||
model = yolov5n(device='cuda')
|
||||
```
|
||||
"""
|
||||
return _create("yolov5n", pretrained, channels, classes, autoshape, _verbose, device)
|
||||
|
||||
|
||||
def yolov5s(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
||||
"""
|
||||
Create a YOLOv5-small (yolov5s) model with options for pretraining, input channels, class count, autoshaping,
|
||||
verbosity, and device configuration.
|
||||
|
||||
Args:
|
||||
pretrained (bool, optional): Flag to load pretrained weights into the model. Defaults to True.
|
||||
channels (int, optional): Number of input channels. Defaults to 3.
|
||||
classes (int, optional): Number of model classes. Defaults to 80.
|
||||
autoshape (bool, optional): Whether to wrap the model with YOLOv5's .autoshape() for handling various input formats.
|
||||
Defaults to True.
|
||||
_verbose (bool, optional): Flag to print detailed information regarding model loading. Defaults to True.
|
||||
device (str | torch.device | None, optional): Device to use for model computation, can be 'cpu', 'cuda', or
|
||||
torch.device instances. If None, automatically selects the best available device. Defaults to None.
|
||||
|
||||
Returns:
|
||||
torch.nn.Module: The YOLOv5-small model configured and loaded according to the specified parameters.
|
||||
|
||||
Example:
|
||||
```python
|
||||
import torch
|
||||
|
||||
# Load the official YOLOv5-small model with pretrained weights
|
||||
model = torch.hub.load('ultralytics/yolov5', 'yolov5s')
|
||||
|
||||
# Load the YOLOv5-small model from a specific branch
|
||||
model = torch.hub.load('ultralytics/yolov5:master', 'yolov5s')
|
||||
|
||||
# Load a custom YOLOv5-small model from a local checkpoint
|
||||
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.pt')
|
||||
|
||||
# Load a local YOLOv5-small model specifying source as local repository
|
||||
model = torch.hub.load('.', 'custom', 'yolov5s.pt', source='local')
|
||||
```
|
||||
|
||||
Notes:
|
||||
For more details on model loading and customization, visit
|
||||
the [YOLOv5 PyTorch Hub Documentation](https://pytorch.org/hub/ultralytics_yolov5).
|
||||
"""
|
||||
return _create("yolov5s", pretrained, channels, classes, autoshape, _verbose, device)
|
||||
|
||||
|
||||
def yolov5m(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
||||
"""
|
||||
Instantiates the YOLOv5-medium model with customizable pretraining, channel count, class count, autoshaping,
|
||||
verbosity, and device.
|
||||
|
||||
Args:
|
||||
pretrained (bool, optional): Whether to load pretrained weights into the model. Default is True.
|
||||
channels (int, optional): Number of input channels. Default is 3.
|
||||
classes (int, optional): Number of model classes. Default is 80.
|
||||
autoshape (bool, optional): Apply YOLOv5 .autoshape() wrapper to the model for handling various input formats.
|
||||
Default is True.
|
||||
_verbose (bool, optional): Whether to print detailed information to the screen. Default is True.
|
||||
device (str | torch.device | None, optional): Device specification to use for model parameters (e.g., 'cpu', 'cuda').
|
||||
Default is None.
|
||||
|
||||
Returns:
|
||||
torch.nn.Module: The instantiated YOLOv5-medium model.
|
||||
|
||||
Usage Example:
|
||||
```python
|
||||
import torch
|
||||
|
||||
model = torch.hub.load('ultralytics/yolov5', 'yolov5m') # Load YOLOv5-medium from Ultralytics repository
|
||||
model = torch.hub.load('ultralytics/yolov5:master', 'yolov5m') # Load from the master branch
|
||||
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5m.pt') # Load a custom/local YOLOv5-medium model
|
||||
model = torch.hub.load('.', 'custom', 'yolov5m.pt', source='local') # Load from a local repository
|
||||
```
|
||||
|
||||
For more information, visit https://pytorch.org/hub/ultralytics_yolov5.
|
||||
"""
|
||||
return _create("yolov5m", pretrained, channels, classes, autoshape, _verbose, device)
|
||||
|
||||
|
||||
def yolov5l(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
||||
"""
|
||||
Creates YOLOv5-large model with options for pretraining, channels, classes, autoshaping, verbosity, and device
|
||||
selection.
|
||||
|
||||
Args:
|
||||
pretrained (bool): Load pretrained weights into the model. Default is True.
|
||||
channels (int): Number of input channels. Default is 3.
|
||||
classes (int): Number of model classes. Default is 80.
|
||||
autoshape (bool): Apply YOLOv5 .autoshape() wrapper to model. Default is True.
|
||||
_verbose (bool): Print all information to screen. Default is True.
|
||||
device (str | torch.device | None): Device to use for model parameters, e.g., 'cpu', 'cuda', or a torch.device instance.
|
||||
Default is None.
|
||||
|
||||
Returns:
|
||||
YOLOv5 model (torch.nn.Module): The YOLOv5-large model instantiated with specified configurations and possibly
|
||||
pretrained weights.
|
||||
|
||||
Examples:
|
||||
```python
|
||||
import torch
|
||||
model = torch.hub.load('ultralytics/yolov5', 'yolov5l')
|
||||
```
|
||||
|
||||
Notes:
|
||||
For additional details, refer to the PyTorch Hub models documentation:
|
||||
https://pytorch.org/hub/ultralytics_yolov5
|
||||
"""
|
||||
return _create("yolov5l", pretrained, channels, classes, autoshape, _verbose, device)
|
||||
|
||||
|
||||
def yolov5x(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
||||
"""
|
||||
Perform object detection using the YOLOv5-xlarge model with options for pretraining, input channels, class count,
|
||||
autoshaping, verbosity, and device specification.
|
||||
|
||||
Args:
|
||||
pretrained (bool): If True, loads pretrained weights into the model. Defaults to True.
|
||||
channels (int): Number of input channels for the model. Defaults to 3.
|
||||
classes (int): Number of model classes for object detection. Defaults to 80.
|
||||
autoshape (bool): If True, applies the YOLOv5 .autoshape() wrapper for handling different input formats. Defaults to
|
||||
True.
|
||||
_verbose (bool): If True, prints detailed information during model loading. Defaults to True.
|
||||
device (str | torch.device | None): Device specification for computing the model, e.g., 'cpu', 'cuda:0', torch.device('cuda').
|
||||
Defaults to None.
|
||||
|
||||
Returns:
|
||||
torch.nn.Module: The YOLOv5-xlarge model loaded with the specified parameters, optionally with pretrained weights and
|
||||
autoshaping applied.
|
||||
|
||||
Example:
|
||||
```python
|
||||
import torch
|
||||
model = torch.hub.load('ultralytics/yolov5', 'yolov5x')
|
||||
```
|
||||
|
||||
For additional details, refer to the official YOLOv5 PyTorch Hub models documentation:
|
||||
https://pytorch.org/hub/ultralytics_yolov5
|
||||
"""
|
||||
return _create("yolov5x", pretrained, channels, classes, autoshape, _verbose, device)
|
||||
|
||||
|
||||
def yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
||||
"""
|
||||
Creates YOLOv5-nano-P6 model with options for pretraining, channels, classes, autoshaping, verbosity, and device.
|
||||
|
||||
Args:
|
||||
pretrained (bool, optional): If True, loads pretrained weights into the model. Default is True.
|
||||
channels (int, optional): Number of input channels. Default is 3.
|
||||
classes (int, optional): Number of model classes. Default is 80.
|
||||
autoshape (bool, optional): If True, applies the YOLOv5 .autoshape() wrapper to the model. Default is True.
|
||||
_verbose (bool, optional): If True, prints all information to screen. Default is True.
|
||||
device (str | torch.device | None, optional): Device to use for model parameters. Can be 'cpu', 'cuda', or None.
|
||||
Default is None.
|
||||
|
||||
Returns:
|
||||
torch.nn.Module: YOLOv5-nano-P6 model loaded with the specified configurations.
|
||||
|
||||
Example:
|
||||
```python
|
||||
import torch
|
||||
model = yolov5n6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device='cuda')
|
||||
```
|
||||
|
||||
Notes:
|
||||
For more information on PyTorch Hub models, visit: https://pytorch.org/hub/ultralytics_yolov5
|
||||
"""
|
||||
return _create("yolov5n6", pretrained, channels, classes, autoshape, _verbose, device)
|
||||
|
||||
|
||||
def yolov5s6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
||||
"""
|
||||
Instantiate the YOLOv5-small-P6 model with options for pretraining, input channels, number of classes, autoshaping,
|
||||
verbosity, and device selection.
|
||||
|
||||
Args:
|
||||
pretrained (bool): If True, loads pretrained weights. Default is True.
|
||||
channels (int): Number of input channels. Default is 3.
|
||||
classes (int): Number of object detection classes. Default is 80.
|
||||
autoshape (bool): If True, applies YOLOv5 .autoshape() wrapper to the model, allowing for varied input formats.
|
||||
Default is True.
|
||||
_verbose (bool): If True, prints detailed information during model loading. Default is True.
|
||||
device (str | torch.device | None): Device specification for model parameters (e.g., 'cpu', 'cuda', or torch.device).
|
||||
Default is None, which selects an available device automatically.
|
||||
|
||||
Returns:
|
||||
torch.nn.Module: The YOLOv5-small-P6 model instance.
|
||||
|
||||
Usage:
|
||||
```python
|
||||
import torch
|
||||
|
||||
model = torch.hub.load('ultralytics/yolov5', 'yolov5s6')
|
||||
model = torch.hub.load('ultralytics/yolov5:master', 'yolov5s6') # load from a specific branch
|
||||
model = torch.hub.load('ultralytics/yolov5', 'custom', 'path/to/yolov5s6.pt') # custom/local model
|
||||
model = torch.hub.load('.', 'custom', 'path/to/yolov5s6.pt', source='local') # local repo model
|
||||
```
|
||||
|
||||
Notes:
|
||||
- For more information, refer to the PyTorch Hub models documentation at https://pytorch.org/hub/ultralytics_yolov5
|
||||
|
||||
Raises:
|
||||
Exception: If there is an error during model creation or loading, with a suggestion to visit the YOLOv5
|
||||
tutorials for help.
|
||||
"""
|
||||
return _create("yolov5s6", pretrained, channels, classes, autoshape, _verbose, device)
|
||||
|
||||
|
||||
def yolov5m6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
||||
"""
|
||||
Create YOLOv5-medium-P6 model with options for pretraining, channel count, class count, autoshaping, verbosity, and
|
||||
device.
|
||||
|
||||
Args:
|
||||
pretrained (bool): If True, loads pretrained weights. Default is True.
|
||||
channels (int): Number of input channels. Default is 3.
|
||||
classes (int): Number of model classes. Default is 80.
|
||||
autoshape (bool): Apply YOLOv5 .autoshape() wrapper to the model for file/URI/PIL/cv2/np inputs and NMS.
|
||||
Default is True.
|
||||
_verbose (bool): If True, prints detailed information to the screen. Default is True.
|
||||
device (str | torch.device | None): Device to use for model parameters. Default is None, which uses the
|
||||
best available device.
|
||||
|
||||
Returns:
|
||||
torch.nn.Module: The YOLOv5-medium-P6 model.
|
||||
|
||||
Refer to the PyTorch Hub models documentation: https://pytorch.org/hub/ultralytics_yolov5 for additional details.
|
||||
|
||||
Example:
|
||||
```python
|
||||
import torch
|
||||
|
||||
# Load YOLOv5-medium-P6 model
|
||||
model = torch.hub.load('ultralytics/yolov5', 'yolov5m6')
|
||||
```
|
||||
|
||||
Notes:
|
||||
- The model can be loaded with pre-trained weights for better performance on specific tasks.
|
||||
- The autoshape feature simplifies input handling by allowing various popular data formats.
|
||||
"""
|
||||
return _create("yolov5m6", pretrained, channels, classes, autoshape, _verbose, device)
|
||||
|
||||
|
||||
def yolov5l6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
||||
"""
|
||||
Instantiate the YOLOv5-large-P6 model with options for pretraining, channel and class counts, autoshaping,
|
||||
verbosity, and device selection.
|
||||
|
||||
Args:
|
||||
pretrained (bool, optional): If True, load pretrained weights into the model. Default is True.
|
||||
channels (int, optional): Number of input channels. Default is 3.
|
||||
classes (int, optional): Number of model classes. Default is 80.
|
||||
autoshape (bool, optional): If True, apply YOLOv5 .autoshape() wrapper to the model for input flexibility. Default is True.
|
||||
_verbose (bool, optional): If True, print all information to the screen. Default is True.
|
||||
device (str | torch.device | None, optional): Device to use for model parameters, e.g., 'cpu', 'cuda', or torch.device.
|
||||
If None, automatically selects the best available device. Default is None.
|
||||
|
||||
Returns:
|
||||
torch.nn.Module: The instantiated YOLOv5-large-P6 model.
|
||||
|
||||
Example:
|
||||
```python
|
||||
import torch
|
||||
model = torch.hub.load('ultralytics/yolov5', 'yolov5l6') # official model
|
||||
model = torch.hub.load('ultralytics/yolov5:master', 'yolov5l6') # from specific branch
|
||||
model = torch.hub.load('ultralytics/yolov5', 'custom', 'path/to/yolov5l6.pt') # custom/local model
|
||||
model = torch.hub.load('.', 'custom', 'path/to/yolov5l6.pt', source='local') # local repository
|
||||
```
|
||||
|
||||
Note:
|
||||
Refer to [PyTorch Hub Documentation](https://pytorch.org/hub/ultralytics_yolov5) for additional usage instructions.
|
||||
"""
|
||||
return _create("yolov5l6", pretrained, channels, classes, autoshape, _verbose, device)
|
||||
|
||||
|
||||
def yolov5x6(pretrained=True, channels=3, classes=80, autoshape=True, _verbose=True, device=None):
|
||||
"""
|
||||
Creates the YOLOv5-xlarge-P6 model with options for pretraining, number of input channels, class count, autoshaping,
|
||||
verbosity, and device selection.
|
||||
|
||||
Args:
|
||||
pretrained (bool): If True, loads pretrained weights into the model. Default is True.
|
||||
channels (int): Number of input channels. Default is 3.
|
||||
classes (int): Number of model classes. Default is 80.
|
||||
autoshape (bool): If True, applies YOLOv5 .autoshape() wrapper to the model. Default is True.
|
||||
_verbose (bool): If True, prints all information to the screen. Default is True.
|
||||
device (str | torch.device | None): Device to use for model parameters, can be a string, torch.device object, or
|
||||
None for default device selection. Default is None.
|
||||
|
||||
Returns:
|
||||
torch.nn.Module: The instantiated YOLOv5-xlarge-P6 model.
|
||||
|
||||
Example:
|
||||
```python
|
||||
import torch
|
||||
model = torch.hub.load('ultralytics/yolov5', 'yolov5x6') # load the YOLOv5-xlarge-P6 model
|
||||
```
|
||||
|
||||
Note:
|
||||
For more information on YOLOv5 models, visit the official documentation:
|
||||
https://docs.ultralytics.com/yolov5
|
||||
"""
|
||||
return _create("yolov5x6", pretrained, channels, classes, autoshape, _verbose, device)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
from utils.general import cv2, print_args
|
||||
|
||||
# Argparser
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--model", type=str, default="yolov5s", help="model name")
|
||||
opt = parser.parse_args()
|
||||
print_args(vars(opt))
|
||||
|
||||
# Model
|
||||
model = _create(name=opt.model, pretrained=True, channels=3, classes=80, autoshape=True, verbose=True)
|
||||
# model = custom(path='path/to/model.pt') # custom
|
||||
|
||||
# Images
|
||||
imgs = [
|
||||
"data/images/zidane.jpg", # filename
|
||||
Path("data/images/zidane.jpg"), # Path
|
||||
"https://ultralytics.com/images/zidane.jpg", # URI
|
||||
cv2.imread("data/images/bus.jpg")[:, :, ::-1], # OpenCV
|
||||
Image.open("data/images/bus.jpg"), # PIL
|
||||
np.zeros((320, 640, 3)),
|
||||
] # numpy
|
||||
|
||||
# Inference
|
||||
results = model(imgs, size=320) # batched inference
|
||||
|
||||
# Results
|
||||
results.print()
|
||||
results.save()
|
1
yolov5/models/__init__.py
Normal file
1
yolov5/models/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
1111
yolov5/models/common.py
Normal file
1111
yolov5/models/common.py
Normal file
File diff suppressed because it is too large
Load Diff
130
yolov5/models/experimental.py
Normal file
130
yolov5/models/experimental.py
Normal file
@ -0,0 +1,130 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""Experimental modules."""
|
||||
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from utils.downloads import attempt_download
|
||||
|
||||
|
||||
class Sum(nn.Module):
|
||||
"""Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070."""
|
||||
|
||||
def __init__(self, n, weight=False):
|
||||
"""Initializes a module to sum outputs of layers with number of inputs `n` and optional weighting, supporting 2+
|
||||
inputs.
|
||||
"""
|
||||
super().__init__()
|
||||
self.weight = weight # apply weights boolean
|
||||
self.iter = range(n - 1) # iter object
|
||||
if weight:
|
||||
self.w = nn.Parameter(-torch.arange(1.0, n) / 2, requires_grad=True) # layer weights
|
||||
|
||||
def forward(self, x):
|
||||
"""Processes input through a customizable weighted sum of `n` inputs, optionally applying learned weights."""
|
||||
y = x[0] # no weight
|
||||
if self.weight:
|
||||
w = torch.sigmoid(self.w) * 2
|
||||
for i in self.iter:
|
||||
y = y + x[i + 1] * w[i]
|
||||
else:
|
||||
for i in self.iter:
|
||||
y = y + x[i + 1]
|
||||
return y
|
||||
|
||||
|
||||
class MixConv2d(nn.Module):
|
||||
"""Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595."""
|
||||
|
||||
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
|
||||
"""Initializes MixConv2d with mixed depth-wise convolutional layers, taking input and output channels (c1, c2),
|
||||
kernel sizes (k), stride (s), and channel distribution strategy (equal_ch).
|
||||
"""
|
||||
super().__init__()
|
||||
n = len(k) # number of convolutions
|
||||
if equal_ch: # equal c_ per group
|
||||
i = torch.linspace(0, n - 1e-6, c2).floor() # c2 indices
|
||||
c_ = [(i == g).sum() for g in range(n)] # intermediate channels
|
||||
else: # equal weight.numel() per group
|
||||
b = [c2] + [0] * n
|
||||
a = np.eye(n + 1, n, k=-1)
|
||||
a -= np.roll(a, 1, axis=1)
|
||||
a *= np.array(k) ** 2
|
||||
a[0] = 1
|
||||
c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
|
||||
|
||||
self.m = nn.ModuleList(
|
||||
[nn.Conv2d(c1, int(c_), k, s, k // 2, groups=math.gcd(c1, int(c_)), bias=False) for k, c_ in zip(k, c_)]
|
||||
)
|
||||
self.bn = nn.BatchNorm2d(c2)
|
||||
self.act = nn.SiLU()
|
||||
|
||||
def forward(self, x):
|
||||
"""Performs forward pass by applying SiLU activation on batch-normalized concatenated convolutional layer
|
||||
outputs.
|
||||
"""
|
||||
return self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
|
||||
|
||||
|
||||
class Ensemble(nn.ModuleList):
|
||||
"""Ensemble of models."""
|
||||
|
||||
def __init__(self):
|
||||
"""Initializes an ensemble of models to be used for aggregated predictions."""
|
||||
super().__init__()
|
||||
|
||||
def forward(self, x, augment=False, profile=False, visualize=False):
|
||||
"""Performs forward pass aggregating outputs from an ensemble of models.."""
|
||||
y = [module(x, augment, profile, visualize)[0] for module in self]
|
||||
# y = torch.stack(y).max(0)[0] # max ensemble
|
||||
# y = torch.stack(y).mean(0) # mean ensemble
|
||||
y = torch.cat(y, 1) # nms ensemble
|
||||
return y, None # inference, train output
|
||||
|
||||
|
||||
def attempt_load(weights, device=None, inplace=True, fuse=True):
|
||||
"""
|
||||
Loads and fuses an ensemble or single YOLOv5 model from weights, handling device placement and model adjustments.
|
||||
|
||||
Example inputs: weights=[a,b,c] or a single model weights=[a] or weights=a.
|
||||
"""
|
||||
from models.yolo import Detect, Model
|
||||
|
||||
model = Ensemble()
|
||||
for w in weights if isinstance(weights, list) else [weights]:
|
||||
ckpt = torch.load(attempt_download(w), map_location="cpu") # load
|
||||
ckpt = (ckpt.get("ema") or ckpt["model"]).to(device).float() # FP32 model
|
||||
|
||||
# Model compatibility updates
|
||||
if not hasattr(ckpt, "stride"):
|
||||
ckpt.stride = torch.tensor([32.0])
|
||||
if hasattr(ckpt, "names") and isinstance(ckpt.names, (list, tuple)):
|
||||
ckpt.names = dict(enumerate(ckpt.names)) # convert to dict
|
||||
|
||||
model.append(ckpt.fuse().eval() if fuse and hasattr(ckpt, "fuse") else ckpt.eval()) # model in eval mode
|
||||
|
||||
# Module updates
|
||||
for m in model.modules():
|
||||
t = type(m)
|
||||
if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model):
|
||||
m.inplace = inplace
|
||||
if t is Detect and not isinstance(m.anchor_grid, list):
|
||||
delattr(m, "anchor_grid")
|
||||
setattr(m, "anchor_grid", [torch.zeros(1)] * m.nl)
|
||||
elif t is nn.Upsample and not hasattr(m, "recompute_scale_factor"):
|
||||
m.recompute_scale_factor = None # torch 1.11.0 compatibility
|
||||
|
||||
# Return model
|
||||
if len(model) == 1:
|
||||
return model[-1]
|
||||
|
||||
# Return detection ensemble
|
||||
print(f"Ensemble created with {weights}\n")
|
||||
for k in "names", "nc", "yaml":
|
||||
setattr(model, k, getattr(model[0], k))
|
||||
model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
|
||||
assert all(model[0].nc == m.nc for m in model), f"Models have different class counts: {[m.nc for m in model]}"
|
||||
return model
|
57
yolov5/models/hub/anchors.yaml
Normal file
57
yolov5/models/hub/anchors.yaml
Normal file
@ -0,0 +1,57 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Default anchors for COCO data
|
||||
|
||||
# P5 -------------------------------------------------------------------------------------------------------------------
|
||||
# P5-640:
|
||||
anchors_p5_640:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# P6 -------------------------------------------------------------------------------------------------------------------
|
||||
# P6-640: thr=0.25: 0.9964 BPR, 5.54 anchors past thr, n=12, img_size=640, metric_all=0.281/0.716-mean/best, past_thr=0.469-mean: 9,11, 21,19, 17,41, 43,32, 39,70, 86,64, 65,131, 134,130, 120,265, 282,180, 247,354, 512,387
|
||||
anchors_p6_640:
|
||||
- [9, 11, 21, 19, 17, 41] # P3/8
|
||||
- [43, 32, 39, 70, 86, 64] # P4/16
|
||||
- [65, 131, 134, 130, 120, 265] # P5/32
|
||||
- [282, 180, 247, 354, 512, 387] # P6/64
|
||||
|
||||
# P6-1280: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1280, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 19,27, 44,40, 38,94, 96,68, 86,152, 180,137, 140,301, 303,264, 238,542, 436,615, 739,380, 925,792
|
||||
anchors_p6_1280:
|
||||
- [19, 27, 44, 40, 38, 94] # P3/8
|
||||
- [96, 68, 86, 152, 180, 137] # P4/16
|
||||
- [140, 301, 303, 264, 238, 542] # P5/32
|
||||
- [436, 615, 739, 380, 925, 792] # P6/64
|
||||
|
||||
# P6-1920: thr=0.25: 0.9950 BPR, 5.55 anchors past thr, n=12, img_size=1920, metric_all=0.281/0.714-mean/best, past_thr=0.468-mean: 28,41, 67,59, 57,141, 144,103, 129,227, 270,205, 209,452, 455,396, 358,812, 653,922, 1109,570, 1387,1187
|
||||
anchors_p6_1920:
|
||||
- [28, 41, 67, 59, 57, 141] # P3/8
|
||||
- [144, 103, 129, 227, 270, 205] # P4/16
|
||||
- [209, 452, 455, 396, 358, 812] # P5/32
|
||||
- [653, 922, 1109, 570, 1387, 1187] # P6/64
|
||||
|
||||
# P7 -------------------------------------------------------------------------------------------------------------------
|
||||
# P7-640: thr=0.25: 0.9962 BPR, 6.76 anchors past thr, n=15, img_size=640, metric_all=0.275/0.733-mean/best, past_thr=0.466-mean: 11,11, 13,30, 29,20, 30,46, 61,38, 39,92, 78,80, 146,66, 79,163, 149,150, 321,143, 157,303, 257,402, 359,290, 524,372
|
||||
anchors_p7_640:
|
||||
- [11, 11, 13, 30, 29, 20] # P3/8
|
||||
- [30, 46, 61, 38, 39, 92] # P4/16
|
||||
- [78, 80, 146, 66, 79, 163] # P5/32
|
||||
- [149, 150, 321, 143, 157, 303] # P6/64
|
||||
- [257, 402, 359, 290, 524, 372] # P7/128
|
||||
|
||||
# P7-1280: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1280, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 19,22, 54,36, 32,77, 70,83, 138,71, 75,173, 165,159, 148,334, 375,151, 334,317, 251,626, 499,474, 750,326, 534,814, 1079,818
|
||||
anchors_p7_1280:
|
||||
- [19, 22, 54, 36, 32, 77] # P3/8
|
||||
- [70, 83, 138, 71, 75, 173] # P4/16
|
||||
- [165, 159, 148, 334, 375, 151] # P5/32
|
||||
- [334, 317, 251, 626, 499, 474] # P6/64
|
||||
- [750, 326, 534, 814, 1079, 818] # P7/128
|
||||
|
||||
# P7-1920: thr=0.25: 0.9968 BPR, 6.71 anchors past thr, n=15, img_size=1920, metric_all=0.273/0.732-mean/best, past_thr=0.463-mean: 29,34, 81,55, 47,115, 105,124, 207,107, 113,259, 247,238, 222,500, 563,227, 501,476, 376,939, 749,711, 1126,489, 801,1222, 1618,1227
|
||||
anchors_p7_1920:
|
||||
- [29, 34, 81, 55, 47, 115] # P3/8
|
||||
- [105, 124, 207, 107, 113, 259] # P4/16
|
||||
- [247, 238, 222, 500, 563, 227] # P5/32
|
||||
- [501, 476, 376, 939, 749, 711] # P6/64
|
||||
- [1126, 489, 801, 1222, 1618, 1227] # P7/128
|
52
yolov5/models/hub/yolov3-spp.yaml
Normal file
52
yolov5/models/hub/yolov3-spp.yaml
Normal file
@ -0,0 +1,52 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# darknet53 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [32, 3, 1]], # 0
|
||||
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
||||
[-1, 1, Bottleneck, [64]],
|
||||
[-1, 1, Conv, [128, 3, 2]], # 3-P2/4
|
||||
[-1, 2, Bottleneck, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 5-P3/8
|
||||
[-1, 8, Bottleneck, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 7-P4/16
|
||||
[-1, 8, Bottleneck, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
|
||||
[-1, 4, Bottleneck, [1024]], # 10
|
||||
]
|
||||
|
||||
# YOLOv3-SPP head
|
||||
head: [
|
||||
[-1, 1, Bottleneck, [1024, False]],
|
||||
[-1, 1, SPP, [512, [5, 9, 13]]],
|
||||
[-1, 1, Conv, [1024, 3, 1]],
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
|
||||
|
||||
[-2, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 8], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 1, Bottleneck, [512, False]],
|
||||
[-1, 1, Bottleneck, [512, False]],
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
|
||||
|
||||
[-2, 1, Conv, [128, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 1, Bottleneck, [256, False]],
|
||||
[-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
|
||||
|
||||
[[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
42
yolov5/models/hub/yolov3-tiny.yaml
Normal file
42
yolov5/models/hub/yolov3-tiny.yaml
Normal file
@ -0,0 +1,42 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 14, 23, 27, 37, 58] # P4/16
|
||||
- [81, 82, 135, 169, 344, 319] # P5/32
|
||||
|
||||
# YOLOv3-tiny backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [16, 3, 1]], # 0
|
||||
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 1-P1/2
|
||||
[-1, 1, Conv, [32, 3, 1]],
|
||||
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 3-P2/4
|
||||
[-1, 1, Conv, [64, 3, 1]],
|
||||
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 5-P3/8
|
||||
[-1, 1, Conv, [128, 3, 1]],
|
||||
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 7-P4/16
|
||||
[-1, 1, Conv, [256, 3, 1]],
|
||||
[-1, 1, nn.MaxPool2d, [2, 2, 0]], # 9-P5/32
|
||||
[-1, 1, Conv, [512, 3, 1]],
|
||||
[-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]], # 11
|
||||
[-1, 1, nn.MaxPool2d, [2, 1, 0]], # 12
|
||||
]
|
||||
|
||||
# YOLOv3-tiny head
|
||||
head: [
|
||||
[-1, 1, Conv, [1024, 3, 1]],
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, Conv, [512, 3, 1]], # 15 (P5/32-large)
|
||||
|
||||
[-2, 1, Conv, [128, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 8], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 1, Conv, [256, 3, 1]], # 19 (P4/16-medium)
|
||||
|
||||
[[19, 15], 1, Detect, [nc, anchors]], # Detect(P4, P5)
|
||||
]
|
52
yolov5/models/hub/yolov3.yaml
Normal file
52
yolov5/models/hub/yolov3.yaml
Normal file
@ -0,0 +1,52 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# darknet53 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [32, 3, 1]], # 0
|
||||
[-1, 1, Conv, [64, 3, 2]], # 1-P1/2
|
||||
[-1, 1, Bottleneck, [64]],
|
||||
[-1, 1, Conv, [128, 3, 2]], # 3-P2/4
|
||||
[-1, 2, Bottleneck, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 5-P3/8
|
||||
[-1, 8, Bottleneck, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 7-P4/16
|
||||
[-1, 8, Bottleneck, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 9-P5/32
|
||||
[-1, 4, Bottleneck, [1024]], # 10
|
||||
]
|
||||
|
||||
# YOLOv3 head
|
||||
head: [
|
||||
[-1, 1, Bottleneck, [1024, False]],
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, Conv, [1024, 3, 1]],
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, Conv, [1024, 3, 1]], # 15 (P5/32-large)
|
||||
|
||||
[-2, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 8], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 1, Bottleneck, [512, False]],
|
||||
[-1, 1, Bottleneck, [512, False]],
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, Conv, [512, 3, 1]], # 22 (P4/16-medium)
|
||||
|
||||
[-2, 1, Conv, [128, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 1, Bottleneck, [256, False]],
|
||||
[-1, 2, Bottleneck, [256, False]], # 27 (P3/8-small)
|
||||
|
||||
[[27, 22, 15], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/models/hub/yolov5-bifpn.yaml
Normal file
49
yolov5/models/hub/yolov5-bifpn.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 BiFPN head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14, 6], 1, Concat, [1]], # cat P4 <--- BiFPN change
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
43
yolov5/models/hub/yolov5-fpn.yaml
Normal file
43
yolov5/models/hub/yolov5-fpn.yaml
Normal file
@ -0,0 +1,43 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 FPN head
|
||||
head: [
|
||||
[-1, 3, C3, [1024, False]], # 10 (P5/32-large)
|
||||
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 3, C3, [512, False]], # 14 (P4/16-medium)
|
||||
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 3, C3, [256, False]], # 18 (P3/8-small)
|
||||
|
||||
[[18, 14, 10], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
55
yolov5/models/hub/yolov5-p2.yaml
Normal file
55
yolov5/models/hub/yolov5-p2.yaml
Normal file
@ -0,0 +1,55 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head with (P2, P3, P4, P5) outputs
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [128, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 2], 1, Concat, [1]], # cat backbone P2
|
||||
[-1, 1, C3, [128, False]], # 21 (P2/4-xsmall)
|
||||
|
||||
[-1, 1, Conv, [128, 3, 2]],
|
||||
[[-1, 18], 1, Concat, [1]], # cat head P3
|
||||
[-1, 3, C3, [256, False]], # 24 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 27 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 30 (P5/32-large)
|
||||
|
||||
[[21, 24, 27, 30], 1, Detect, [nc, anchors]], # Detect(P2, P3, P4, P5)
|
||||
]
|
42
yolov5/models/hub/yolov5-p34.yaml
Normal file
42
yolov5/models/hub/yolov5-p34.yaml
Normal file
@ -0,0 +1,42 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.33 # model depth multiple
|
||||
width_multiple: 0.50 # layer channel multiple
|
||||
anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head with (P3, P4) outputs
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[[17, 20], 1, Detect, [nc, anchors]], # Detect(P3, P4)
|
||||
]
|
57
yolov5/models/hub/yolov5-p6.yaml
Normal file
57
yolov5/models/hub/yolov5-p6.yaml
Normal file
@ -0,0 +1,57 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [768]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 11
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head with (P3, P4, P5, P6) outputs
|
||||
head: [
|
||||
[-1, 1, Conv, [768, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
||||
[-1, 3, C3, [768, False]], # 15
|
||||
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 19
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 20], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 16], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
||||
|
||||
[-1, 1, Conv, [768, 3, 2]],
|
||||
[[-1, 12], 1, Concat, [1]], # cat head P6
|
||||
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
||||
|
||||
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
||||
]
|
68
yolov5/models/hub/yolov5-p7.yaml
Normal file
68
yolov5/models/hub/yolov5-p7.yaml
Normal file
@ -0,0 +1,68 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors: 3 # AutoAnchor evolves 3 anchors per P output layer
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [768]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, Conv, [1280, 3, 2]], # 11-P7/128
|
||||
[-1, 3, C3, [1280]],
|
||||
[-1, 1, SPPF, [1280, 5]], # 13
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head with (P3, P4, P5, P6, P7) outputs
|
||||
head: [
|
||||
[-1, 1, Conv, [1024, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat backbone P6
|
||||
[-1, 3, C3, [1024, False]], # 17
|
||||
|
||||
[-1, 1, Conv, [768, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
||||
[-1, 3, C3, [768, False]], # 21
|
||||
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 25
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 29 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 26], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 32 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 22], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [768, False]], # 35 (P5/32-large)
|
||||
|
||||
[-1, 1, Conv, [768, 3, 2]],
|
||||
[[-1, 18], 1, Concat, [1]], # cat head P6
|
||||
[-1, 3, C3, [1024, False]], # 38 (P6/64-xlarge)
|
||||
|
||||
[-1, 1, Conv, [1024, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P7
|
||||
[-1, 3, C3, [1280, False]], # 41 (P7/128-xxlarge)
|
||||
|
||||
[[29, 32, 35, 38, 41], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6, P7)
|
||||
]
|
49
yolov5/models/hub/yolov5-panet.yaml
Normal file
49
yolov5/models/hub/yolov5-panet.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 PANet head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
61
yolov5/models/hub/yolov5l6.yaml
Normal file
61
yolov5/models/hub/yolov5l6.yaml
Normal file
@ -0,0 +1,61 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors:
|
||||
- [19, 27, 44, 40, 38, 94] # P3/8
|
||||
- [96, 68, 86, 152, 180, 137] # P4/16
|
||||
- [140, 301, 303, 264, 238, 542] # P5/32
|
||||
- [436, 615, 739, 380, 925, 792] # P6/64
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [768]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 11
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [768, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
||||
[-1, 3, C3, [768, False]], # 15
|
||||
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 19
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 20], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 16], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
||||
|
||||
[-1, 1, Conv, [768, 3, 2]],
|
||||
[[-1, 12], 1, Concat, [1]], # cat head P6
|
||||
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
||||
|
||||
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
||||
]
|
61
yolov5/models/hub/yolov5m6.yaml
Normal file
61
yolov5/models/hub/yolov5m6.yaml
Normal file
@ -0,0 +1,61 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.67 # model depth multiple
|
||||
width_multiple: 0.75 # layer channel multiple
|
||||
anchors:
|
||||
- [19, 27, 44, 40, 38, 94] # P3/8
|
||||
- [96, 68, 86, 152, 180, 137] # P4/16
|
||||
- [140, 301, 303, 264, 238, 542] # P5/32
|
||||
- [436, 615, 739, 380, 925, 792] # P6/64
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [768]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 11
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [768, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
||||
[-1, 3, C3, [768, False]], # 15
|
||||
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 19
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 20], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 16], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
||||
|
||||
[-1, 1, Conv, [768, 3, 2]],
|
||||
[[-1, 12], 1, Concat, [1]], # cat head P6
|
||||
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
||||
|
||||
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
||||
]
|
61
yolov5/models/hub/yolov5n6.yaml
Normal file
61
yolov5/models/hub/yolov5n6.yaml
Normal file
@ -0,0 +1,61 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.33 # model depth multiple
|
||||
width_multiple: 0.25 # layer channel multiple
|
||||
anchors:
|
||||
- [19, 27, 44, 40, 38, 94] # P3/8
|
||||
- [96, 68, 86, 152, 180, 137] # P4/16
|
||||
- [140, 301, 303, 264, 238, 542] # P5/32
|
||||
- [436, 615, 739, 380, 925, 792] # P6/64
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [768]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 11
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [768, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
||||
[-1, 3, C3, [768, False]], # 15
|
||||
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 19
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 20], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 16], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
||||
|
||||
[-1, 1, Conv, [768, 3, 2]],
|
||||
[[-1, 12], 1, Concat, [1]], # cat head P6
|
||||
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
||||
|
||||
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
||||
]
|
50
yolov5/models/hub/yolov5s-LeakyReLU.yaml
Normal file
50
yolov5/models/hub/yolov5s-LeakyReLU.yaml
Normal file
@ -0,0 +1,50 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
activation: nn.LeakyReLU(0.1) # <----- Conv() activation used throughout entire YOLOv5 model
|
||||
depth_multiple: 0.33 # model depth multiple
|
||||
width_multiple: 0.50 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/models/hub/yolov5s-ghost.yaml
Normal file
49
yolov5/models/hub/yolov5s-ghost.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.33 # model depth multiple
|
||||
width_multiple: 0.50 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, GhostConv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3Ghost, [128]],
|
||||
[-1, 1, GhostConv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3Ghost, [256]],
|
||||
[-1, 1, GhostConv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3Ghost, [512]],
|
||||
[-1, 1, GhostConv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3Ghost, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, GhostConv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3Ghost, [512, False]], # 13
|
||||
|
||||
[-1, 1, GhostConv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3Ghost, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, GhostConv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3Ghost, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, GhostConv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3Ghost, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/models/hub/yolov5s-transformer.yaml
Normal file
49
yolov5/models/hub/yolov5s-transformer.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.33 # model depth multiple
|
||||
width_multiple: 0.50 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3TR, [1024]], # 9 <--- C3TR() Transformer module
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
61
yolov5/models/hub/yolov5s6.yaml
Normal file
61
yolov5/models/hub/yolov5s6.yaml
Normal file
@ -0,0 +1,61 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.33 # model depth multiple
|
||||
width_multiple: 0.50 # layer channel multiple
|
||||
anchors:
|
||||
- [19, 27, 44, 40, 38, 94] # P3/8
|
||||
- [96, 68, 86, 152, 180, 137] # P4/16
|
||||
- [140, 301, 303, 264, 238, 542] # P5/32
|
||||
- [436, 615, 739, 380, 925, 792] # P6/64
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [768]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 11
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [768, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
||||
[-1, 3, C3, [768, False]], # 15
|
||||
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 19
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 20], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 16], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
||||
|
||||
[-1, 1, Conv, [768, 3, 2]],
|
||||
[[-1, 12], 1, Concat, [1]], # cat head P6
|
||||
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
||||
|
||||
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
||||
]
|
61
yolov5/models/hub/yolov5x6.yaml
Normal file
61
yolov5/models/hub/yolov5x6.yaml
Normal file
@ -0,0 +1,61 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.33 # model depth multiple
|
||||
width_multiple: 1.25 # layer channel multiple
|
||||
anchors:
|
||||
- [19, 27, 44, 40, 38, 94] # P3/8
|
||||
- [96, 68, 86, 152, 180, 137] # P4/16
|
||||
- [140, 301, 303, 264, 238, 542] # P5/32
|
||||
- [436, 615, 739, 380, 925, 792] # P6/64
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [768, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [768]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 11
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [768, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 8], 1, Concat, [1]], # cat backbone P5
|
||||
[-1, 3, C3, [768, False]], # 15
|
||||
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 19
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 23 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 20], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 26 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 16], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [768, False]], # 29 (P5/32-large)
|
||||
|
||||
[-1, 1, Conv, [768, 3, 2]],
|
||||
[[-1, 12], 1, Concat, [1]], # cat head P6
|
||||
[-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
|
||||
|
||||
[[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
|
||||
]
|
49
yolov5/models/segment/yolov5l-seg.yaml
Normal file
49
yolov5/models/segment/yolov5l-seg.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Segment, [nc, anchors, 32, 256]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/models/segment/yolov5m-seg.yaml
Normal file
49
yolov5/models/segment/yolov5m-seg.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.67 # model depth multiple
|
||||
width_multiple: 0.75 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Segment, [nc, anchors, 32, 256]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/models/segment/yolov5n-seg.yaml
Normal file
49
yolov5/models/segment/yolov5n-seg.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.33 # model depth multiple
|
||||
width_multiple: 0.25 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Segment, [nc, anchors, 32, 256]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/models/segment/yolov5s-seg.yaml
Normal file
49
yolov5/models/segment/yolov5s-seg.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.33 # model depth multiple
|
||||
width_multiple: 0.5 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Segment, [nc, anchors, 32, 256]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/models/segment/yolov5x-seg.yaml
Normal file
49
yolov5/models/segment/yolov5x-seg.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.33 # model depth multiple
|
||||
width_multiple: 1.25 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Segment, [nc, anchors, 32, 256]], # Detect(P3, P4, P5)
|
||||
]
|
797
yolov5/models/tf.py
Normal file
797
yolov5/models/tf.py
Normal file
@ -0,0 +1,797 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""
|
||||
TensorFlow, Keras and TFLite versions of YOLOv5
|
||||
Authored by https://github.com/zldrobit in PR https://github.com/ultralytics/yolov5/pull/1127.
|
||||
|
||||
Usage:
|
||||
$ python models/tf.py --weights yolov5s.pt
|
||||
|
||||
Export:
|
||||
$ python export.py --weights yolov5s.pt --include saved_model pb tflite tfjs
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
|
||||
FILE = Path(__file__).resolve()
|
||||
ROOT = FILE.parents[1] # YOLOv5 root directory
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.append(str(ROOT)) # add ROOT to PATH
|
||||
# ROOT = ROOT.relative_to(Path.cwd()) # relative
|
||||
|
||||
import numpy as np
|
||||
import tensorflow as tf
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from tensorflow import keras
|
||||
|
||||
from models.common import (
|
||||
C3,
|
||||
SPP,
|
||||
SPPF,
|
||||
Bottleneck,
|
||||
BottleneckCSP,
|
||||
C3x,
|
||||
Concat,
|
||||
Conv,
|
||||
CrossConv,
|
||||
DWConv,
|
||||
DWConvTranspose2d,
|
||||
Focus,
|
||||
autopad,
|
||||
)
|
||||
from models.experimental import MixConv2d, attempt_load
|
||||
from models.yolo import Detect, Segment
|
||||
from utils.activations import SiLU
|
||||
from utils.general import LOGGER, make_divisible, print_args
|
||||
|
||||
|
||||
class TFBN(keras.layers.Layer):
|
||||
"""TensorFlow BatchNormalization wrapper for initializing with optional pretrained weights."""
|
||||
|
||||
def __init__(self, w=None):
|
||||
"""Initializes a TensorFlow BatchNormalization layer with optional pretrained weights."""
|
||||
super().__init__()
|
||||
self.bn = keras.layers.BatchNormalization(
|
||||
beta_initializer=keras.initializers.Constant(w.bias.numpy()),
|
||||
gamma_initializer=keras.initializers.Constant(w.weight.numpy()),
|
||||
moving_mean_initializer=keras.initializers.Constant(w.running_mean.numpy()),
|
||||
moving_variance_initializer=keras.initializers.Constant(w.running_var.numpy()),
|
||||
epsilon=w.eps,
|
||||
)
|
||||
|
||||
def call(self, inputs):
|
||||
"""Applies batch normalization to the inputs."""
|
||||
return self.bn(inputs)
|
||||
|
||||
|
||||
class TFPad(keras.layers.Layer):
|
||||
"""Pads input tensors in spatial dimensions 1 and 2 with specified integer or tuple padding values."""
|
||||
|
||||
def __init__(self, pad):
|
||||
"""
|
||||
Initializes a padding layer for spatial dimensions 1 and 2 with specified padding, supporting both int and tuple
|
||||
inputs.
|
||||
|
||||
Inputs are
|
||||
"""
|
||||
super().__init__()
|
||||
if isinstance(pad, int):
|
||||
self.pad = tf.constant([[0, 0], [pad, pad], [pad, pad], [0, 0]])
|
||||
else: # tuple/list
|
||||
self.pad = tf.constant([[0, 0], [pad[0], pad[0]], [pad[1], pad[1]], [0, 0]])
|
||||
|
||||
def call(self, inputs):
|
||||
"""Pads input tensor with zeros using specified padding, suitable for int and tuple pad dimensions."""
|
||||
return tf.pad(inputs, self.pad, mode="constant", constant_values=0)
|
||||
|
||||
|
||||
class TFConv(keras.layers.Layer):
|
||||
"""Implements a standard convolutional layer with optional batch normalization and activation for TensorFlow."""
|
||||
|
||||
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
|
||||
"""
|
||||
Initializes a standard convolution layer with optional batch normalization and activation; supports only
|
||||
group=1.
|
||||
|
||||
Inputs are ch_in, ch_out, weights, kernel, stride, padding, groups.
|
||||
"""
|
||||
super().__init__()
|
||||
assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
|
||||
# TensorFlow convolution padding is inconsistent with PyTorch (e.g. k=3 s=2 'SAME' padding)
|
||||
# see https://stackoverflow.com/questions/52975843/comparing-conv2d-with-padding-between-tensorflow-and-pytorch
|
||||
conv = keras.layers.Conv2D(
|
||||
filters=c2,
|
||||
kernel_size=k,
|
||||
strides=s,
|
||||
padding="SAME" if s == 1 else "VALID",
|
||||
use_bias=not hasattr(w, "bn"),
|
||||
kernel_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
|
||||
bias_initializer="zeros" if hasattr(w, "bn") else keras.initializers.Constant(w.conv.bias.numpy()),
|
||||
)
|
||||
self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
|
||||
self.bn = TFBN(w.bn) if hasattr(w, "bn") else tf.identity
|
||||
self.act = activations(w.act) if act else tf.identity
|
||||
|
||||
def call(self, inputs):
|
||||
"""Applies convolution, batch normalization, and activation function to input tensors."""
|
||||
return self.act(self.bn(self.conv(inputs)))
|
||||
|
||||
|
||||
class TFDWConv(keras.layers.Layer):
|
||||
"""Initializes a depthwise convolution layer with optional batch normalization and activation for TensorFlow."""
|
||||
|
||||
def __init__(self, c1, c2, k=1, s=1, p=None, act=True, w=None):
|
||||
"""
|
||||
Initializes a depthwise convolution layer with optional batch normalization and activation for TensorFlow
|
||||
models.
|
||||
|
||||
Input are ch_in, ch_out, weights, kernel, stride, padding, groups.
|
||||
"""
|
||||
super().__init__()
|
||||
assert c2 % c1 == 0, f"TFDWConv() output={c2} must be a multiple of input={c1} channels"
|
||||
conv = keras.layers.DepthwiseConv2D(
|
||||
kernel_size=k,
|
||||
depth_multiplier=c2 // c1,
|
||||
strides=s,
|
||||
padding="SAME" if s == 1 else "VALID",
|
||||
use_bias=not hasattr(w, "bn"),
|
||||
depthwise_initializer=keras.initializers.Constant(w.conv.weight.permute(2, 3, 1, 0).numpy()),
|
||||
bias_initializer="zeros" if hasattr(w, "bn") else keras.initializers.Constant(w.conv.bias.numpy()),
|
||||
)
|
||||
self.conv = conv if s == 1 else keras.Sequential([TFPad(autopad(k, p)), conv])
|
||||
self.bn = TFBN(w.bn) if hasattr(w, "bn") else tf.identity
|
||||
self.act = activations(w.act) if act else tf.identity
|
||||
|
||||
def call(self, inputs):
|
||||
"""Applies convolution, batch normalization, and activation function to input tensors."""
|
||||
return self.act(self.bn(self.conv(inputs)))
|
||||
|
||||
|
||||
class TFDWConvTranspose2d(keras.layers.Layer):
|
||||
"""Implements a depthwise ConvTranspose2D layer for TensorFlow with specific settings."""
|
||||
|
||||
def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0, w=None):
|
||||
"""
|
||||
Initializes depthwise ConvTranspose2D layer with specific channel, kernel, stride, and padding settings.
|
||||
|
||||
Inputs are ch_in, ch_out, weights, kernel, stride, padding, groups.
|
||||
"""
|
||||
super().__init__()
|
||||
assert c1 == c2, f"TFDWConv() output={c2} must be equal to input={c1} channels"
|
||||
assert k == 4 and p1 == 1, "TFDWConv() only valid for k=4 and p1=1"
|
||||
weight, bias = w.weight.permute(2, 3, 1, 0).numpy(), w.bias.numpy()
|
||||
self.c1 = c1
|
||||
self.conv = [
|
||||
keras.layers.Conv2DTranspose(
|
||||
filters=1,
|
||||
kernel_size=k,
|
||||
strides=s,
|
||||
padding="VALID",
|
||||
output_padding=p2,
|
||||
use_bias=True,
|
||||
kernel_initializer=keras.initializers.Constant(weight[..., i : i + 1]),
|
||||
bias_initializer=keras.initializers.Constant(bias[i]),
|
||||
)
|
||||
for i in range(c1)
|
||||
]
|
||||
|
||||
def call(self, inputs):
|
||||
"""Processes input through parallel convolutions and concatenates results, trimming border pixels."""
|
||||
return tf.concat([m(x) for m, x in zip(self.conv, tf.split(inputs, self.c1, 3))], 3)[:, 1:-1, 1:-1]
|
||||
|
||||
|
||||
class TFFocus(keras.layers.Layer):
|
||||
"""Focuses spatial information into channel space using pixel shuffling and convolution for TensorFlow models."""
|
||||
|
||||
def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True, w=None):
|
||||
"""
|
||||
Initializes TFFocus layer to focus width and height information into channel space with custom convolution
|
||||
parameters.
|
||||
|
||||
Inputs are ch_in, ch_out, kernel, stride, padding, groups.
|
||||
"""
|
||||
super().__init__()
|
||||
self.conv = TFConv(c1 * 4, c2, k, s, p, g, act, w.conv)
|
||||
|
||||
def call(self, inputs):
|
||||
"""
|
||||
Performs pixel shuffling and convolution on input tensor, downsampling by 2 and expanding channels by 4.
|
||||
|
||||
Example x(b,w,h,c) -> y(b,w/2,h/2,4c).
|
||||
"""
|
||||
inputs = [inputs[:, ::2, ::2, :], inputs[:, 1::2, ::2, :], inputs[:, ::2, 1::2, :], inputs[:, 1::2, 1::2, :]]
|
||||
return self.conv(tf.concat(inputs, 3))
|
||||
|
||||
|
||||
class TFBottleneck(keras.layers.Layer):
|
||||
"""Implements a TensorFlow bottleneck layer with optional shortcut connections for efficient feature extraction."""
|
||||
|
||||
def __init__(self, c1, c2, shortcut=True, g=1, e=0.5, w=None):
|
||||
"""
|
||||
Initializes a standard bottleneck layer for TensorFlow models, expanding and contracting channels with optional
|
||||
shortcut.
|
||||
|
||||
Arguments are ch_in, ch_out, shortcut, groups, expansion.
|
||||
"""
|
||||
super().__init__()
|
||||
c_ = int(c2 * e) # hidden channels
|
||||
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
||||
self.cv2 = TFConv(c_, c2, 3, 1, g=g, w=w.cv2)
|
||||
self.add = shortcut and c1 == c2
|
||||
|
||||
def call(self, inputs):
|
||||
"""Performs forward pass; if shortcut is True & input/output channels match, adds input to the convolution
|
||||
result.
|
||||
"""
|
||||
return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
|
||||
|
||||
|
||||
class TFCrossConv(keras.layers.Layer):
|
||||
"""Implements a cross convolutional layer with optional expansion, grouping, and shortcut for TensorFlow."""
|
||||
|
||||
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False, w=None):
|
||||
"""Initializes cross convolution layer with optional expansion, grouping, and shortcut addition capabilities."""
|
||||
super().__init__()
|
||||
c_ = int(c2 * e) # hidden channels
|
||||
self.cv1 = TFConv(c1, c_, (1, k), (1, s), w=w.cv1)
|
||||
self.cv2 = TFConv(c_, c2, (k, 1), (s, 1), g=g, w=w.cv2)
|
||||
self.add = shortcut and c1 == c2
|
||||
|
||||
def call(self, inputs):
|
||||
"""Passes input through two convolutions optionally adding the input if channel dimensions match."""
|
||||
return inputs + self.cv2(self.cv1(inputs)) if self.add else self.cv2(self.cv1(inputs))
|
||||
|
||||
|
||||
class TFConv2d(keras.layers.Layer):
|
||||
"""Implements a TensorFlow 2D convolution layer, mimicking PyTorch's nn.Conv2D for specified filters and stride."""
|
||||
|
||||
def __init__(self, c1, c2, k, s=1, g=1, bias=True, w=None):
|
||||
"""Initializes a TensorFlow 2D convolution layer, mimicking PyTorch's nn.Conv2D functionality for given filter
|
||||
sizes and stride.
|
||||
"""
|
||||
super().__init__()
|
||||
assert g == 1, "TF v2.2 Conv2D does not support 'groups' argument"
|
||||
self.conv = keras.layers.Conv2D(
|
||||
filters=c2,
|
||||
kernel_size=k,
|
||||
strides=s,
|
||||
padding="VALID",
|
||||
use_bias=bias,
|
||||
kernel_initializer=keras.initializers.Constant(w.weight.permute(2, 3, 1, 0).numpy()),
|
||||
bias_initializer=keras.initializers.Constant(w.bias.numpy()) if bias else None,
|
||||
)
|
||||
|
||||
def call(self, inputs):
|
||||
"""Applies a convolution operation to the inputs and returns the result."""
|
||||
return self.conv(inputs)
|
||||
|
||||
|
||||
class TFBottleneckCSP(keras.layers.Layer):
|
||||
"""Implements a CSP bottleneck layer for TensorFlow models to enhance gradient flow and efficiency."""
|
||||
|
||||
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
|
||||
"""
|
||||
Initializes CSP bottleneck layer with specified channel sizes, count, shortcut option, groups, and expansion
|
||||
ratio.
|
||||
|
||||
Inputs are ch_in, ch_out, number, shortcut, groups, expansion.
|
||||
"""
|
||||
super().__init__()
|
||||
c_ = int(c2 * e) # hidden channels
|
||||
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
||||
self.cv2 = TFConv2d(c1, c_, 1, 1, bias=False, w=w.cv2)
|
||||
self.cv3 = TFConv2d(c_, c_, 1, 1, bias=False, w=w.cv3)
|
||||
self.cv4 = TFConv(2 * c_, c2, 1, 1, w=w.cv4)
|
||||
self.bn = TFBN(w.bn)
|
||||
self.act = lambda x: keras.activations.swish(x)
|
||||
self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
|
||||
|
||||
def call(self, inputs):
|
||||
"""Processes input through the model layers, concatenates, normalizes, activates, and reduces the output
|
||||
dimensions.
|
||||
"""
|
||||
y1 = self.cv3(self.m(self.cv1(inputs)))
|
||||
y2 = self.cv2(inputs)
|
||||
return self.cv4(self.act(self.bn(tf.concat((y1, y2), axis=3))))
|
||||
|
||||
|
||||
class TFC3(keras.layers.Layer):
|
||||
"""CSP bottleneck layer with 3 convolutions for TensorFlow, supporting optional shortcuts and group convolutions."""
|
||||
|
||||
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
|
||||
"""
|
||||
Initializes CSP Bottleneck with 3 convolutions, supporting optional shortcuts and group convolutions.
|
||||
|
||||
Inputs are ch_in, ch_out, number, shortcut, groups, expansion.
|
||||
"""
|
||||
super().__init__()
|
||||
c_ = int(c2 * e) # hidden channels
|
||||
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
||||
self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
|
||||
self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
|
||||
self.m = keras.Sequential([TFBottleneck(c_, c_, shortcut, g, e=1.0, w=w.m[j]) for j in range(n)])
|
||||
|
||||
def call(self, inputs):
|
||||
"""
|
||||
Processes input through a sequence of transformations for object detection (YOLOv5).
|
||||
|
||||
See https://github.com/ultralytics/yolov5.
|
||||
"""
|
||||
return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
|
||||
|
||||
|
||||
class TFC3x(keras.layers.Layer):
|
||||
"""A TensorFlow layer for enhanced feature extraction using cross-convolutions in object detection models."""
|
||||
|
||||
def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5, w=None):
|
||||
"""
|
||||
Initializes layer with cross-convolutions for enhanced feature extraction in object detection models.
|
||||
|
||||
Inputs are ch_in, ch_out, number, shortcut, groups, expansion.
|
||||
"""
|
||||
super().__init__()
|
||||
c_ = int(c2 * e) # hidden channels
|
||||
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
||||
self.cv2 = TFConv(c1, c_, 1, 1, w=w.cv2)
|
||||
self.cv3 = TFConv(2 * c_, c2, 1, 1, w=w.cv3)
|
||||
self.m = keras.Sequential(
|
||||
[TFCrossConv(c_, c_, k=3, s=1, g=g, e=1.0, shortcut=shortcut, w=w.m[j]) for j in range(n)]
|
||||
)
|
||||
|
||||
def call(self, inputs):
|
||||
"""Processes input through cascaded convolutions and merges features, returning the final tensor output."""
|
||||
return self.cv3(tf.concat((self.m(self.cv1(inputs)), self.cv2(inputs)), axis=3))
|
||||
|
||||
|
||||
class TFSPP(keras.layers.Layer):
|
||||
"""Implements spatial pyramid pooling for YOLOv3-SPP with specific channels and kernel sizes."""
|
||||
|
||||
def __init__(self, c1, c2, k=(5, 9, 13), w=None):
|
||||
"""Initializes a YOLOv3-SPP layer with specific input/output channels and kernel sizes for pooling."""
|
||||
super().__init__()
|
||||
c_ = c1 // 2 # hidden channels
|
||||
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
||||
self.cv2 = TFConv(c_ * (len(k) + 1), c2, 1, 1, w=w.cv2)
|
||||
self.m = [keras.layers.MaxPool2D(pool_size=x, strides=1, padding="SAME") for x in k]
|
||||
|
||||
def call(self, inputs):
|
||||
"""Processes input through two TFConv layers and concatenates with max-pooled outputs at intermediate stage."""
|
||||
x = self.cv1(inputs)
|
||||
return self.cv2(tf.concat([x] + [m(x) for m in self.m], 3))
|
||||
|
||||
|
||||
class TFSPPF(keras.layers.Layer):
|
||||
"""Implements a fast spatial pyramid pooling layer for TensorFlow with optimized feature extraction."""
|
||||
|
||||
def __init__(self, c1, c2, k=5, w=None):
|
||||
"""Initializes a fast spatial pyramid pooling layer with customizable in/out channels, kernel size, and
|
||||
weights.
|
||||
"""
|
||||
super().__init__()
|
||||
c_ = c1 // 2 # hidden channels
|
||||
self.cv1 = TFConv(c1, c_, 1, 1, w=w.cv1)
|
||||
self.cv2 = TFConv(c_ * 4, c2, 1, 1, w=w.cv2)
|
||||
self.m = keras.layers.MaxPool2D(pool_size=k, strides=1, padding="SAME")
|
||||
|
||||
def call(self, inputs):
|
||||
"""Executes the model's forward pass, concatenating input features with three max-pooled versions before final
|
||||
convolution.
|
||||
"""
|
||||
x = self.cv1(inputs)
|
||||
y1 = self.m(x)
|
||||
y2 = self.m(y1)
|
||||
return self.cv2(tf.concat([x, y1, y2, self.m(y2)], 3))
|
||||
|
||||
|
||||
class TFDetect(keras.layers.Layer):
|
||||
"""Implements YOLOv5 object detection layer in TensorFlow for predicting bounding boxes and class probabilities."""
|
||||
|
||||
def __init__(self, nc=80, anchors=(), ch=(), imgsz=(640, 640), w=None):
|
||||
"""Initializes YOLOv5 detection layer for TensorFlow with configurable classes, anchors, channels, and image
|
||||
size.
|
||||
"""
|
||||
super().__init__()
|
||||
self.stride = tf.convert_to_tensor(w.stride.numpy(), dtype=tf.float32)
|
||||
self.nc = nc # number of classes
|
||||
self.no = nc + 5 # number of outputs per anchor
|
||||
self.nl = len(anchors) # number of detection layers
|
||||
self.na = len(anchors[0]) // 2 # number of anchors
|
||||
self.grid = [tf.zeros(1)] * self.nl # init grid
|
||||
self.anchors = tf.convert_to_tensor(w.anchors.numpy(), dtype=tf.float32)
|
||||
self.anchor_grid = tf.reshape(self.anchors * tf.reshape(self.stride, [self.nl, 1, 1]), [self.nl, 1, -1, 1, 2])
|
||||
self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)]
|
||||
self.training = False # set to False after building model
|
||||
self.imgsz = imgsz
|
||||
for i in range(self.nl):
|
||||
ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
|
||||
self.grid[i] = self._make_grid(nx, ny)
|
||||
|
||||
def call(self, inputs):
|
||||
"""Performs forward pass through the model layers to predict object bounding boxes and classifications."""
|
||||
z = [] # inference output
|
||||
x = []
|
||||
for i in range(self.nl):
|
||||
x.append(self.m[i](inputs[i]))
|
||||
# x(bs,20,20,255) to x(bs,3,20,20,85)
|
||||
ny, nx = self.imgsz[0] // self.stride[i], self.imgsz[1] // self.stride[i]
|
||||
x[i] = tf.reshape(x[i], [-1, ny * nx, self.na, self.no])
|
||||
|
||||
if not self.training: # inference
|
||||
y = x[i]
|
||||
grid = tf.transpose(self.grid[i], [0, 2, 1, 3]) - 0.5
|
||||
anchor_grid = tf.transpose(self.anchor_grid[i], [0, 2, 1, 3]) * 4
|
||||
xy = (tf.sigmoid(y[..., 0:2]) * 2 + grid) * self.stride[i] # xy
|
||||
wh = tf.sigmoid(y[..., 2:4]) ** 2 * anchor_grid
|
||||
# Normalize xywh to 0-1 to reduce calibration error
|
||||
xy /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
|
||||
wh /= tf.constant([[self.imgsz[1], self.imgsz[0]]], dtype=tf.float32)
|
||||
y = tf.concat([xy, wh, tf.sigmoid(y[..., 4 : 5 + self.nc]), y[..., 5 + self.nc :]], -1)
|
||||
z.append(tf.reshape(y, [-1, self.na * ny * nx, self.no]))
|
||||
|
||||
return tf.transpose(x, [0, 2, 1, 3]) if self.training else (tf.concat(z, 1),)
|
||||
|
||||
@staticmethod
|
||||
def _make_grid(nx=20, ny=20):
|
||||
"""Generates a 2D grid of coordinates in (x, y) format with shape [1, 1, ny*nx, 2]."""
|
||||
# return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
|
||||
xv, yv = tf.meshgrid(tf.range(nx), tf.range(ny))
|
||||
return tf.cast(tf.reshape(tf.stack([xv, yv], 2), [1, 1, ny * nx, 2]), dtype=tf.float32)
|
||||
|
||||
|
||||
class TFSegment(TFDetect):
|
||||
"""YOLOv5 segmentation head for TensorFlow, combining detection and segmentation."""
|
||||
|
||||
def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), imgsz=(640, 640), w=None):
|
||||
"""Initializes YOLOv5 Segment head with specified channel depths, anchors, and input size for segmentation
|
||||
models.
|
||||
"""
|
||||
super().__init__(nc, anchors, ch, imgsz, w)
|
||||
self.nm = nm # number of masks
|
||||
self.npr = npr # number of protos
|
||||
self.no = 5 + nc + self.nm # number of outputs per anchor
|
||||
self.m = [TFConv2d(x, self.no * self.na, 1, w=w.m[i]) for i, x in enumerate(ch)] # output conv
|
||||
self.proto = TFProto(ch[0], self.npr, self.nm, w=w.proto) # protos
|
||||
self.detect = TFDetect.call
|
||||
|
||||
def call(self, x):
|
||||
"""Applies detection and proto layers on input, returning detections and optionally protos if training."""
|
||||
p = self.proto(x[0])
|
||||
# p = TFUpsample(None, scale_factor=4, mode='nearest')(self.proto(x[0])) # (optional) full-size protos
|
||||
p = tf.transpose(p, [0, 3, 1, 2]) # from shape(1,160,160,32) to shape(1,32,160,160)
|
||||
x = self.detect(self, x)
|
||||
return (x, p) if self.training else (x[0], p)
|
||||
|
||||
|
||||
class TFProto(keras.layers.Layer):
|
||||
"""Implements convolutional and upsampling layers for feature extraction in YOLOv5 segmentation."""
|
||||
|
||||
def __init__(self, c1, c_=256, c2=32, w=None):
|
||||
"""Initializes TFProto layer with convolutional and upsampling layers for feature extraction and
|
||||
transformation.
|
||||
"""
|
||||
super().__init__()
|
||||
self.cv1 = TFConv(c1, c_, k=3, w=w.cv1)
|
||||
self.upsample = TFUpsample(None, scale_factor=2, mode="nearest")
|
||||
self.cv2 = TFConv(c_, c_, k=3, w=w.cv2)
|
||||
self.cv3 = TFConv(c_, c2, w=w.cv3)
|
||||
|
||||
def call(self, inputs):
|
||||
"""Performs forward pass through the model, applying convolutions and upscaling on input tensor."""
|
||||
return self.cv3(self.cv2(self.upsample(self.cv1(inputs))))
|
||||
|
||||
|
||||
class TFUpsample(keras.layers.Layer):
|
||||
"""Implements a TensorFlow upsampling layer with specified size, scale factor, and interpolation mode."""
|
||||
|
||||
def __init__(self, size, scale_factor, mode, w=None):
|
||||
"""
|
||||
Initializes a TensorFlow upsampling layer with specified size, scale_factor, and mode, ensuring scale_factor is
|
||||
even.
|
||||
|
||||
Warning: all arguments needed including 'w'
|
||||
"""
|
||||
super().__init__()
|
||||
assert scale_factor % 2 == 0, "scale_factor must be multiple of 2"
|
||||
self.upsample = lambda x: tf.image.resize(x, (x.shape[1] * scale_factor, x.shape[2] * scale_factor), mode)
|
||||
# self.upsample = keras.layers.UpSampling2D(size=scale_factor, interpolation=mode)
|
||||
# with default arguments: align_corners=False, half_pixel_centers=False
|
||||
# self.upsample = lambda x: tf.raw_ops.ResizeNearestNeighbor(images=x,
|
||||
# size=(x.shape[1] * 2, x.shape[2] * 2))
|
||||
|
||||
def call(self, inputs):
|
||||
"""Applies upsample operation to inputs using nearest neighbor interpolation."""
|
||||
return self.upsample(inputs)
|
||||
|
||||
|
||||
class TFConcat(keras.layers.Layer):
|
||||
"""Implements TensorFlow's version of torch.concat() for concatenating tensors along the last dimension."""
|
||||
|
||||
def __init__(self, dimension=1, w=None):
|
||||
"""Initializes a TensorFlow layer for NCHW to NHWC concatenation, requiring dimension=1."""
|
||||
super().__init__()
|
||||
assert dimension == 1, "convert only NCHW to NHWC concat"
|
||||
self.d = 3
|
||||
|
||||
def call(self, inputs):
|
||||
"""Concatenates a list of tensors along the last dimension, used for NCHW to NHWC conversion."""
|
||||
return tf.concat(inputs, self.d)
|
||||
|
||||
|
||||
def parse_model(d, ch, model, imgsz):
|
||||
"""Parses a model definition dict `d` to create YOLOv5 model layers, including dynamic channel adjustments."""
|
||||
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
|
||||
anchors, nc, gd, gw, ch_mul = (
|
||||
d["anchors"],
|
||||
d["nc"],
|
||||
d["depth_multiple"],
|
||||
d["width_multiple"],
|
||||
d.get("channel_multiple"),
|
||||
)
|
||||
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
|
||||
no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
|
||||
if not ch_mul:
|
||||
ch_mul = 8
|
||||
|
||||
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
|
||||
for i, (f, n, m, args) in enumerate(d["backbone"] + d["head"]): # from, number, module, args
|
||||
m_str = m
|
||||
m = eval(m) if isinstance(m, str) else m # eval strings
|
||||
for j, a in enumerate(args):
|
||||
try:
|
||||
args[j] = eval(a) if isinstance(a, str) else a # eval strings
|
||||
except NameError:
|
||||
pass
|
||||
|
||||
n = max(round(n * gd), 1) if n > 1 else n # depth gain
|
||||
if m in [
|
||||
nn.Conv2d,
|
||||
Conv,
|
||||
DWConv,
|
||||
DWConvTranspose2d,
|
||||
Bottleneck,
|
||||
SPP,
|
||||
SPPF,
|
||||
MixConv2d,
|
||||
Focus,
|
||||
CrossConv,
|
||||
BottleneckCSP,
|
||||
C3,
|
||||
C3x,
|
||||
]:
|
||||
c1, c2 = ch[f], args[0]
|
||||
c2 = make_divisible(c2 * gw, ch_mul) if c2 != no else c2
|
||||
|
||||
args = [c1, c2, *args[1:]]
|
||||
if m in [BottleneckCSP, C3, C3x]:
|
||||
args.insert(2, n)
|
||||
n = 1
|
||||
elif m is nn.BatchNorm2d:
|
||||
args = [ch[f]]
|
||||
elif m is Concat:
|
||||
c2 = sum(ch[-1 if x == -1 else x + 1] for x in f)
|
||||
elif m in [Detect, Segment]:
|
||||
args.append([ch[x + 1] for x in f])
|
||||
if isinstance(args[1], int): # number of anchors
|
||||
args[1] = [list(range(args[1] * 2))] * len(f)
|
||||
if m is Segment:
|
||||
args[3] = make_divisible(args[3] * gw, ch_mul)
|
||||
args.append(imgsz)
|
||||
else:
|
||||
c2 = ch[f]
|
||||
|
||||
tf_m = eval("TF" + m_str.replace("nn.", ""))
|
||||
m_ = (
|
||||
keras.Sequential([tf_m(*args, w=model.model[i][j]) for j in range(n)])
|
||||
if n > 1
|
||||
else tf_m(*args, w=model.model[i])
|
||||
) # module
|
||||
|
||||
torch_m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
|
||||
t = str(m)[8:-2].replace("__main__.", "") # module type
|
||||
np = sum(x.numel() for x in torch_m_.parameters()) # number params
|
||||
m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
|
||||
LOGGER.info(f"{i:>3}{str(f):>18}{str(n):>3}{np:>10} {t:<40}{str(args):<30}") # print
|
||||
save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
|
||||
layers.append(m_)
|
||||
ch.append(c2)
|
||||
return keras.Sequential(layers), sorted(save)
|
||||
|
||||
|
||||
class TFModel:
|
||||
"""Implements YOLOv5 model in TensorFlow, supporting TensorFlow, Keras, and TFLite formats for object detection."""
|
||||
|
||||
def __init__(self, cfg="yolov5s.yaml", ch=3, nc=None, model=None, imgsz=(640, 640)):
|
||||
"""Initializes TF YOLOv5 model with specified configuration, channels, classes, model instance, and input
|
||||
size.
|
||||
"""
|
||||
super().__init__()
|
||||
if isinstance(cfg, dict):
|
||||
self.yaml = cfg # model dict
|
||||
else: # is *.yaml
|
||||
import yaml # for torch hub
|
||||
|
||||
self.yaml_file = Path(cfg).name
|
||||
with open(cfg) as f:
|
||||
self.yaml = yaml.load(f, Loader=yaml.FullLoader) # model dict
|
||||
|
||||
# Define model
|
||||
if nc and nc != self.yaml["nc"]:
|
||||
LOGGER.info(f"Overriding {cfg} nc={self.yaml['nc']} with nc={nc}")
|
||||
self.yaml["nc"] = nc # override yaml value
|
||||
self.model, self.savelist = parse_model(deepcopy(self.yaml), ch=[ch], model=model, imgsz=imgsz)
|
||||
|
||||
def predict(
|
||||
self,
|
||||
inputs,
|
||||
tf_nms=False,
|
||||
agnostic_nms=False,
|
||||
topk_per_class=100,
|
||||
topk_all=100,
|
||||
iou_thres=0.45,
|
||||
conf_thres=0.25,
|
||||
):
|
||||
"""Runs inference on input data, with an option for TensorFlow NMS."""
|
||||
y = [] # outputs
|
||||
x = inputs
|
||||
for m in self.model.layers:
|
||||
if m.f != -1: # if not from previous layer
|
||||
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
|
||||
|
||||
x = m(x) # run
|
||||
y.append(x if m.i in self.savelist else None) # save output
|
||||
|
||||
# Add TensorFlow NMS
|
||||
if tf_nms:
|
||||
boxes = self._xywh2xyxy(x[0][..., :4])
|
||||
probs = x[0][:, :, 4:5]
|
||||
classes = x[0][:, :, 5:]
|
||||
scores = probs * classes
|
||||
if agnostic_nms:
|
||||
nms = AgnosticNMS()((boxes, classes, scores), topk_all, iou_thres, conf_thres)
|
||||
else:
|
||||
boxes = tf.expand_dims(boxes, 2)
|
||||
nms = tf.image.combined_non_max_suppression(
|
||||
boxes, scores, topk_per_class, topk_all, iou_thres, conf_thres, clip_boxes=False
|
||||
)
|
||||
return (nms,)
|
||||
return x # output [1,6300,85] = [xywh, conf, class0, class1, ...]
|
||||
# x = x[0] # [x(1,6300,85), ...] to x(6300,85)
|
||||
# xywh = x[..., :4] # x(6300,4) boxes
|
||||
# conf = x[..., 4:5] # x(6300,1) confidences
|
||||
# cls = tf.reshape(tf.cast(tf.argmax(x[..., 5:], axis=1), tf.float32), (-1, 1)) # x(6300,1) classes
|
||||
# return tf.concat([conf, cls, xywh], 1)
|
||||
|
||||
@staticmethod
|
||||
def _xywh2xyxy(xywh):
|
||||
"""Converts bounding box format from [x, y, w, h] to [x1, y1, x2, y2], where xy1=top-left and xy2=bottom-
|
||||
right.
|
||||
"""
|
||||
x, y, w, h = tf.split(xywh, num_or_size_splits=4, axis=-1)
|
||||
return tf.concat([x - w / 2, y - h / 2, x + w / 2, y + h / 2], axis=-1)
|
||||
|
||||
|
||||
class AgnosticNMS(keras.layers.Layer):
|
||||
"""Performs agnostic non-maximum suppression (NMS) on detected objects using IoU and confidence thresholds."""
|
||||
|
||||
def call(self, input, topk_all, iou_thres, conf_thres):
|
||||
"""Performs agnostic NMS on input tensors using given thresholds and top-K selection."""
|
||||
return tf.map_fn(
|
||||
lambda x: self._nms(x, topk_all, iou_thres, conf_thres),
|
||||
input,
|
||||
fn_output_signature=(tf.float32, tf.float32, tf.float32, tf.int32),
|
||||
name="agnostic_nms",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _nms(x, topk_all=100, iou_thres=0.45, conf_thres=0.25):
|
||||
"""Performs agnostic non-maximum suppression (NMS) on detected objects, filtering based on IoU and confidence
|
||||
thresholds.
|
||||
"""
|
||||
boxes, classes, scores = x
|
||||
class_inds = tf.cast(tf.argmax(classes, axis=-1), tf.float32)
|
||||
scores_inp = tf.reduce_max(scores, -1)
|
||||
selected_inds = tf.image.non_max_suppression(
|
||||
boxes, scores_inp, max_output_size=topk_all, iou_threshold=iou_thres, score_threshold=conf_thres
|
||||
)
|
||||
selected_boxes = tf.gather(boxes, selected_inds)
|
||||
padded_boxes = tf.pad(
|
||||
selected_boxes,
|
||||
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]], [0, 0]],
|
||||
mode="CONSTANT",
|
||||
constant_values=0.0,
|
||||
)
|
||||
selected_scores = tf.gather(scores_inp, selected_inds)
|
||||
padded_scores = tf.pad(
|
||||
selected_scores,
|
||||
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
|
||||
mode="CONSTANT",
|
||||
constant_values=-1.0,
|
||||
)
|
||||
selected_classes = tf.gather(class_inds, selected_inds)
|
||||
padded_classes = tf.pad(
|
||||
selected_classes,
|
||||
paddings=[[0, topk_all - tf.shape(selected_boxes)[0]]],
|
||||
mode="CONSTANT",
|
||||
constant_values=-1.0,
|
||||
)
|
||||
valid_detections = tf.shape(selected_inds)[0]
|
||||
return padded_boxes, padded_scores, padded_classes, valid_detections
|
||||
|
||||
|
||||
def activations(act=nn.SiLU):
|
||||
"""Converts PyTorch activations to TensorFlow equivalents, supporting LeakyReLU, Hardswish, and SiLU/Swish."""
|
||||
if isinstance(act, nn.LeakyReLU):
|
||||
return lambda x: keras.activations.relu(x, alpha=0.1)
|
||||
elif isinstance(act, nn.Hardswish):
|
||||
return lambda x: x * tf.nn.relu6(x + 3) * 0.166666667
|
||||
elif isinstance(act, (nn.SiLU, SiLU)):
|
||||
return lambda x: keras.activations.swish(x)
|
||||
else:
|
||||
raise Exception(f"no matching TensorFlow activation found for PyTorch activation {act}")
|
||||
|
||||
|
||||
def representative_dataset_gen(dataset, ncalib=100):
|
||||
"""Generates a representative dataset for calibration by yielding transformed numpy arrays from the input
|
||||
dataset.
|
||||
"""
|
||||
for n, (path, img, im0s, vid_cap, string) in enumerate(dataset):
|
||||
im = np.transpose(img, [1, 2, 0])
|
||||
im = np.expand_dims(im, axis=0).astype(np.float32)
|
||||
im /= 255
|
||||
yield [im]
|
||||
if n >= ncalib:
|
||||
break
|
||||
|
||||
|
||||
def run(
|
||||
weights=ROOT / "yolov5s.pt", # weights path
|
||||
imgsz=(640, 640), # inference size h,w
|
||||
batch_size=1, # batch size
|
||||
dynamic=False, # dynamic batch size
|
||||
):
|
||||
# PyTorch model
|
||||
"""Exports YOLOv5 model from PyTorch to TensorFlow and Keras formats, performing inference for validation."""
|
||||
im = torch.zeros((batch_size, 3, *imgsz)) # BCHW image
|
||||
model = attempt_load(weights, device=torch.device("cpu"), inplace=True, fuse=False)
|
||||
_ = model(im) # inference
|
||||
model.info()
|
||||
|
||||
# TensorFlow model
|
||||
im = tf.zeros((batch_size, *imgsz, 3)) # BHWC image
|
||||
tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
|
||||
_ = tf_model.predict(im) # inference
|
||||
|
||||
# Keras model
|
||||
im = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
|
||||
keras_model = keras.Model(inputs=im, outputs=tf_model.predict(im))
|
||||
keras_model.summary()
|
||||
|
||||
LOGGER.info("PyTorch, TensorFlow and Keras models successfully verified.\nUse export.py for TF model export.")
|
||||
|
||||
|
||||
def parse_opt():
|
||||
"""Parses and returns command-line options for model inference, including weights path, image size, batch size, and
|
||||
dynamic batching.
|
||||
"""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt", help="weights path")
|
||||
parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[640], help="inference size h,w")
|
||||
parser.add_argument("--batch-size", type=int, default=1, help="batch size")
|
||||
parser.add_argument("--dynamic", action="store_true", help="dynamic batch size")
|
||||
opt = parser.parse_args()
|
||||
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
||||
print_args(vars(opt))
|
||||
return opt
|
||||
|
||||
|
||||
def main(opt):
|
||||
"""Executes the YOLOv5 model run function with parsed command line options."""
|
||||
run(**vars(opt))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
opt = parse_opt()
|
||||
main(opt)
|
495
yolov5/models/yolo.py
Normal file
495
yolov5/models/yolo.py
Normal file
@ -0,0 +1,495 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""
|
||||
YOLO-specific modules.
|
||||
|
||||
Usage:
|
||||
$ python models/yolo.py --cfg yolov5s.yaml
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import contextlib
|
||||
import math
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
FILE = Path(__file__).resolve()
|
||||
ROOT = FILE.parents[1] # YOLOv5 root directory
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.append(str(ROOT)) # add ROOT to PATH
|
||||
if platform.system() != "Windows":
|
||||
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
||||
|
||||
from models.common import (
|
||||
C3,
|
||||
C3SPP,
|
||||
C3TR,
|
||||
SPP,
|
||||
SPPF,
|
||||
Bottleneck,
|
||||
BottleneckCSP,
|
||||
C3Ghost,
|
||||
C3x,
|
||||
Classify,
|
||||
Concat,
|
||||
Contract,
|
||||
Conv,
|
||||
CrossConv,
|
||||
DetectMultiBackend,
|
||||
DWConv,
|
||||
DWConvTranspose2d,
|
||||
Expand,
|
||||
Focus,
|
||||
GhostBottleneck,
|
||||
GhostConv,
|
||||
Proto,
|
||||
)
|
||||
from models.experimental import MixConv2d
|
||||
from utils.autoanchor import check_anchor_order
|
||||
from utils.general import LOGGER, check_version, check_yaml, colorstr, make_divisible, print_args
|
||||
from utils.plots import feature_visualization
|
||||
from utils.torch_utils import (
|
||||
fuse_conv_and_bn,
|
||||
initialize_weights,
|
||||
model_info,
|
||||
profile,
|
||||
scale_img,
|
||||
select_device,
|
||||
time_sync,
|
||||
)
|
||||
|
||||
try:
|
||||
import thop # for FLOPs computation
|
||||
except ImportError:
|
||||
thop = None
|
||||
|
||||
|
||||
class Detect(nn.Module):
|
||||
"""YOLOv5 Detect head for processing input tensors and generating detection outputs in object detection models."""
|
||||
|
||||
stride = None # strides computed during build
|
||||
dynamic = False # force grid reconstruction
|
||||
export = False # export mode
|
||||
|
||||
def __init__(self, nc=80, anchors=(), ch=(), inplace=True):
|
||||
"""Initializes YOLOv5 detection layer with specified classes, anchors, channels, and inplace operations."""
|
||||
super().__init__()
|
||||
self.nc = nc # number of classes
|
||||
self.no = nc + 5 # number of outputs per anchor
|
||||
self.nl = len(anchors) # number of detection layers
|
||||
self.na = len(anchors[0]) // 2 # number of anchors
|
||||
self.grid = [torch.empty(0) for _ in range(self.nl)] # init grid
|
||||
self.anchor_grid = [torch.empty(0) for _ in range(self.nl)] # init anchor grid
|
||||
self.register_buffer("anchors", torch.tensor(anchors).float().view(self.nl, -1, 2)) # shape(nl,na,2)
|
||||
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
|
||||
self.inplace = inplace # use inplace ops (e.g. slice assignment)
|
||||
|
||||
def forward(self, x):
|
||||
"""Processes input through YOLOv5 layers, altering shape for detection: `x(bs, 3, ny, nx, 85)`."""
|
||||
z = [] # inference output
|
||||
for i in range(self.nl):
|
||||
x[i] = self.m[i](x[i]) # conv
|
||||
bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
|
||||
x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
|
||||
|
||||
if not self.training: # inference
|
||||
if self.dynamic or self.grid[i].shape[2:4] != x[i].shape[2:4]:
|
||||
self.grid[i], self.anchor_grid[i] = self._make_grid(nx, ny, i)
|
||||
|
||||
if isinstance(self, Segment): # (boxes + masks)
|
||||
xy, wh, conf, mask = x[i].split((2, 2, self.nc + 1, self.no - self.nc - 5), 4)
|
||||
xy = (xy.sigmoid() * 2 + self.grid[i]) * self.stride[i] # xy
|
||||
wh = (wh.sigmoid() * 2) ** 2 * self.anchor_grid[i] # wh
|
||||
y = torch.cat((xy, wh, conf.sigmoid(), mask), 4)
|
||||
else: # Detect (boxes only)
|
||||
xy, wh, conf = x[i].sigmoid().split((2, 2, self.nc + 1), 4)
|
||||
xy = (xy * 2 + self.grid[i]) * self.stride[i] # xy
|
||||
wh = (wh * 2) ** 2 * self.anchor_grid[i] # wh
|
||||
y = torch.cat((xy, wh, conf), 4)
|
||||
z.append(y.view(bs, self.na * nx * ny, self.no))
|
||||
|
||||
return x if self.training else (torch.cat(z, 1),) if self.export else (torch.cat(z, 1), x)
|
||||
|
||||
def _make_grid(self, nx=20, ny=20, i=0, torch_1_10=check_version(torch.__version__, "1.10.0")):
|
||||
"""Generates a mesh grid for anchor boxes with optional compatibility for torch versions < 1.10."""
|
||||
d = self.anchors[i].device
|
||||
t = self.anchors[i].dtype
|
||||
shape = 1, self.na, ny, nx, 2 # grid shape
|
||||
y, x = torch.arange(ny, device=d, dtype=t), torch.arange(nx, device=d, dtype=t)
|
||||
yv, xv = torch.meshgrid(y, x, indexing="ij") if torch_1_10 else torch.meshgrid(y, x) # torch>=0.7 compatibility
|
||||
grid = torch.stack((xv, yv), 2).expand(shape) - 0.5 # add grid offset, i.e. y = 2.0 * x - 0.5
|
||||
anchor_grid = (self.anchors[i] * self.stride[i]).view((1, self.na, 1, 1, 2)).expand(shape)
|
||||
return grid, anchor_grid
|
||||
|
||||
|
||||
class Segment(Detect):
|
||||
"""YOLOv5 Segment head for segmentation models, extending Detect with mask and prototype layers."""
|
||||
|
||||
def __init__(self, nc=80, anchors=(), nm=32, npr=256, ch=(), inplace=True):
|
||||
"""Initializes YOLOv5 Segment head with options for mask count, protos, and channel adjustments."""
|
||||
super().__init__(nc, anchors, ch, inplace)
|
||||
self.nm = nm # number of masks
|
||||
self.npr = npr # number of protos
|
||||
self.no = 5 + nc + self.nm # number of outputs per anchor
|
||||
self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
|
||||
self.proto = Proto(ch[0], self.npr, self.nm) # protos
|
||||
self.detect = Detect.forward
|
||||
|
||||
def forward(self, x):
|
||||
"""Processes input through the network, returning detections and prototypes; adjusts output based on
|
||||
training/export mode.
|
||||
"""
|
||||
p = self.proto(x[0])
|
||||
x = self.detect(self, x)
|
||||
return (x, p) if self.training else (x[0], p) if self.export else (x[0], p, x[1])
|
||||
|
||||
|
||||
class BaseModel(nn.Module):
|
||||
"""YOLOv5 base model."""
|
||||
|
||||
def forward(self, x, profile=False, visualize=False):
|
||||
"""Executes a single-scale inference or training pass on the YOLOv5 base model, with options for profiling and
|
||||
visualization.
|
||||
"""
|
||||
return self._forward_once(x, profile, visualize) # single-scale inference, train
|
||||
|
||||
def _forward_once(self, x, profile=False, visualize=False):
|
||||
"""Performs a forward pass on the YOLOv5 model, enabling profiling and feature visualization options."""
|
||||
y, dt = [], [] # outputs
|
||||
for m in self.model:
|
||||
if m.f != -1: # if not from previous layer
|
||||
x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
|
||||
if profile:
|
||||
self._profile_one_layer(m, x, dt)
|
||||
x = m(x) # run
|
||||
y.append(x if m.i in self.save else None) # save output
|
||||
if visualize:
|
||||
feature_visualization(x, m.type, m.i, save_dir=visualize)
|
||||
return x
|
||||
|
||||
def _profile_one_layer(self, m, x, dt):
|
||||
"""Profiles a single layer's performance by computing GFLOPs, execution time, and parameters."""
|
||||
c = m == self.model[-1] # is final layer, copy input as inplace fix
|
||||
o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1e9 * 2 if thop else 0 # FLOPs
|
||||
t = time_sync()
|
||||
for _ in range(10):
|
||||
m(x.copy() if c else x)
|
||||
dt.append((time_sync() - t) * 100)
|
||||
if m == self.model[0]:
|
||||
LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} module")
|
||||
LOGGER.info(f"{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}")
|
||||
if c:
|
||||
LOGGER.info(f"{sum(dt):10.2f} {'-':>10s} {'-':>10s} Total")
|
||||
|
||||
def fuse(self):
|
||||
"""Fuses Conv2d() and BatchNorm2d() layers in the model to improve inference speed."""
|
||||
LOGGER.info("Fusing layers... ")
|
||||
for m in self.model.modules():
|
||||
if isinstance(m, (Conv, DWConv)) and hasattr(m, "bn"):
|
||||
m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
|
||||
delattr(m, "bn") # remove batchnorm
|
||||
m.forward = m.forward_fuse # update forward
|
||||
self.info()
|
||||
return self
|
||||
|
||||
def info(self, verbose=False, img_size=640):
|
||||
"""Prints model information given verbosity and image size, e.g., `info(verbose=True, img_size=640)`."""
|
||||
model_info(self, verbose, img_size)
|
||||
|
||||
def _apply(self, fn):
|
||||
"""Applies transformations like to(), cpu(), cuda(), half() to model tensors excluding parameters or registered
|
||||
buffers.
|
||||
"""
|
||||
self = super()._apply(fn)
|
||||
m = self.model[-1] # Detect()
|
||||
if isinstance(m, (Detect, Segment)):
|
||||
m.stride = fn(m.stride)
|
||||
m.grid = list(map(fn, m.grid))
|
||||
if isinstance(m.anchor_grid, list):
|
||||
m.anchor_grid = list(map(fn, m.anchor_grid))
|
||||
return self
|
||||
|
||||
|
||||
class DetectionModel(BaseModel):
|
||||
"""YOLOv5 detection model class for object detection tasks, supporting custom configurations and anchors."""
|
||||
|
||||
def __init__(self, cfg="yolov5s.yaml", ch=3, nc=None, anchors=None):
|
||||
"""Initializes YOLOv5 model with configuration file, input channels, number of classes, and custom anchors."""
|
||||
super().__init__()
|
||||
if isinstance(cfg, dict):
|
||||
self.yaml = cfg # model dict
|
||||
else: # is *.yaml
|
||||
import yaml # for torch hub
|
||||
|
||||
self.yaml_file = Path(cfg).name
|
||||
with open(cfg, encoding="ascii", errors="ignore") as f:
|
||||
self.yaml = yaml.safe_load(f) # model dict
|
||||
|
||||
# Define model
|
||||
ch = self.yaml["ch"] = self.yaml.get("ch", ch) # input channels
|
||||
if nc and nc != self.yaml["nc"]:
|
||||
LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}")
|
||||
self.yaml["nc"] = nc # override yaml value
|
||||
if anchors:
|
||||
LOGGER.info(f"Overriding model.yaml anchors with anchors={anchors}")
|
||||
self.yaml["anchors"] = round(anchors) # override yaml value
|
||||
self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
|
||||
self.names = [str(i) for i in range(self.yaml["nc"])] # default names
|
||||
self.inplace = self.yaml.get("inplace", True)
|
||||
|
||||
# Build strides, anchors
|
||||
m = self.model[-1] # Detect()
|
||||
if isinstance(m, (Detect, Segment)):
|
||||
|
||||
def _forward(x):
|
||||
"""Passes the input 'x' through the model and returns the processed output."""
|
||||
return self.forward(x)[0] if isinstance(m, Segment) else self.forward(x)
|
||||
|
||||
s = 256 # 2x min stride
|
||||
m.inplace = self.inplace
|
||||
m.stride = torch.tensor([s / x.shape[-2] for x in _forward(torch.zeros(1, ch, s, s))]) # forward
|
||||
check_anchor_order(m)
|
||||
m.anchors /= m.stride.view(-1, 1, 1)
|
||||
self.stride = m.stride
|
||||
self._initialize_biases() # only run once
|
||||
|
||||
# Init weights, biases
|
||||
initialize_weights(self)
|
||||
self.info()
|
||||
LOGGER.info("")
|
||||
|
||||
def forward(self, x, augment=False, profile=False, visualize=False):
|
||||
"""Performs single-scale or augmented inference and may include profiling or visualization."""
|
||||
if augment:
|
||||
return self._forward_augment(x) # augmented inference, None
|
||||
return self._forward_once(x, profile, visualize) # single-scale inference, train
|
||||
|
||||
def _forward_augment(self, x):
|
||||
"""Performs augmented inference across different scales and flips, returning combined detections."""
|
||||
img_size = x.shape[-2:] # height, width
|
||||
s = [1, 0.83, 0.67] # scales
|
||||
f = [None, 3, None] # flips (2-ud, 3-lr)
|
||||
y = [] # outputs
|
||||
for si, fi in zip(s, f):
|
||||
xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
|
||||
yi = self._forward_once(xi)[0] # forward
|
||||
# cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
|
||||
yi = self._descale_pred(yi, fi, si, img_size)
|
||||
y.append(yi)
|
||||
y = self._clip_augmented(y) # clip augmented tails
|
||||
return torch.cat(y, 1), None # augmented inference, train
|
||||
|
||||
def _descale_pred(self, p, flips, scale, img_size):
|
||||
"""De-scales predictions from augmented inference, adjusting for flips and image size."""
|
||||
if self.inplace:
|
||||
p[..., :4] /= scale # de-scale
|
||||
if flips == 2:
|
||||
p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
|
||||
elif flips == 3:
|
||||
p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
|
||||
else:
|
||||
x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
|
||||
if flips == 2:
|
||||
y = img_size[0] - y # de-flip ud
|
||||
elif flips == 3:
|
||||
x = img_size[1] - x # de-flip lr
|
||||
p = torch.cat((x, y, wh, p[..., 4:]), -1)
|
||||
return p
|
||||
|
||||
def _clip_augmented(self, y):
|
||||
"""Clips augmented inference tails for YOLOv5 models, affecting first and last tensors based on grid points and
|
||||
layer counts.
|
||||
"""
|
||||
nl = self.model[-1].nl # number of detection layers (P3-P5)
|
||||
g = sum(4**x for x in range(nl)) # grid points
|
||||
e = 1 # exclude layer count
|
||||
i = (y[0].shape[1] // g) * sum(4**x for x in range(e)) # indices
|
||||
y[0] = y[0][:, :-i] # large
|
||||
i = (y[-1].shape[1] // g) * sum(4 ** (nl - 1 - x) for x in range(e)) # indices
|
||||
y[-1] = y[-1][:, i:] # small
|
||||
return y
|
||||
|
||||
def _initialize_biases(self, cf=None):
|
||||
"""
|
||||
Initializes biases for YOLOv5's Detect() module, optionally using class frequencies (cf).
|
||||
|
||||
For details see https://arxiv.org/abs/1708.02002 section 3.3.
|
||||
"""
|
||||
# cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
|
||||
m = self.model[-1] # Detect() module
|
||||
for mi, s in zip(m.m, m.stride): # from
|
||||
b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
|
||||
b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
|
||||
b.data[:, 5 : 5 + m.nc] += (
|
||||
math.log(0.6 / (m.nc - 0.99999)) if cf is None else torch.log(cf / cf.sum())
|
||||
) # cls
|
||||
mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
|
||||
|
||||
|
||||
Model = DetectionModel # retain YOLOv5 'Model' class for backwards compatibility
|
||||
|
||||
|
||||
class SegmentationModel(DetectionModel):
|
||||
"""YOLOv5 segmentation model for object detection and segmentation tasks with configurable parameters."""
|
||||
|
||||
def __init__(self, cfg="yolov5s-seg.yaml", ch=3, nc=None, anchors=None):
|
||||
"""Initializes a YOLOv5 segmentation model with configurable params: cfg (str) for configuration, ch (int) for channels, nc (int) for num classes, anchors (list)."""
|
||||
super().__init__(cfg, ch, nc, anchors)
|
||||
|
||||
|
||||
class ClassificationModel(BaseModel):
|
||||
"""YOLOv5 classification model for image classification tasks, initialized with a config file or detection model."""
|
||||
|
||||
def __init__(self, cfg=None, model=None, nc=1000, cutoff=10):
|
||||
"""Initializes YOLOv5 model with config file `cfg`, input channels `ch`, number of classes `nc`, and `cuttoff`
|
||||
index.
|
||||
"""
|
||||
super().__init__()
|
||||
self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg)
|
||||
|
||||
def _from_detection_model(self, model, nc=1000, cutoff=10):
|
||||
"""Creates a classification model from a YOLOv5 detection model, slicing at `cutoff` and adding a classification
|
||||
layer.
|
||||
"""
|
||||
if isinstance(model, DetectMultiBackend):
|
||||
model = model.model # unwrap DetectMultiBackend
|
||||
model.model = model.model[:cutoff] # backbone
|
||||
m = model.model[-1] # last layer
|
||||
ch = m.conv.in_channels if hasattr(m, "conv") else m.cv1.conv.in_channels # ch into module
|
||||
c = Classify(ch, nc) # Classify()
|
||||
c.i, c.f, c.type = m.i, m.f, "models.common.Classify" # index, from, type
|
||||
model.model[-1] = c # replace
|
||||
self.model = model.model
|
||||
self.stride = model.stride
|
||||
self.save = []
|
||||
self.nc = nc
|
||||
|
||||
def _from_yaml(self, cfg):
|
||||
"""Creates a YOLOv5 classification model from a specified *.yaml configuration file."""
|
||||
self.model = None
|
||||
|
||||
|
||||
def parse_model(d, ch):
|
||||
"""Parses a YOLOv5 model from a dict `d`, configuring layers based on input channels `ch` and model architecture."""
|
||||
LOGGER.info(f"\n{'':>3}{'from':>18}{'n':>3}{'params':>10} {'module':<40}{'arguments':<30}")
|
||||
anchors, nc, gd, gw, act, ch_mul = (
|
||||
d["anchors"],
|
||||
d["nc"],
|
||||
d["depth_multiple"],
|
||||
d["width_multiple"],
|
||||
d.get("activation"),
|
||||
d.get("channel_multiple"),
|
||||
)
|
||||
if act:
|
||||
Conv.default_act = eval(act) # redefine default activation, i.e. Conv.default_act = nn.SiLU()
|
||||
LOGGER.info(f"{colorstr('activation:')} {act}") # print
|
||||
if not ch_mul:
|
||||
ch_mul = 8
|
||||
na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
|
||||
no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
|
||||
|
||||
layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
|
||||
for i, (f, n, m, args) in enumerate(d["backbone"] + d["head"]): # from, number, module, args
|
||||
m = eval(m) if isinstance(m, str) else m # eval strings
|
||||
for j, a in enumerate(args):
|
||||
with contextlib.suppress(NameError):
|
||||
args[j] = eval(a) if isinstance(a, str) else a # eval strings
|
||||
|
||||
n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
|
||||
if m in {
|
||||
Conv,
|
||||
GhostConv,
|
||||
Bottleneck,
|
||||
GhostBottleneck,
|
||||
SPP,
|
||||
SPPF,
|
||||
DWConv,
|
||||
MixConv2d,
|
||||
Focus,
|
||||
CrossConv,
|
||||
BottleneckCSP,
|
||||
C3,
|
||||
C3TR,
|
||||
C3SPP,
|
||||
C3Ghost,
|
||||
nn.ConvTranspose2d,
|
||||
DWConvTranspose2d,
|
||||
C3x,
|
||||
}:
|
||||
c1, c2 = ch[f], args[0]
|
||||
if c2 != no: # if not output
|
||||
c2 = make_divisible(c2 * gw, ch_mul)
|
||||
|
||||
args = [c1, c2, *args[1:]]
|
||||
if m in {BottleneckCSP, C3, C3TR, C3Ghost, C3x}:
|
||||
args.insert(2, n) # number of repeats
|
||||
n = 1
|
||||
elif m is nn.BatchNorm2d:
|
||||
args = [ch[f]]
|
||||
elif m is Concat:
|
||||
c2 = sum(ch[x] for x in f)
|
||||
# TODO: channel, gw, gd
|
||||
elif m in {Detect, Segment}:
|
||||
args.append([ch[x] for x in f])
|
||||
if isinstance(args[1], int): # number of anchors
|
||||
args[1] = [list(range(args[1] * 2))] * len(f)
|
||||
if m is Segment:
|
||||
args[3] = make_divisible(args[3] * gw, ch_mul)
|
||||
elif m is Contract:
|
||||
c2 = ch[f] * args[0] ** 2
|
||||
elif m is Expand:
|
||||
c2 = ch[f] // args[0] ** 2
|
||||
else:
|
||||
c2 = ch[f]
|
||||
|
||||
m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args) # module
|
||||
t = str(m)[8:-2].replace("__main__.", "") # module type
|
||||
np = sum(x.numel() for x in m_.parameters()) # number params
|
||||
m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
|
||||
LOGGER.info(f"{i:>3}{str(f):>18}{n_:>3}{np:10.0f} {t:<40}{str(args):<30}") # print
|
||||
save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
|
||||
layers.append(m_)
|
||||
if i == 0:
|
||||
ch = []
|
||||
ch.append(c2)
|
||||
return nn.Sequential(*layers), sorted(save)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--cfg", type=str, default="yolov5s.yaml", help="model.yaml")
|
||||
parser.add_argument("--batch-size", type=int, default=1, help="total batch size for all GPUs")
|
||||
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
||||
parser.add_argument("--profile", action="store_true", help="profile model speed")
|
||||
parser.add_argument("--line-profile", action="store_true", help="profile model speed layer by layer")
|
||||
parser.add_argument("--test", action="store_true", help="test all yolo*.yaml")
|
||||
opt = parser.parse_args()
|
||||
opt.cfg = check_yaml(opt.cfg) # check YAML
|
||||
print_args(vars(opt))
|
||||
device = select_device(opt.device)
|
||||
|
||||
# Create model
|
||||
im = torch.rand(opt.batch_size, 3, 640, 640).to(device)
|
||||
model = Model(opt.cfg).to(device)
|
||||
|
||||
# Options
|
||||
if opt.line_profile: # profile layer by layer
|
||||
model(im, profile=True)
|
||||
|
||||
elif opt.profile: # profile forward-backward
|
||||
results = profile(input=im, ops=[model], n=3)
|
||||
|
||||
elif opt.test: # test all models
|
||||
for cfg in Path(ROOT / "models").rglob("yolo*.yaml"):
|
||||
try:
|
||||
_ = Model(cfg)
|
||||
except Exception as e:
|
||||
print(f"Error in {cfg}: {e}")
|
||||
|
||||
else: # report fused model summary
|
||||
model.fuse()
|
49
yolov5/models/yolov5l.yaml
Normal file
49
yolov5/models/yolov5l.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.0 # model depth multiple
|
||||
width_multiple: 1.0 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/models/yolov5m.yaml
Normal file
49
yolov5/models/yolov5m.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.67 # model depth multiple
|
||||
width_multiple: 0.75 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/models/yolov5n.yaml
Normal file
49
yolov5/models/yolov5n.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.33 # model depth multiple
|
||||
width_multiple: 0.25 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/models/yolov5s.yaml
Normal file
49
yolov5/models/yolov5s.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 0.33 # model depth multiple
|
||||
width_multiple: 0.50 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/models/yolov5x.yaml
Normal file
49
yolov5/models/yolov5x.yaml
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Parameters
|
||||
nc: 80 # number of classes
|
||||
depth_multiple: 1.33 # model depth multiple
|
||||
width_multiple: 1.25 # layer channel multiple
|
||||
anchors:
|
||||
- [10, 13, 16, 30, 33, 23] # P3/8
|
||||
- [30, 61, 62, 45, 59, 119] # P4/16
|
||||
- [116, 90, 156, 198, 373, 326] # P5/32
|
||||
|
||||
# YOLOv5 v6.0 backbone
|
||||
backbone:
|
||||
# [from, number, module, args]
|
||||
[
|
||||
[-1, 1, Conv, [64, 6, 2, 2]], # 0-P1/2
|
||||
[-1, 1, Conv, [128, 3, 2]], # 1-P2/4
|
||||
[-1, 3, C3, [128]],
|
||||
[-1, 1, Conv, [256, 3, 2]], # 3-P3/8
|
||||
[-1, 6, C3, [256]],
|
||||
[-1, 1, Conv, [512, 3, 2]], # 5-P4/16
|
||||
[-1, 9, C3, [512]],
|
||||
[-1, 1, Conv, [1024, 3, 2]], # 7-P5/32
|
||||
[-1, 3, C3, [1024]],
|
||||
[-1, 1, SPPF, [1024, 5]], # 9
|
||||
]
|
||||
|
||||
# YOLOv5 v6.0 head
|
||||
head: [
|
||||
[-1, 1, Conv, [512, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 6], 1, Concat, [1]], # cat backbone P4
|
||||
[-1, 3, C3, [512, False]], # 13
|
||||
|
||||
[-1, 1, Conv, [256, 1, 1]],
|
||||
[-1, 1, nn.Upsample, [None, 2, "nearest"]],
|
||||
[[-1, 4], 1, Concat, [1]], # cat backbone P3
|
||||
[-1, 3, C3, [256, False]], # 17 (P3/8-small)
|
||||
|
||||
[-1, 1, Conv, [256, 3, 2]],
|
||||
[[-1, 14], 1, Concat, [1]], # cat head P4
|
||||
[-1, 3, C3, [512, False]], # 20 (P4/16-medium)
|
||||
|
||||
[-1, 1, Conv, [512, 3, 2]],
|
||||
[[-1, 10], 1, Concat, [1]], # cat head P5
|
||||
[-1, 3, C3, [1024, False]], # 23 (P5/32-large)
|
||||
|
||||
[[17, 20, 23], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5)
|
||||
]
|
49
yolov5/requirements.txt
Normal file
49
yolov5/requirements.txt
Normal file
@ -0,0 +1,49 @@
|
||||
YOLOv5 requirements
|
||||
# Usage: pip install -r requirements.txt
|
||||
|
||||
# Base ------------------------------------------------------------------------
|
||||
gitpython>=3.1.30
|
||||
matplotlib>=3.3
|
||||
numpy>=1.23.5
|
||||
opencv-python>=4.1.1
|
||||
pillow>=10.3.0
|
||||
psutil # system resources
|
||||
PyYAML>=5.3.1
|
||||
requests>=2.32.2
|
||||
scipy>=1.4.1
|
||||
thop>=0.1.1 # FLOPs computation
|
||||
torch>=1.8.0 # see https://pytorch.org/get-started/locally (recommended)
|
||||
torchvision>=0.9.0
|
||||
tqdm>=4.66.3
|
||||
ultralytics>=8.2.34 # https://ultralytics.com
|
||||
# protobuf<=3.20.1 # https://github.com/ultralytics/yolov5/issues/8012
|
||||
|
||||
# Logging ---------------------------------------------------------------------
|
||||
# tensorboard>=2.4.1
|
||||
# clearml>=1.2.0
|
||||
# comet
|
||||
|
||||
# Plotting --------------------------------------------------------------------
|
||||
pandas>=1.1.4
|
||||
seaborn>=0.11.0
|
||||
|
||||
# Export ----------------------------------------------------------------------
|
||||
# coremltools>=6.0 # CoreML export
|
||||
# onnx>=1.10.0 # ONNX export
|
||||
# onnx-simplifier>=0.4.1 # ONNX simplifier
|
||||
# nvidia-pyindex # TensorRT export
|
||||
# nvidia-tensorrt # TensorRT export
|
||||
# scikit-learn<=1.1.2 # CoreML quantization
|
||||
# tensorflow>=2.4.0,<=2.13.1 # TF exports (-cpu, -aarch64, -macos)
|
||||
# tensorflowjs>=3.9.0 # TF.js export
|
||||
# openvino-dev>=2023.0 # OpenVINO export
|
||||
|
||||
# Deploy ----------------------------------------------------------------------
|
||||
setuptools>=70.0.0 # Snyk vulnerability fix
|
||||
# tritonclient[all]~=2.24.0
|
||||
|
||||
# Extras ----------------------------------------------------------------------
|
||||
# ipython # interactive notebook
|
||||
# mss # screenshots
|
||||
# albumentations>=1.0.3
|
||||
# pycocotools>=2.0.6 # COCO mAP
|
986
yolov5/train.py
Normal file
986
yolov5/train.py
Normal file
@ -0,0 +1,986 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""
|
||||
Train a YOLOv5 model on a custom dataset. Models and datasets download automatically from the latest YOLOv5 release.
|
||||
|
||||
Usage - Single-GPU training:
|
||||
$ python train.py --data coco128.yaml --weights yolov5s.pt --img 640 # from pretrained (recommended)
|
||||
$ python train.py --data coco128.yaml --weights '' --cfg yolov5s.yaml --img 640 # from scratch
|
||||
|
||||
Usage - Multi-GPU DDP training:
|
||||
$ python -m torch.distributed.run --nproc_per_node 4 --master_port 1 train.py --data coco128.yaml --weights yolov5s.pt --img 640 --device 0,1,2,3
|
||||
|
||||
Models: https://github.com/ultralytics/yolov5/tree/master/models
|
||||
Datasets: https://github.com/ultralytics/yolov5/tree/master/data
|
||||
Tutorial: https://docs.ultralytics.com/yolov5/tutorials/train_custom_data
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from copy import deepcopy
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
import comet_ml # must be imported before torch (if installed)
|
||||
except ImportError:
|
||||
comet_ml = None
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.nn as nn
|
||||
import yaml
|
||||
from torch.optim import lr_scheduler
|
||||
from tqdm import tqdm
|
||||
|
||||
FILE = Path(__file__).resolve()
|
||||
ROOT = FILE.parents[0] # YOLOv5 root directory
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.append(str(ROOT)) # add ROOT to PATH
|
||||
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
||||
|
||||
import val as validate # for end-of-epoch mAP
|
||||
from models.experimental import attempt_load
|
||||
from models.yolo import Model
|
||||
from utils.autoanchor import check_anchors
|
||||
from utils.autobatch import check_train_batch_size
|
||||
from utils.callbacks import Callbacks
|
||||
from utils.dataloaders import create_dataloader
|
||||
from utils.downloads import attempt_download, is_url
|
||||
from utils.general import (
|
||||
LOGGER,
|
||||
TQDM_BAR_FORMAT,
|
||||
check_amp,
|
||||
check_dataset,
|
||||
check_file,
|
||||
check_git_info,
|
||||
check_git_status,
|
||||
check_img_size,
|
||||
check_requirements,
|
||||
check_suffix,
|
||||
check_yaml,
|
||||
colorstr,
|
||||
get_latest_run,
|
||||
increment_path,
|
||||
init_seeds,
|
||||
intersect_dicts,
|
||||
labels_to_class_weights,
|
||||
labels_to_image_weights,
|
||||
methods,
|
||||
one_cycle,
|
||||
print_args,
|
||||
print_mutation,
|
||||
strip_optimizer,
|
||||
yaml_save,
|
||||
)
|
||||
from utils.loggers import LOGGERS, Loggers
|
||||
from utils.loggers.comet.comet_utils import check_comet_resume
|
||||
from utils.loss import ComputeLoss
|
||||
from utils.metrics import fitness
|
||||
from utils.plots import plot_evolve
|
||||
from utils.torch_utils import (
|
||||
EarlyStopping,
|
||||
ModelEMA,
|
||||
de_parallel,
|
||||
select_device,
|
||||
smart_DDP,
|
||||
smart_optimizer,
|
||||
smart_resume,
|
||||
torch_distributed_zero_first,
|
||||
)
|
||||
|
||||
LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
|
||||
RANK = int(os.getenv("RANK", -1))
|
||||
WORLD_SIZE = int(os.getenv("WORLD_SIZE", 1))
|
||||
GIT_INFO = check_git_info()
|
||||
|
||||
|
||||
def train(hyp, opt, device, callbacks):
|
||||
"""
|
||||
Train a YOLOv5 model on a custom dataset using specified hyperparameters, options, and device, managing datasets,
|
||||
model architecture, loss computation, and optimizer steps.
|
||||
|
||||
Args:
|
||||
hyp (str | dict): Path to the hyperparameters YAML file or a dictionary of hyperparameters.
|
||||
opt (argparse.Namespace): Parsed command-line arguments containing training options.
|
||||
device (torch.device): Device on which training occurs, e.g., 'cuda' or 'cpu'.
|
||||
callbacks (Callbacks): Callback functions for various training events.
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Models and datasets download automatically from the latest YOLOv5 release.
|
||||
|
||||
Example:
|
||||
Single-GPU training:
|
||||
```bash
|
||||
$ python train.py --data coco128.yaml --weights yolov5s.pt --img 640 # from pretrained (recommended)
|
||||
$ python train.py --data coco128.yaml --weights '' --cfg yolov5s.yaml --img 640 # from scratch
|
||||
```
|
||||
|
||||
Multi-GPU DDP training:
|
||||
```bash
|
||||
$ python -m torch.distributed.run --nproc_per_node 4 --master_port 1 train.py --data coco128.yaml --weights
|
||||
yolov5s.pt --img 640 --device 0,1,2,3
|
||||
```
|
||||
|
||||
For more usage details, refer to:
|
||||
- Models: https://github.com/ultralytics/yolov5/tree/master/models
|
||||
- Datasets: https://github.com/ultralytics/yolov5/tree/master/data
|
||||
- Tutorial: https://docs.ultralytics.com/yolov5/tutorials/train_custom_data
|
||||
"""
|
||||
save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze = (
|
||||
Path(opt.save_dir),
|
||||
opt.epochs,
|
||||
opt.batch_size,
|
||||
opt.weights,
|
||||
opt.single_cls,
|
||||
opt.evolve,
|
||||
opt.data,
|
||||
opt.cfg,
|
||||
opt.resume,
|
||||
opt.noval,
|
||||
opt.nosave,
|
||||
opt.workers,
|
||||
opt.freeze,
|
||||
)
|
||||
callbacks.run("on_pretrain_routine_start")
|
||||
|
||||
# Directories
|
||||
w = save_dir / "weights" # weights dir
|
||||
(w.parent if evolve else w).mkdir(parents=True, exist_ok=True) # make dir
|
||||
last, best = w / "last.pt", w / "best.pt"
|
||||
|
||||
# Hyperparameters
|
||||
if isinstance(hyp, str):
|
||||
with open(hyp, errors="ignore") as f:
|
||||
hyp = yaml.safe_load(f) # load hyps dict
|
||||
LOGGER.info(colorstr("hyperparameters: ") + ", ".join(f"{k}={v}" for k, v in hyp.items()))
|
||||
opt.hyp = hyp.copy() # for saving hyps to checkpoints
|
||||
|
||||
# Save run settings
|
||||
if not evolve:
|
||||
yaml_save(save_dir / "hyp.yaml", hyp)
|
||||
yaml_save(save_dir / "opt.yaml", vars(opt))
|
||||
|
||||
# Loggers
|
||||
data_dict = None
|
||||
if RANK in {-1, 0}:
|
||||
include_loggers = list(LOGGERS)
|
||||
if getattr(opt, "ndjson_console", False):
|
||||
include_loggers.append("ndjson_console")
|
||||
if getattr(opt, "ndjson_file", False):
|
||||
include_loggers.append("ndjson_file")
|
||||
|
||||
loggers = Loggers(
|
||||
save_dir=save_dir,
|
||||
weights=weights,
|
||||
opt=opt,
|
||||
hyp=hyp,
|
||||
logger=LOGGER,
|
||||
include=tuple(include_loggers),
|
||||
)
|
||||
|
||||
# Register actions
|
||||
for k in methods(loggers):
|
||||
callbacks.register_action(k, callback=getattr(loggers, k))
|
||||
|
||||
# Process custom dataset artifact link
|
||||
data_dict = loggers.remote_dataset
|
||||
if resume: # If resuming runs from remote artifact
|
||||
weights, epochs, hyp, batch_size = opt.weights, opt.epochs, opt.hyp, opt.batch_size
|
||||
|
||||
# Config
|
||||
plots = not evolve and not opt.noplots # create plots
|
||||
cuda = device.type != "cpu"
|
||||
init_seeds(opt.seed + 1 + RANK, deterministic=True)
|
||||
with torch_distributed_zero_first(LOCAL_RANK):
|
||||
data_dict = data_dict or check_dataset(data) # check if None
|
||||
train_path, val_path = data_dict["train"], data_dict["val"]
|
||||
nc = 1 if single_cls else int(data_dict["nc"]) # number of classes
|
||||
names = {0: "item"} if single_cls and len(data_dict["names"]) != 1 else data_dict["names"] # class names
|
||||
is_coco = isinstance(val_path, str) and val_path.endswith("coco/val2017.txt") # COCO dataset
|
||||
|
||||
# Model
|
||||
check_suffix(weights, ".pt") # check weights
|
||||
pretrained = weights.endswith(".pt")
|
||||
if pretrained:
|
||||
with torch_distributed_zero_first(LOCAL_RANK):
|
||||
weights = attempt_download(weights) # download if not found locally
|
||||
ckpt = torch.load(weights, map_location="cpu") # load checkpoint to CPU to avoid CUDA memory leak
|
||||
model = Model(cfg or ckpt["model"].yaml, ch=3, nc=nc, anchors=hyp.get("anchors")).to(device) # create
|
||||
exclude = ["anchor"] if (cfg or hyp.get("anchors")) and not resume else [] # exclude keys
|
||||
csd = ckpt["model"].float().state_dict() # checkpoint state_dict as FP32
|
||||
csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect
|
||||
model.load_state_dict(csd, strict=False) # load
|
||||
LOGGER.info(f"Transferred {len(csd)}/{len(model.state_dict())} items from {weights}") # report
|
||||
else:
|
||||
model = Model(cfg, ch=3, nc=nc, anchors=hyp.get("anchors")).to(device) # create
|
||||
amp = check_amp(model) # check AMP
|
||||
|
||||
# Freeze
|
||||
freeze = [f"model.{x}." for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze
|
||||
for k, v in model.named_parameters():
|
||||
v.requires_grad = True # train all layers
|
||||
# v.register_hook(lambda x: torch.nan_to_num(x)) # NaN to 0 (commented for erratic training results)
|
||||
if any(x in k for x in freeze):
|
||||
LOGGER.info(f"freezing {k}")
|
||||
v.requires_grad = False
|
||||
|
||||
# Image size
|
||||
gs = max(int(model.stride.max()), 32) # grid size (max stride)
|
||||
imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple
|
||||
|
||||
# Batch size
|
||||
if RANK == -1 and batch_size == -1: # single-GPU only, estimate best batch size
|
||||
batch_size = check_train_batch_size(model, imgsz, amp)
|
||||
loggers.on_params_update({"batch_size": batch_size})
|
||||
|
||||
# Optimizer
|
||||
nbs = 64 # nominal batch size
|
||||
accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing
|
||||
hyp["weight_decay"] *= batch_size * accumulate / nbs # scale weight_decay
|
||||
optimizer = smart_optimizer(model, opt.optimizer, hyp["lr0"], hyp["momentum"], hyp["weight_decay"])
|
||||
|
||||
# Scheduler
|
||||
if opt.cos_lr:
|
||||
lf = one_cycle(1, hyp["lrf"], epochs) # cosine 1->hyp['lrf']
|
||||
else:
|
||||
|
||||
def lf(x):
|
||||
"""Linear learning rate scheduler function with decay calculated by epoch proportion."""
|
||||
return (1 - x / epochs) * (1.0 - hyp["lrf"]) + hyp["lrf"] # linear
|
||||
|
||||
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
|
||||
|
||||
# EMA
|
||||
ema = ModelEMA(model) if RANK in {-1, 0} else None
|
||||
|
||||
# Resume
|
||||
best_fitness, start_epoch = 0.0, 0
|
||||
if pretrained:
|
||||
if resume:
|
||||
best_fitness, start_epoch, epochs = smart_resume(ckpt, optimizer, ema, weights, epochs, resume)
|
||||
del ckpt, csd
|
||||
|
||||
# DP mode
|
||||
if cuda and RANK == -1 and torch.cuda.device_count() > 1:
|
||||
LOGGER.warning(
|
||||
"WARNING ⚠️ DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n"
|
||||
"See Multi-GPU Tutorial at https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training to get started."
|
||||
)
|
||||
model = torch.nn.DataParallel(model)
|
||||
|
||||
# SyncBatchNorm
|
||||
if opt.sync_bn and cuda and RANK != -1:
|
||||
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
|
||||
LOGGER.info("Using SyncBatchNorm()")
|
||||
|
||||
# Trainloader
|
||||
train_loader, dataset = create_dataloader(
|
||||
train_path,
|
||||
imgsz,
|
||||
batch_size // WORLD_SIZE,
|
||||
gs,
|
||||
single_cls,
|
||||
hyp=hyp,
|
||||
augment=True,
|
||||
cache=None if opt.cache == "val" else opt.cache,
|
||||
rect=opt.rect,
|
||||
rank=LOCAL_RANK,
|
||||
workers=workers,
|
||||
image_weights=opt.image_weights,
|
||||
quad=opt.quad,
|
||||
prefix=colorstr("train: "),
|
||||
shuffle=True,
|
||||
seed=opt.seed,
|
||||
)
|
||||
labels = np.concatenate(dataset.labels, 0)
|
||||
mlc = int(labels[:, 0].max()) # max label class
|
||||
assert mlc < nc, f"Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}"
|
||||
|
||||
# Process 0
|
||||
if RANK in {-1, 0}:
|
||||
val_loader = create_dataloader(
|
||||
val_path,
|
||||
imgsz,
|
||||
batch_size // WORLD_SIZE * 2,
|
||||
gs,
|
||||
single_cls,
|
||||
hyp=hyp,
|
||||
cache=None if noval else opt.cache,
|
||||
rect=True,
|
||||
rank=-1,
|
||||
workers=workers * 2,
|
||||
pad=0.5,
|
||||
prefix=colorstr("val: "),
|
||||
)[0]
|
||||
|
||||
if not resume:
|
||||
if not opt.noautoanchor:
|
||||
check_anchors(dataset, model=model, thr=hyp["anchor_t"], imgsz=imgsz) # run AutoAnchor
|
||||
model.half().float() # pre-reduce anchor precision
|
||||
|
||||
callbacks.run("on_pretrain_routine_end", labels, names)
|
||||
|
||||
# DDP mode
|
||||
if cuda and RANK != -1:
|
||||
model = smart_DDP(model)
|
||||
|
||||
# Model attributes
|
||||
nl = de_parallel(model).model[-1].nl # number of detection layers (to scale hyps)
|
||||
hyp["box"] *= 3 / nl # scale to layers
|
||||
hyp["cls"] *= nc / 80 * 3 / nl # scale to classes and layers
|
||||
hyp["obj"] *= (imgsz / 640) ** 2 * 3 / nl # scale to image size and layers
|
||||
hyp["label_smoothing"] = opt.label_smoothing
|
||||
model.nc = nc # attach number of classes to model
|
||||
model.hyp = hyp # attach hyperparameters to model
|
||||
model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
|
||||
model.names = names
|
||||
|
||||
# Start training
|
||||
t0 = time.time()
|
||||
nb = len(train_loader) # number of batches
|
||||
nw = max(round(hyp["warmup_epochs"] * nb), 100) # number of warmup iterations, max(3 epochs, 100 iterations)
|
||||
# nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
|
||||
last_opt_step = -1
|
||||
maps = np.zeros(nc) # mAP per class
|
||||
results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls)
|
||||
scheduler.last_epoch = start_epoch - 1 # do not move
|
||||
scaler = torch.cuda.amp.GradScaler(enabled=amp)
|
||||
stopper, stop = EarlyStopping(patience=opt.patience), False
|
||||
compute_loss = ComputeLoss(model) # init loss class
|
||||
callbacks.run("on_train_start")
|
||||
LOGGER.info(
|
||||
f"Image sizes {imgsz} train, {imgsz} val\n"
|
||||
f"Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n"
|
||||
f"Logging results to {colorstr('bold', save_dir)}\n"
|
||||
f"Starting training for {epochs} epochs..."
|
||||
)
|
||||
for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
|
||||
callbacks.run("on_train_epoch_start")
|
||||
model.train()
|
||||
|
||||
# Update image weights (optional, single-GPU only)
|
||||
if opt.image_weights:
|
||||
cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
|
||||
iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
|
||||
dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
|
||||
|
||||
# Update mosaic border (optional)
|
||||
# b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
|
||||
# dataset.mosaic_border = [b - imgsz, -b] # height, width borders
|
||||
|
||||
mloss = torch.zeros(3, device=device) # mean losses
|
||||
if RANK != -1:
|
||||
train_loader.sampler.set_epoch(epoch)
|
||||
pbar = enumerate(train_loader)
|
||||
LOGGER.info(("\n" + "%11s" * 7) % ("Epoch", "GPU_mem", "box_loss", "obj_loss", "cls_loss", "Instances", "Size"))
|
||||
if RANK in {-1, 0}:
|
||||
pbar = tqdm(pbar, total=nb, bar_format=TQDM_BAR_FORMAT) # progress bar
|
||||
optimizer.zero_grad()
|
||||
for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
|
||||
callbacks.run("on_train_batch_start")
|
||||
ni = i + nb * epoch # number integrated batches (since train start)
|
||||
imgs = imgs.to(device, non_blocking=True).float() / 255 # uint8 to float32, 0-255 to 0.0-1.0
|
||||
|
||||
# Warmup
|
||||
if ni <= nw:
|
||||
xi = [0, nw] # x interp
|
||||
# compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
|
||||
accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
|
||||
for j, x in enumerate(optimizer.param_groups):
|
||||
# bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
|
||||
x["lr"] = np.interp(ni, xi, [hyp["warmup_bias_lr"] if j == 0 else 0.0, x["initial_lr"] * lf(epoch)])
|
||||
if "momentum" in x:
|
||||
x["momentum"] = np.interp(ni, xi, [hyp["warmup_momentum"], hyp["momentum"]])
|
||||
|
||||
# Multi-scale
|
||||
if opt.multi_scale:
|
||||
sz = random.randrange(int(imgsz * 0.5), int(imgsz * 1.5) + gs) // gs * gs # size
|
||||
sf = sz / max(imgs.shape[2:]) # scale factor
|
||||
if sf != 1:
|
||||
ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
|
||||
imgs = nn.functional.interpolate(imgs, size=ns, mode="bilinear", align_corners=False)
|
||||
|
||||
# Forward
|
||||
with torch.cuda.amp.autocast(amp):
|
||||
pred = model(imgs) # forward
|
||||
loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size
|
||||
if RANK != -1:
|
||||
loss *= WORLD_SIZE # gradient averaged between devices in DDP mode
|
||||
if opt.quad:
|
||||
loss *= 4.0
|
||||
|
||||
# Backward
|
||||
scaler.scale(loss).backward()
|
||||
|
||||
# Optimize - https://pytorch.org/docs/master/notes/amp_examples.html
|
||||
if ni - last_opt_step >= accumulate:
|
||||
scaler.unscale_(optimizer) # unscale gradients
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients
|
||||
scaler.step(optimizer) # optimizer.step
|
||||
scaler.update()
|
||||
optimizer.zero_grad()
|
||||
if ema:
|
||||
ema.update(model)
|
||||
last_opt_step = ni
|
||||
|
||||
# Log
|
||||
if RANK in {-1, 0}:
|
||||
mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
|
||||
mem = f"{torch.cuda.memory_reserved() / 1e9 if torch.cuda.is_available() else 0:.3g}G" # (GB)
|
||||
pbar.set_description(
|
||||
("%11s" * 2 + "%11.4g" * 5)
|
||||
% (f"{epoch}/{epochs - 1}", mem, *mloss, targets.shape[0], imgs.shape[-1])
|
||||
)
|
||||
callbacks.run("on_train_batch_end", model, ni, imgs, targets, paths, list(mloss))
|
||||
if callbacks.stop_training:
|
||||
return
|
||||
# end batch ------------------------------------------------------------------------------------------------
|
||||
|
||||
# Scheduler
|
||||
lr = [x["lr"] for x in optimizer.param_groups] # for loggers
|
||||
scheduler.step()
|
||||
|
||||
if RANK in {-1, 0}:
|
||||
# mAP
|
||||
callbacks.run("on_train_epoch_end", epoch=epoch)
|
||||
ema.update_attr(model, include=["yaml", "nc", "hyp", "names", "stride", "class_weights"])
|
||||
final_epoch = (epoch + 1 == epochs) or stopper.possible_stop
|
||||
if not noval or final_epoch: # Calculate mAP
|
||||
results, maps, _ = validate.run(
|
||||
data_dict,
|
||||
batch_size=batch_size // WORLD_SIZE * 2,
|
||||
imgsz=imgsz,
|
||||
half=amp,
|
||||
model=ema.ema,
|
||||
single_cls=single_cls,
|
||||
dataloader=val_loader,
|
||||
save_dir=save_dir,
|
||||
plots=False,
|
||||
callbacks=callbacks,
|
||||
compute_loss=compute_loss,
|
||||
)
|
||||
|
||||
# Update best mAP
|
||||
fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
|
||||
stop = stopper(epoch=epoch, fitness=fi) # early stop check
|
||||
if fi > best_fitness:
|
||||
best_fitness = fi
|
||||
log_vals = list(mloss) + list(results) + lr
|
||||
callbacks.run("on_fit_epoch_end", log_vals, epoch, best_fitness, fi)
|
||||
|
||||
# Save model
|
||||
if (not nosave) or (final_epoch and not evolve): # if save
|
||||
ckpt = {
|
||||
"epoch": epoch,
|
||||
"best_fitness": best_fitness,
|
||||
"model": deepcopy(de_parallel(model)).half(),
|
||||
"ema": deepcopy(ema.ema).half(),
|
||||
"updates": ema.updates,
|
||||
"optimizer": optimizer.state_dict(),
|
||||
"opt": vars(opt),
|
||||
"git": GIT_INFO, # {remote, branch, commit} if a git repo
|
||||
"date": datetime.now().isoformat(),
|
||||
}
|
||||
|
||||
# Save last, best and delete
|
||||
torch.save(ckpt, last)
|
||||
if best_fitness == fi:
|
||||
torch.save(ckpt, best)
|
||||
if opt.save_period > 0 and epoch % opt.save_period == 0:
|
||||
torch.save(ckpt, w / f"epoch{epoch}.pt")
|
||||
del ckpt
|
||||
callbacks.run("on_model_save", last, epoch, final_epoch, best_fitness, fi)
|
||||
|
||||
# EarlyStopping
|
||||
if RANK != -1: # if DDP training
|
||||
broadcast_list = [stop if RANK == 0 else None]
|
||||
dist.broadcast_object_list(broadcast_list, 0) # broadcast 'stop' to all ranks
|
||||
if RANK != 0:
|
||||
stop = broadcast_list[0]
|
||||
if stop:
|
||||
break # must break all DDP ranks
|
||||
|
||||
# end epoch ----------------------------------------------------------------------------------------------------
|
||||
# end training -----------------------------------------------------------------------------------------------------
|
||||
if RANK in {-1, 0}:
|
||||
LOGGER.info(f"\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.")
|
||||
for f in last, best:
|
||||
if f.exists():
|
||||
strip_optimizer(f) # strip optimizers
|
||||
if f is best:
|
||||
LOGGER.info(f"\nValidating {f}...")
|
||||
results, _, _ = validate.run(
|
||||
data_dict,
|
||||
batch_size=batch_size // WORLD_SIZE * 2,
|
||||
imgsz=imgsz,
|
||||
model=attempt_load(f, device).half(),
|
||||
iou_thres=0.65 if is_coco else 0.60, # best pycocotools at iou 0.65
|
||||
single_cls=single_cls,
|
||||
dataloader=val_loader,
|
||||
save_dir=save_dir,
|
||||
save_json=is_coco,
|
||||
verbose=True,
|
||||
plots=plots,
|
||||
callbacks=callbacks,
|
||||
compute_loss=compute_loss,
|
||||
) # val best model with plots
|
||||
if is_coco:
|
||||
callbacks.run("on_fit_epoch_end", list(mloss) + list(results) + lr, epoch, best_fitness, fi)
|
||||
|
||||
callbacks.run("on_train_end", last, best, epoch, results)
|
||||
|
||||
torch.cuda.empty_cache()
|
||||
return results
|
||||
|
||||
|
||||
def parse_opt(known=False):
|
||||
"""
|
||||
Parse command-line arguments for YOLOv5 training, validation, and testing.
|
||||
|
||||
Args:
|
||||
known (bool, optional): If True, parses known arguments, ignoring the unknown. Defaults to False.
|
||||
|
||||
Returns:
|
||||
(argparse.Namespace): Parsed command-line arguments containing options for YOLOv5 execution.
|
||||
|
||||
Example:
|
||||
```python
|
||||
from ultralytics.yolo import parse_opt
|
||||
opt = parse_opt()
|
||||
print(opt)
|
||||
```
|
||||
|
||||
Links:
|
||||
- Models: https://github.com/ultralytics/yolov5/tree/master/models
|
||||
- Datasets: https://github.com/ultralytics/yolov5/tree/master/data
|
||||
- Tutorial: https://docs.ultralytics.com/yolov5/tutorials/train_custom_data
|
||||
"""
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--weights", type=str, default=ROOT / "yolov5s.pt", help="initial weights path")
|
||||
parser.add_argument("--cfg", type=str, default="", help="model.yaml path")
|
||||
parser.add_argument("--data", type=str, default=ROOT / "data/5t5.yaml", help="dataset.yaml path")
|
||||
parser.add_argument("--hyp", type=str, default=ROOT / "data/hyps/hyp.scratch-low.yaml", help="hyperparameters path")
|
||||
parser.add_argument("--epochs", type=int, default=100, help="total training epochs")
|
||||
parser.add_argument("--batch-size", type=int, default=16, help="total batch size for all GPUs, -1 for autobatch")
|
||||
parser.add_argument("--imgsz", "--img", "--img-size", type=int, default=640, help="train, val image size (pixels)")
|
||||
parser.add_argument("--rect", action="store_true", help="rectangular training")
|
||||
parser.add_argument("--resume", nargs="?", const=True, default=False, help="resume most recent training")
|
||||
parser.add_argument("--nosave", action="store_true", help="only save final checkpoint")
|
||||
parser.add_argument("--noval", action="store_true", help="only validate final epoch")
|
||||
parser.add_argument("--noautoanchor", action="store_true", help="disable AutoAnchor")
|
||||
parser.add_argument("--noplots", action="store_true", help="save no plot files")
|
||||
parser.add_argument("--evolve", type=int, nargs="?", const=300, help="evolve hyperparameters for x generations")
|
||||
parser.add_argument(
|
||||
"--evolve_population", type=str, default=ROOT / "data/hyps", help="location for loading population"
|
||||
)
|
||||
parser.add_argument("--resume_evolve", type=str, default=None, help="resume evolve from last generation")
|
||||
parser.add_argument("--bucket", type=str, default="", help="gsutil bucket")
|
||||
parser.add_argument("--cache", type=str, nargs="?", const="ram", help="image --cache ram/disk")
|
||||
parser.add_argument("--image-weights", action="store_true", help="use weighted image selection for training")
|
||||
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
||||
parser.add_argument("--multi-scale", action="store_true", help="vary img-size +/- 50%%")
|
||||
parser.add_argument("--single-cls", action="store_true", help="train multi-class data as single-class")
|
||||
parser.add_argument("--optimizer", type=str, choices=["SGD", "Adam", "AdamW"], default="SGD", help="optimizer")
|
||||
parser.add_argument("--sync-bn", action="store_true", help="use SyncBatchNorm, only available in DDP mode")
|
||||
parser.add_argument("--workers", type=int, default=8, help="max dataloader workers (per RANK in DDP mode)")
|
||||
parser.add_argument("--project", default=ROOT / "runs/train", help="save to project/name")
|
||||
parser.add_argument("--name", default="exp", help="save to project/name")
|
||||
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
|
||||
parser.add_argument("--quad", action="store_true", help="quad dataloader")
|
||||
parser.add_argument("--cos-lr", action="store_true", help="cosine LR scheduler")
|
||||
parser.add_argument("--label-smoothing", type=float, default=0.0, help="Label smoothing epsilon")
|
||||
parser.add_argument("--patience", type=int, default=100, help="EarlyStopping patience (epochs without improvement)")
|
||||
parser.add_argument("--freeze", nargs="+", type=int, default=[0], help="Freeze layers: backbone=10, first3=0 1 2")
|
||||
parser.add_argument("--save-period", type=int, default=-1, help="Save checkpoint every x epochs (disabled if < 1)")
|
||||
parser.add_argument("--seed", type=int, default=0, help="Global training seed")
|
||||
parser.add_argument("--local_rank", type=int, default=-1, help="Automatic DDP Multi-GPU argument, do not modify")
|
||||
|
||||
# Logger arguments
|
||||
parser.add_argument("--entity", default=None, help="Entity")
|
||||
parser.add_argument("--upload_dataset", nargs="?", const=True, default=False, help='Upload data, "val" option')
|
||||
parser.add_argument("--bbox_interval", type=int, default=-1, help="Set bounding-box image logging interval")
|
||||
parser.add_argument("--artifact_alias", type=str, default="latest", help="Version of dataset artifact to use")
|
||||
|
||||
# NDJSON logging
|
||||
parser.add_argument("--ndjson-console", action="store_true", help="Log ndjson to console")
|
||||
parser.add_argument("--ndjson-file", action="store_true", help="Log ndjson to file")
|
||||
|
||||
return parser.parse_known_args()[0] if known else parser.parse_args()
|
||||
|
||||
|
||||
def main(opt, callbacks=Callbacks()):
|
||||
"""
|
||||
Runs the main entry point for training or hyperparameter evolution with specified options and optional callbacks.
|
||||
|
||||
Args:
|
||||
opt (argparse.Namespace): The command-line arguments parsed for YOLOv5 training and evolution.
|
||||
callbacks (ultralytics.utils.callbacks.Callbacks, optional): Callback functions for various training stages.
|
||||
Defaults to Callbacks().
|
||||
|
||||
Returns:
|
||||
None
|
||||
|
||||
Note:
|
||||
For detailed usage, refer to:
|
||||
https://github.com/ultralytics/yolov5/tree/master/models
|
||||
"""
|
||||
if RANK in {-1, 0}:
|
||||
print_args(vars(opt))
|
||||
check_git_status()
|
||||
check_requirements(ROOT / "requirements.txt")
|
||||
|
||||
# Resume (from specified or most recent last.pt)
|
||||
if opt.resume and not check_comet_resume(opt) and not opt.evolve:
|
||||
last = Path(check_file(opt.resume) if isinstance(opt.resume, str) else get_latest_run())
|
||||
opt_yaml = last.parent.parent / "opt.yaml" # train options yaml
|
||||
opt_data = opt.data # original dataset
|
||||
if opt_yaml.is_file():
|
||||
with open(opt_yaml, errors="ignore") as f:
|
||||
d = yaml.safe_load(f)
|
||||
else:
|
||||
d = torch.load(last, map_location="cpu")["opt"]
|
||||
opt = argparse.Namespace(**d) # replace
|
||||
opt.cfg, opt.weights, opt.resume = "", str(last), True # reinstate
|
||||
if is_url(opt_data):
|
||||
opt.data = check_file(opt_data) # avoid HUB resume auth timeout
|
||||
else:
|
||||
opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = (
|
||||
check_file(opt.data),
|
||||
check_yaml(opt.cfg),
|
||||
check_yaml(opt.hyp),
|
||||
str(opt.weights),
|
||||
str(opt.project),
|
||||
) # checks
|
||||
assert len(opt.cfg) or len(opt.weights), "either --cfg or --weights must be specified"
|
||||
if opt.evolve:
|
||||
if opt.project == str(ROOT / "runs/train"): # if default project name, rename to runs/evolve
|
||||
opt.project = str(ROOT / "runs/evolve")
|
||||
opt.exist_ok, opt.resume = opt.resume, False # pass resume to exist_ok and disable resume
|
||||
if opt.name == "cfg":
|
||||
opt.name = Path(opt.cfg).stem # use model.yaml as name
|
||||
opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
|
||||
|
||||
# DDP mode
|
||||
device = select_device(opt.device, batch_size=opt.batch_size)
|
||||
if LOCAL_RANK != -1:
|
||||
msg = "is not compatible with YOLOv5 Multi-GPU DDP training"
|
||||
assert not opt.image_weights, f"--image-weights {msg}"
|
||||
assert not opt.evolve, f"--evolve {msg}"
|
||||
assert opt.batch_size != -1, f"AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size"
|
||||
assert opt.batch_size % WORLD_SIZE == 0, f"--batch-size {opt.batch_size} must be multiple of WORLD_SIZE"
|
||||
assert torch.cuda.device_count() > LOCAL_RANK, "insufficient CUDA devices for DDP command"
|
||||
torch.cuda.set_device(LOCAL_RANK)
|
||||
device = torch.device("cuda", LOCAL_RANK)
|
||||
dist.init_process_group(
|
||||
backend="nccl" if dist.is_nccl_available() else "gloo", timeout=timedelta(seconds=10800)
|
||||
)
|
||||
|
||||
# Train
|
||||
if not opt.evolve:
|
||||
train(opt.hyp, opt, device, callbacks)
|
||||
|
||||
# Evolve hyperparameters (optional)
|
||||
else:
|
||||
# Hyperparameter evolution metadata (including this hyperparameter True-False, lower_limit, upper_limit)
|
||||
meta = {
|
||||
"lr0": (False, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
|
||||
"lrf": (False, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
|
||||
"momentum": (False, 0.6, 0.98), # SGD momentum/Adam beta1
|
||||
"weight_decay": (False, 0.0, 0.001), # optimizer weight decay
|
||||
"warmup_epochs": (False, 0.0, 5.0), # warmup epochs (fractions ok)
|
||||
"warmup_momentum": (False, 0.0, 0.95), # warmup initial momentum
|
||||
"warmup_bias_lr": (False, 0.0, 0.2), # warmup initial bias lr
|
||||
"box": (False, 0.02, 0.2), # box loss gain
|
||||
"cls": (False, 0.2, 4.0), # cls loss gain
|
||||
"cls_pw": (False, 0.5, 2.0), # cls BCELoss positive_weight
|
||||
"obj": (False, 0.2, 4.0), # obj loss gain (scale with pixels)
|
||||
"obj_pw": (False, 0.5, 2.0), # obj BCELoss positive_weight
|
||||
"iou_t": (False, 0.1, 0.7), # IoU training threshold
|
||||
"anchor_t": (False, 2.0, 8.0), # anchor-multiple threshold
|
||||
"anchors": (False, 2.0, 10.0), # anchors per output grid (0 to ignore)
|
||||
"fl_gamma": (False, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
|
||||
"hsv_h": (True, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
|
||||
"hsv_s": (True, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
|
||||
"hsv_v": (True, 0.0, 0.9), # image HSV-Value augmentation (fraction)
|
||||
"degrees": (True, 0.0, 45.0), # image rotation (+/- deg)
|
||||
"translate": (True, 0.0, 0.9), # image translation (+/- fraction)
|
||||
"scale": (True, 0.0, 0.9), # image scale (+/- gain)
|
||||
"shear": (True, 0.0, 10.0), # image shear (+/- deg)
|
||||
"perspective": (True, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
|
||||
"flipud": (True, 0.0, 1.0), # image flip up-down (probability)
|
||||
"fliplr": (True, 0.0, 1.0), # image flip left-right (probability)
|
||||
"mosaic": (True, 0.0, 1.0), # image mosaic (probability)
|
||||
"mixup": (True, 0.0, 1.0), # image mixup (probability)
|
||||
"copy_paste": (True, 0.0, 1.0), # segment copy-paste (probability)
|
||||
}
|
||||
|
||||
# GA configs
|
||||
pop_size = 50
|
||||
mutation_rate_min = 0.01
|
||||
mutation_rate_max = 0.5
|
||||
crossover_rate_min = 0.5
|
||||
crossover_rate_max = 1
|
||||
min_elite_size = 2
|
||||
max_elite_size = 5
|
||||
tournament_size_min = 2
|
||||
tournament_size_max = 10
|
||||
|
||||
with open(opt.hyp, errors="ignore") as f:
|
||||
hyp = yaml.safe_load(f) # load hyps dict
|
||||
if "anchors" not in hyp: # anchors commented in hyp.yaml
|
||||
hyp["anchors"] = 3
|
||||
if opt.noautoanchor:
|
||||
del hyp["anchors"], meta["anchors"]
|
||||
opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) # only val/save final epoch
|
||||
# ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
|
||||
evolve_yaml, evolve_csv = save_dir / "hyp_evolve.yaml", save_dir / "evolve.csv"
|
||||
if opt.bucket:
|
||||
# download evolve.csv if exists
|
||||
subprocess.run(
|
||||
[
|
||||
"gsutil",
|
||||
"cp",
|
||||
f"gs://{opt.bucket}/evolve.csv",
|
||||
str(evolve_csv),
|
||||
]
|
||||
)
|
||||
|
||||
# Delete the items in meta dictionary whose first value is False
|
||||
del_ = [item for item, value_ in meta.items() if value_[0] is False]
|
||||
hyp_GA = hyp.copy() # Make a copy of hyp dictionary
|
||||
for item in del_:
|
||||
del meta[item] # Remove the item from meta dictionary
|
||||
del hyp_GA[item] # Remove the item from hyp_GA dictionary
|
||||
|
||||
# Set lower_limit and upper_limit arrays to hold the search space boundaries
|
||||
lower_limit = np.array([meta[k][1] for k in hyp_GA.keys()])
|
||||
upper_limit = np.array([meta[k][2] for k in hyp_GA.keys()])
|
||||
|
||||
# Create gene_ranges list to hold the range of values for each gene in the population
|
||||
gene_ranges = [(lower_limit[i], upper_limit[i]) for i in range(len(upper_limit))]
|
||||
|
||||
# Initialize the population with initial_values or random values
|
||||
initial_values = []
|
||||
|
||||
# If resuming evolution from a previous checkpoint
|
||||
if opt.resume_evolve is not None:
|
||||
assert os.path.isfile(ROOT / opt.resume_evolve), "evolve population path is wrong!"
|
||||
with open(ROOT / opt.resume_evolve, errors="ignore") as f:
|
||||
evolve_population = yaml.safe_load(f)
|
||||
for value in evolve_population.values():
|
||||
value = np.array([value[k] for k in hyp_GA.keys()])
|
||||
initial_values.append(list(value))
|
||||
|
||||
# If not resuming from a previous checkpoint, generate initial values from .yaml files in opt.evolve_population
|
||||
else:
|
||||
yaml_files = [f for f in os.listdir(opt.evolve_population) if f.endswith(".yaml")]
|
||||
for file_name in yaml_files:
|
||||
with open(os.path.join(opt.evolve_population, file_name)) as yaml_file:
|
||||
value = yaml.safe_load(yaml_file)
|
||||
value = np.array([value[k] for k in hyp_GA.keys()])
|
||||
initial_values.append(list(value))
|
||||
|
||||
# Generate random values within the search space for the rest of the population
|
||||
if initial_values is None:
|
||||
population = [generate_individual(gene_ranges, len(hyp_GA)) for _ in range(pop_size)]
|
||||
elif pop_size > 1:
|
||||
population = [generate_individual(gene_ranges, len(hyp_GA)) for _ in range(pop_size - len(initial_values))]
|
||||
for initial_value in initial_values:
|
||||
population = [initial_value] + population
|
||||
|
||||
# Run the genetic algorithm for a fixed number of generations
|
||||
list_keys = list(hyp_GA.keys())
|
||||
for generation in range(opt.evolve):
|
||||
if generation >= 1:
|
||||
save_dict = {}
|
||||
for i in range(len(population)):
|
||||
little_dict = {list_keys[j]: float(population[i][j]) for j in range(len(population[i]))}
|
||||
save_dict[f"gen{str(generation)}number{str(i)}"] = little_dict
|
||||
|
||||
with open(save_dir / "evolve_population.yaml", "w") as outfile:
|
||||
yaml.dump(save_dict, outfile, default_flow_style=False)
|
||||
|
||||
# Adaptive elite size
|
||||
elite_size = min_elite_size + int((max_elite_size - min_elite_size) * (generation / opt.evolve))
|
||||
# Evaluate the fitness of each individual in the population
|
||||
fitness_scores = []
|
||||
for individual in population:
|
||||
for key, value in zip(hyp_GA.keys(), individual):
|
||||
hyp_GA[key] = value
|
||||
hyp.update(hyp_GA)
|
||||
results = train(hyp.copy(), opt, device, callbacks)
|
||||
callbacks = Callbacks()
|
||||
# Write mutation results
|
||||
keys = (
|
||||
"metrics/precision",
|
||||
"metrics/recall",
|
||||
"metrics/mAP_0.5",
|
||||
"metrics/mAP_0.5:0.95",
|
||||
"val/box_loss",
|
||||
"val/obj_loss",
|
||||
"val/cls_loss",
|
||||
)
|
||||
print_mutation(keys, results, hyp.copy(), save_dir, opt.bucket)
|
||||
fitness_scores.append(results[2])
|
||||
|
||||
# Select the fittest individuals for reproduction using adaptive tournament selection
|
||||
selected_indices = []
|
||||
for _ in range(pop_size - elite_size):
|
||||
# Adaptive tournament size
|
||||
tournament_size = max(
|
||||
max(2, tournament_size_min),
|
||||
int(min(tournament_size_max, pop_size) - (generation / (opt.evolve / 10))),
|
||||
)
|
||||
# Perform tournament selection to choose the best individual
|
||||
tournament_indices = random.sample(range(pop_size), tournament_size)
|
||||
tournament_fitness = [fitness_scores[j] for j in tournament_indices]
|
||||
winner_index = tournament_indices[tournament_fitness.index(max(tournament_fitness))]
|
||||
selected_indices.append(winner_index)
|
||||
|
||||
# Add the elite individuals to the selected indices
|
||||
elite_indices = [i for i in range(pop_size) if fitness_scores[i] in sorted(fitness_scores)[-elite_size:]]
|
||||
selected_indices.extend(elite_indices)
|
||||
# Create the next generation through crossover and mutation
|
||||
next_generation = []
|
||||
for _ in range(pop_size):
|
||||
parent1_index = selected_indices[random.randint(0, pop_size - 1)]
|
||||
parent2_index = selected_indices[random.randint(0, pop_size - 1)]
|
||||
# Adaptive crossover rate
|
||||
crossover_rate = max(
|
||||
crossover_rate_min, min(crossover_rate_max, crossover_rate_max - (generation / opt.evolve))
|
||||
)
|
||||
if random.uniform(0, 1) < crossover_rate:
|
||||
crossover_point = random.randint(1, len(hyp_GA) - 1)
|
||||
child = population[parent1_index][:crossover_point] + population[parent2_index][crossover_point:]
|
||||
else:
|
||||
child = population[parent1_index]
|
||||
# Adaptive mutation rate
|
||||
mutation_rate = max(
|
||||
mutation_rate_min, min(mutation_rate_max, mutation_rate_max - (generation / opt.evolve))
|
||||
)
|
||||
for j in range(len(hyp_GA)):
|
||||
if random.uniform(0, 1) < mutation_rate:
|
||||
child[j] += random.uniform(-0.1, 0.1)
|
||||
child[j] = min(max(child[j], gene_ranges[j][0]), gene_ranges[j][1])
|
||||
next_generation.append(child)
|
||||
# Replace the old population with the new generation
|
||||
population = next_generation
|
||||
# Print the best solution found
|
||||
best_index = fitness_scores.index(max(fitness_scores))
|
||||
best_individual = population[best_index]
|
||||
print("Best solution found:", best_individual)
|
||||
# Plot results
|
||||
plot_evolve(evolve_csv)
|
||||
LOGGER.info(
|
||||
f"Hyperparameter evolution finished {opt.evolve} generations\n"
|
||||
f"Results saved to {colorstr('bold', save_dir)}\n"
|
||||
f"Usage example: $ python train.py --hyp {evolve_yaml}"
|
||||
)
|
||||
|
||||
|
||||
def generate_individual(input_ranges, individual_length):
|
||||
"""
|
||||
Generate an individual with random hyperparameters within specified ranges.
|
||||
|
||||
Args:
|
||||
input_ranges (list[tuple[float, float]]): List of tuples where each tuple contains the lower and upper bounds
|
||||
for the corresponding gene (hyperparameter).
|
||||
individual_length (int): The number of genes (hyperparameters) in the individual.
|
||||
|
||||
Returns:
|
||||
list[float]: A list representing a generated individual with random gene values within the specified ranges.
|
||||
|
||||
Example:
|
||||
```python
|
||||
input_ranges = [(0.01, 0.1), (0.1, 1.0), (0.9, 2.0)]
|
||||
individual_length = 3
|
||||
individual = generate_individual(input_ranges, individual_length)
|
||||
print(individual) # Output: [0.035, 0.678, 1.456] (example output)
|
||||
```
|
||||
|
||||
Note:
|
||||
The individual returned will have a length equal to `individual_length`, with each gene value being a floating-point
|
||||
number within its specified range in `input_ranges`.
|
||||
"""
|
||||
individual = []
|
||||
for i in range(individual_length):
|
||||
lower_bound, upper_bound = input_ranges[i]
|
||||
individual.append(random.uniform(lower_bound, upper_bound))
|
||||
return individual
|
||||
|
||||
|
||||
def run(**kwargs):
|
||||
"""
|
||||
Execute YOLOv5 training with specified options, allowing optional overrides through keyword arguments.
|
||||
|
||||
Args:
|
||||
weights (str, optional): Path to initial weights. Defaults to ROOT / 'yolov5s.pt'.
|
||||
cfg (str, optional): Path to model YAML configuration. Defaults to an empty string.
|
||||
data (str, optional): Path to dataset YAML configuration. Defaults to ROOT / 'data/coco128.yaml'.
|
||||
hyp (str, optional): Path to hyperparameters YAML configuration. Defaults to ROOT / 'data/hyps/hyp.scratch-low.yaml'.
|
||||
epochs (int, optional): Total number of training epochs. Defaults to 100.
|
||||
batch_size (int, optional): Total batch size for all GPUs. Use -1 for automatic batch size determination. Defaults to 16.
|
||||
imgsz (int, optional): Image size (pixels) for training and validation. Defaults to 640.
|
||||
rect (bool, optional): Use rectangular training. Defaults to False.
|
||||
resume (bool | str, optional): Resume most recent training with an optional path. Defaults to False.
|
||||
nosave (bool, optional): Only save the final checkpoint. Defaults to False.
|
||||
noval (bool, optional): Only validate at the final epoch. Defaults to False.
|
||||
noautoanchor (bool, optional): Disable AutoAnchor. Defaults to False.
|
||||
noplots (bool, optional): Do not save plot files. Defaults to False.
|
||||
evolve (int, optional): Evolve hyperparameters for a specified number of generations. Use 300 if provided without a
|
||||
value.
|
||||
evolve_population (str, optional): Directory for loading population during evolution. Defaults to ROOT / 'data/ hyps'.
|
||||
resume_evolve (str, optional): Resume hyperparameter evolution from the last generation. Defaults to None.
|
||||
bucket (str, optional): gsutil bucket for saving checkpoints. Defaults to an empty string.
|
||||
cache (str, optional): Cache image data in 'ram' or 'disk'. Defaults to None.
|
||||
image_weights (bool, optional): Use weighted image selection for training. Defaults to False.
|
||||
device (str, optional): CUDA device identifier, e.g., '0', '0,1,2,3', or 'cpu'. Defaults to an empty string.
|
||||
multi_scale (bool, optional): Use multi-scale training, varying image size by ±50%. Defaults to False.
|
||||
single_cls (bool, optional): Train with multi-class data as single-class. Defaults to False.
|
||||
optimizer (str, optional): Optimizer type, choices are ['SGD', 'Adam', 'AdamW']. Defaults to 'SGD'.
|
||||
sync_bn (bool, optional): Use synchronized BatchNorm, only available in DDP mode. Defaults to False.
|
||||
workers (int, optional): Maximum dataloader workers per rank in DDP mode. Defaults to 8.
|
||||
project (str, optional): Directory for saving training runs. Defaults to ROOT / 'runs/train'.
|
||||
name (str, optional): Name for saving the training run. Defaults to 'exp'.
|
||||
exist_ok (bool, optional): Allow existing project/name without incrementing. Defaults to False.
|
||||
quad (bool, optional): Use quad dataloader. Defaults to False.
|
||||
cos_lr (bool, optional): Use cosine learning rate scheduler. Defaults to False.
|
||||
label_smoothing (float, optional): Label smoothing epsilon value. Defaults to 0.0.
|
||||
patience (int, optional): Patience for early stopping, measured in epochs without improvement. Defaults to 100.
|
||||
freeze (list, optional): Layers to freeze, e.g., backbone=10, first 3 layers = [0, 1, 2]. Defaults to [0].
|
||||
save_period (int, optional): Frequency in epochs to save checkpoints. Disabled if < 1. Defaults to -1.
|
||||
seed (int, optional): Global training random seed. Defaults to 0.
|
||||
local_rank (int, optional): Automatic DDP Multi-GPU argument. Do not modify. Defaults to -1.
|
||||
|
||||
Returns:
|
||||
None: The function initiates YOLOv5 training or hyperparameter evolution based on the provided options.
|
||||
|
||||
Examples:
|
||||
```python
|
||||
import train
|
||||
train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt')
|
||||
```
|
||||
|
||||
Notes:
|
||||
- Models: https://github.com/ultralytics/yolov5/tree/master/models
|
||||
- Datasets: https://github.com/ultralytics/yolov5/tree/master/data
|
||||
- Tutorial: https://docs.ultralytics.com/yolov5/tutorials/train_custom_data
|
||||
"""
|
||||
opt = parse_opt(True)
|
||||
for k, v in kwargs.items():
|
||||
setattr(opt, k, v)
|
||||
main(opt)
|
||||
return opt
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
opt = parse_opt()
|
||||
main(opt)
|
604
yolov5/tutorial.ipynb
Normal file
604
yolov5/tutorial.ipynb
Normal file
@ -0,0 +1,604 @@
|
||||
{
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 0,
|
||||
"metadata": {
|
||||
"colab": {
|
||||
"name": "YOLOv5 Tutorial",
|
||||
"provenance": []
|
||||
},
|
||||
"kernelspec": {
|
||||
"name": "python3",
|
||||
"display_name": "Python 3"
|
||||
},
|
||||
"accelerator": "GPU"
|
||||
},
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "t6MPjfT5NrKQ"
|
||||
},
|
||||
"source": [
|
||||
"<div align=\"center\">\n",
|
||||
"\n",
|
||||
" <a href=\"https://ultralytics.com/yolov5\" target=\"_blank\">\n",
|
||||
" <img width=\"1024\", src=\"https://raw.githubusercontent.com/ultralytics/assets/main/yolov5/v70/splash.png\"></a>\n",
|
||||
"\n",
|
||||
"[中文](https://docs.ultralytics.com/zh/) | [한국어](https://docs.ultralytics.com/ko/) | [日本語](https://docs.ultralytics.com/ja/) | [Русский](https://docs.ultralytics.com/ru/) | [Deutsch](https://docs.ultralytics.com/de/) | [Français](https://docs.ultralytics.com/fr/) | [Español](https://docs.ultralytics.com/es/) | [Português](https://docs.ultralytics.com/pt/) | [العربية](https://docs.ultralytics.com/ar/)\n",
|
||||
"\n",
|
||||
" <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a>\n",
|
||||
" <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n",
|
||||
" <a href=\"https://www.kaggle.com/models/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n",
|
||||
"\n",
|
||||
"This <a href=\"https://github.com/ultralytics/yolov5\">YOLOv5</a> 🚀 notebook by <a href=\"https://ultralytics.com\">Ultralytics</a> presents simple train, validate and predict examples to help start your AI adventure.<br>We hope that the resources in this notebook will help you get the most out of YOLOv5. Please browse the YOLOv5 <a href=\"https://docs.ultralytics.com/yolov5\">Docs</a> for details, raise an issue on <a href=\"https://github.com/ultralytics/yolov5\">GitHub</a> for support, and join our <a href=\"https://ultralytics.com/discord\">Discord</a> community for questions and discussions!\n",
|
||||
"\n",
|
||||
"</div>"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "7mGmQbAO5pQb"
|
||||
},
|
||||
"source": [
|
||||
"# Setup\n",
|
||||
"\n",
|
||||
"Clone GitHub [repository](https://github.com/ultralytics/yolov5), install [dependencies](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) and check PyTorch and GPU."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {
|
||||
"id": "wbvMlHd_QwMG",
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"outputId": "e8225db4-e61d-4640-8b1f-8bfce3331cea"
|
||||
},
|
||||
"source": [
|
||||
"!git clone https://github.com/ultralytics/yolov5 # clone\n",
|
||||
"%cd yolov5\n",
|
||||
"%pip install -qr requirements.txt comet_ml # install\n",
|
||||
"\n",
|
||||
"import torch\n",
|
||||
"import utils\n",
|
||||
"display = utils.notebook_init() # checks"
|
||||
],
|
||||
"execution_count": null,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stderr",
|
||||
"text": [
|
||||
"YOLOv5 🚀 v7.0-136-g71244ae Python-3.9.16 torch-2.0.0+cu118 CUDA:0 (Tesla T4, 15102MiB)\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"text": [
|
||||
"Setup complete ✅ (2 CPUs, 12.7 GB RAM, 23.3/166.8 GB disk)\n"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "4JnkELT0cIJg"
|
||||
},
|
||||
"source": [
|
||||
"# 1. Detect\n",
|
||||
"\n",
|
||||
"`detect.py` runs YOLOv5 inference on a variety of sources, downloading models automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases), and saving results to `runs/detect`. Example inference sources are:\n",
|
||||
"\n",
|
||||
"```shell\n",
|
||||
"python detect.py --source 0 # webcam\n",
|
||||
" img.jpg # image\n",
|
||||
" vid.mp4 # video\n",
|
||||
" screen # screenshot\n",
|
||||
" path/ # directory\n",
|
||||
" 'path/*.jpg' # glob\n",
|
||||
" 'https://youtu.be/LNwODJXcvt4' # YouTube\n",
|
||||
" 'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream\n",
|
||||
"```"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {
|
||||
"id": "zR9ZbuQCH7FX",
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"outputId": "284ef04b-1596-412f-88f6-948828dd2b49"
|
||||
},
|
||||
"source": [
|
||||
"!python detect.py --weights yolov5s.pt --img 640 --conf 0.25 --source data/images\n",
|
||||
"# display.Image(filename='runs/detect/exp/zidane.jpg', width=600)"
|
||||
],
|
||||
"execution_count": null,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"text": [
|
||||
"\u001b[34m\u001b[1mdetect: \u001b[0mweights=['yolov5s.pt'], source=data/images, data=data/coco128.yaml, imgsz=[640, 640], conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, visualize=False, update=False, project=runs/detect, name=exp, exist_ok=False, line_thickness=3, hide_labels=False, hide_conf=False, half=False, dnn=False, vid_stride=1\n",
|
||||
"YOLOv5 🚀 v7.0-136-g71244ae Python-3.9.16 torch-2.0.0+cu118 CUDA:0 (Tesla T4, 15102MiB)\n",
|
||||
"\n",
|
||||
"Downloading https://github.com/ultralytics/yolov5/releases/download/v7.0/yolov5s.pt to yolov5s.pt...\n",
|
||||
"100% 14.1M/14.1M [00:00<00:00, 24.5MB/s]\n",
|
||||
"\n",
|
||||
"Fusing layers... \n",
|
||||
"YOLOv5s summary: 213 layers, 7225885 parameters, 0 gradients\n",
|
||||
"image 1/2 /content/yolov5/data/images/bus.jpg: 640x480 4 persons, 1 bus, 41.5ms\n",
|
||||
"image 2/2 /content/yolov5/data/images/zidane.jpg: 384x640 2 persons, 2 ties, 60.0ms\n",
|
||||
"Speed: 0.5ms pre-process, 50.8ms inference, 37.7ms NMS per image at shape (1, 3, 640, 640)\n",
|
||||
"Results saved to \u001b[1mruns/detect/exp\u001b[0m\n"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "hkAzDWJ7cWTr"
|
||||
},
|
||||
"source": [
|
||||
" \n",
|
||||
"<img align=\"left\" src=\"https://user-images.githubusercontent.com/26833433/127574988-6a558aa1-d268-44b9-bf6b-62d4c605cc72.jpg\" width=\"600\">"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "0eq1SMWl6Sfn"
|
||||
},
|
||||
"source": [
|
||||
"# 2. Validate\n",
|
||||
"Validate a model's accuracy on the [COCO](https://cocodataset.org/#home) dataset's `val` or `test` splits. Models are downloaded automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases). To show results by class use the `--verbose` flag."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {
|
||||
"id": "WQPtK1QYVaD_",
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"outputId": "cf7d52f0-281c-4c96-a488-79f5908f8426"
|
||||
},
|
||||
"source": [
|
||||
"# Download COCO val\n",
|
||||
"torch.hub.download_url_to_file('https://github.com/ultralytics/assets/releases/download/v0.0.0/coco2017val.zip', 'tmp.zip') # download (780M - 5000 images)\n",
|
||||
"!unzip -q tmp.zip -d ../datasets && rm tmp.zip # unzip"
|
||||
],
|
||||
"execution_count": null,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stderr",
|
||||
"text": [
|
||||
"100%|██████████| 780M/780M [00:12<00:00, 66.6MB/s]\n"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {
|
||||
"id": "X58w8JLpMnjH",
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"outputId": "3e234e05-ee8b-4ad1-b1a4-f6a55d5e4f3d"
|
||||
},
|
||||
"source": [
|
||||
"# Validate YOLOv5s on COCO val\n",
|
||||
"!python val.py --weights yolov5s.pt --data coco.yaml --img 640 --half"
|
||||
],
|
||||
"execution_count": null,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"text": [
|
||||
"\u001b[34m\u001b[1mval: \u001b[0mdata=/content/yolov5/data/coco.yaml, weights=['yolov5s.pt'], batch_size=32, imgsz=640, conf_thres=0.001, iou_thres=0.6, max_det=300, task=val, device=, workers=8, single_cls=False, augment=False, verbose=False, save_txt=False, save_hybrid=False, save_conf=False, save_json=True, project=runs/val, name=exp, exist_ok=False, half=True, dnn=False\n",
|
||||
"YOLOv5 🚀 v7.0-136-g71244ae Python-3.9.16 torch-2.0.0+cu118 CUDA:0 (Tesla T4, 15102MiB)\n",
|
||||
"\n",
|
||||
"Fusing layers... \n",
|
||||
"YOLOv5s summary: 213 layers, 7225885 parameters, 0 gradients\n",
|
||||
"\u001b[34m\u001b[1mval: \u001b[0mScanning /content/datasets/coco/val2017... 4952 images, 48 backgrounds, 0 corrupt: 100% 5000/5000 [00:02<00:00, 2024.59it/s]\n",
|
||||
"\u001b[34m\u001b[1mval: \u001b[0mNew cache created: /content/datasets/coco/val2017.cache\n",
|
||||
" Class Images Instances P R mAP50 mAP50-95: 100% 157/157 [01:25<00:00, 1.84it/s]\n",
|
||||
" all 5000 36335 0.671 0.519 0.566 0.371\n",
|
||||
"Speed: 0.1ms pre-process, 3.1ms inference, 2.3ms NMS per image at shape (32, 3, 640, 640)\n",
|
||||
"\n",
|
||||
"Evaluating pycocotools mAP... saving runs/val/exp/yolov5s_predictions.json...\n",
|
||||
"loading annotations into memory...\n",
|
||||
"Done (t=0.43s)\n",
|
||||
"creating index...\n",
|
||||
"index created!\n",
|
||||
"Loading and preparing results...\n",
|
||||
"DONE (t=5.32s)\n",
|
||||
"creating index...\n",
|
||||
"index created!\n",
|
||||
"Running per image evaluation...\n",
|
||||
"Evaluate annotation type *bbox*\n",
|
||||
"DONE (t=78.89s).\n",
|
||||
"Accumulating evaluation results...\n",
|
||||
"DONE (t=14.51s).\n",
|
||||
" Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.374\n",
|
||||
" Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=100 ] = 0.572\n",
|
||||
" Average Precision (AP) @[ IoU=0.75 | area= all | maxDets=100 ] = 0.402\n",
|
||||
" Average Precision (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.211\n",
|
||||
" Average Precision (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.423\n",
|
||||
" Average Precision (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.489\n",
|
||||
" Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 1 ] = 0.311\n",
|
||||
" Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets= 10 ] = 0.516\n",
|
||||
" Average Recall (AR) @[ IoU=0.50:0.95 | area= all | maxDets=100 ] = 0.566\n",
|
||||
" Average Recall (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.378\n",
|
||||
" Average Recall (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.625\n",
|
||||
" Average Recall (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.722\n",
|
||||
"Results saved to \u001b[1mruns/val/exp\u001b[0m\n"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "ZY2VXXXu74w5"
|
||||
},
|
||||
"source": [
|
||||
"# 3. Train\n",
|
||||
"\n",
|
||||
"<p align=\"\"><a href=\"https://ultralytics.com/hub\"><img width=\"1000\" src=\"https://github.com/ultralytics/assets/raw/main/im/integrations-loop.png\"/></a></p>\n",
|
||||
"Close the active learning loop by sampling images from your inference conditions with the `roboflow` pip package\n",
|
||||
"<br><br>\n",
|
||||
"\n",
|
||||
"Train a YOLOv5s model on the [COCO128](https://www.kaggle.com/datasets/ultralytics/coco128) dataset with `--data coco128.yaml`, starting from pretrained `--weights yolov5s.pt`, or from randomly initialized `--weights '' --cfg yolov5s.yaml`.\n",
|
||||
"\n",
|
||||
"- **Pretrained [Models](https://github.com/ultralytics/yolov5/tree/master/models)** are downloaded\n",
|
||||
"automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases)\n",
|
||||
"- **[Datasets](https://github.com/ultralytics/yolov5/tree/master/data)** available for autodownload include: [COCO](https://github.com/ultralytics/yolov5/blob/master/data/coco.yaml), [COCO128](https://github.com/ultralytics/yolov5/blob/master/data/coco128.yaml), [VOC](https://github.com/ultralytics/yolov5/blob/master/data/VOC.yaml), [Argoverse](https://github.com/ultralytics/yolov5/blob/master/data/Argoverse.yaml), [VisDrone](https://github.com/ultralytics/yolov5/blob/master/data/VisDrone.yaml), [GlobalWheat](https://github.com/ultralytics/yolov5/blob/master/data/GlobalWheat2020.yaml), [xView](https://github.com/ultralytics/yolov5/blob/master/data/xView.yaml), [Objects365](https://github.com/ultralytics/yolov5/blob/master/data/Objects365.yaml), [SKU-110K](https://github.com/ultralytics/yolov5/blob/master/data/SKU-110K.yaml).\n",
|
||||
"- **Training Results** are saved to `runs/train/` with incrementing run directories, i.e. `runs/train/exp2`, `runs/train/exp3` etc.\n",
|
||||
"<br>\n",
|
||||
"\n",
|
||||
"A **Mosaic Dataloader** is used for training which combines 4 images into 1 mosaic.\n",
|
||||
"\n",
|
||||
"## Label a dataset on Roboflow (optional)\n",
|
||||
"\n",
|
||||
"[Roboflow](https://roboflow.com/?ref=ultralytics) enables you to easily **organize, label, and prepare** a high quality dataset with your own custom data. Roboflow also makes it easy to establish an active learning pipeline, collaborate with your team on dataset improvement, and integrate directly into your model building workflow with the `roboflow` pip package."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"source": [
|
||||
"#@title Select YOLOv5 🚀 logger {run: 'auto'}\n",
|
||||
"logger = 'Comet' #@param ['Comet', 'ClearML', 'TensorBoard']\n",
|
||||
"\n",
|
||||
"if logger == 'Comet':\n",
|
||||
" %pip install -q comet_ml\n",
|
||||
" import comet_ml; comet_ml.init()\n",
|
||||
"elif logger == 'ClearML':\n",
|
||||
" %pip install -q clearml\n",
|
||||
" import clearml; clearml.browser_login()\n",
|
||||
"elif logger == 'TensorBoard':\n",
|
||||
" %load_ext tensorboard\n",
|
||||
" %tensorboard --logdir runs/train"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "i3oKtE4g-aNn"
|
||||
},
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {
|
||||
"id": "1NcFxRcFdJ_O",
|
||||
"colab": {
|
||||
"base_uri": "https://localhost:8080/"
|
||||
},
|
||||
"outputId": "bbeeea2b-04fc-4185-aa64-258690495b5a"
|
||||
},
|
||||
"source": [
|
||||
"# Train YOLOv5s on COCO128 for 3 epochs\n",
|
||||
"!python train.py --img 640 --batch 16 --epochs 3 --data coco128.yaml --weights yolov5s.pt --cache"
|
||||
],
|
||||
"execution_count": null,
|
||||
"outputs": [
|
||||
{
|
||||
"output_type": "stream",
|
||||
"name": "stdout",
|
||||
"text": [
|
||||
"2023-04-09 14:11:38.063605: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.\n",
|
||||
"To enable the following instructions: AVX2 AVX512F FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.\n",
|
||||
"2023-04-09 14:11:39.026661: W tensorflow/compiler/tf2tensorrt/utils/py_utils.cc:38] TF-TRT Warning: Could not find TensorRT\n",
|
||||
"\u001b[34m\u001b[1mtrain: \u001b[0mweights=yolov5s.pt, cfg=, data=coco128.yaml, hyp=data/hyps/hyp.scratch-low.yaml, epochs=3, batch_size=16, imgsz=640, rect=False, resume=False, nosave=False, noval=False, noautoanchor=False, noplots=False, evolve=None, bucket=, cache=ram, image_weights=False, device=, multi_scale=False, single_cls=False, optimizer=SGD, sync_bn=False, workers=8, project=runs/train, name=exp, exist_ok=False, quad=False, cos_lr=False, label_smoothing=0.0, patience=100, freeze=[0], save_period=-1, seed=0, local_rank=-1, entity=None, upload_dataset=False, bbox_interval=-1, artifact_alias=latest\n",
|
||||
"\u001b[34m\u001b[1mgithub: \u001b[0mup to date with https://github.com/ultralytics/yolov5 ✅\n",
|
||||
"YOLOv5 🚀 v7.0-136-g71244ae Python-3.9.16 torch-2.0.0+cu118 CUDA:0 (Tesla T4, 15102MiB)\n",
|
||||
"\n",
|
||||
"\u001b[34m\u001b[1mhyperparameters: \u001b[0mlr0=0.01, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=0.05, cls=0.5, cls_pw=1.0, obj=1.0, obj_pw=1.0, iou_t=0.2, anchor_t=4.0, fl_gamma=0.0, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0, copy_paste=0.0\n",
|
||||
"\u001b[34m\u001b[1mClearML: \u001b[0mrun 'pip install clearml' to automatically track, visualize and remotely train YOLOv5 🚀 in ClearML\n",
|
||||
"\u001b[34m\u001b[1mComet: \u001b[0mrun 'pip install comet_ml' to automatically track and visualize YOLOv5 🚀 runs in Comet\n",
|
||||
"\u001b[34m\u001b[1mTensorBoard: \u001b[0mStart with 'tensorboard --logdir runs/train', view at http://localhost:6006/\n",
|
||||
"\n",
|
||||
"Dataset not found ⚠️, missing paths ['/content/datasets/coco128/images/train2017']\n",
|
||||
"Downloading https://github.com/ultralytics/assets/releases/download/v0.0.0/coco128.zip to coco128.zip...\n",
|
||||
"100% 6.66M/6.66M [00:00<00:00, 75.6MB/s]\n",
|
||||
"Dataset download success ✅ (0.6s), saved to \u001b[1m/content/datasets\u001b[0m\n",
|
||||
"\n",
|
||||
" from n params module arguments \n",
|
||||
" 0 -1 1 3520 models.common.Conv [3, 32, 6, 2, 2] \n",
|
||||
" 1 -1 1 18560 models.common.Conv [32, 64, 3, 2] \n",
|
||||
" 2 -1 1 18816 models.common.C3 [64, 64, 1] \n",
|
||||
" 3 -1 1 73984 models.common.Conv [64, 128, 3, 2] \n",
|
||||
" 4 -1 2 115712 models.common.C3 [128, 128, 2] \n",
|
||||
" 5 -1 1 295424 models.common.Conv [128, 256, 3, 2] \n",
|
||||
" 6 -1 3 625152 models.common.C3 [256, 256, 3] \n",
|
||||
" 7 -1 1 1180672 models.common.Conv [256, 512, 3, 2] \n",
|
||||
" 8 -1 1 1182720 models.common.C3 [512, 512, 1] \n",
|
||||
" 9 -1 1 656896 models.common.SPPF [512, 512, 5] \n",
|
||||
" 10 -1 1 131584 models.common.Conv [512, 256, 1, 1] \n",
|
||||
" 11 -1 1 0 torch.nn.modules.upsampling.Upsample [None, 2, 'nearest'] \n",
|
||||
" 12 [-1, 6] 1 0 models.common.Concat [1] \n",
|
||||
" 13 -1 1 361984 models.common.C3 [512, 256, 1, False] \n",
|
||||
" 14 -1 1 33024 models.common.Conv [256, 128, 1, 1] \n",
|
||||
" 15 -1 1 0 torch.nn.modules.upsampling.Upsample [None, 2, 'nearest'] \n",
|
||||
" 16 [-1, 4] 1 0 models.common.Concat [1] \n",
|
||||
" 17 -1 1 90880 models.common.C3 [256, 128, 1, False] \n",
|
||||
" 18 -1 1 147712 models.common.Conv [128, 128, 3, 2] \n",
|
||||
" 19 [-1, 14] 1 0 models.common.Concat [1] \n",
|
||||
" 20 -1 1 296448 models.common.C3 [256, 256, 1, False] \n",
|
||||
" 21 -1 1 590336 models.common.Conv [256, 256, 3, 2] \n",
|
||||
" 22 [-1, 10] 1 0 models.common.Concat [1] \n",
|
||||
" 23 -1 1 1182720 models.common.C3 [512, 512, 1, False] \n",
|
||||
" 24 [17, 20, 23] 1 229245 models.yolo.Detect [80, [[10, 13, 16, 30, 33, 23], [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]], [128, 256, 512]]\n",
|
||||
"Model summary: 214 layers, 7235389 parameters, 7235389 gradients, 16.6 GFLOPs\n",
|
||||
"\n",
|
||||
"Transferred 349/349 items from yolov5s.pt\n",
|
||||
"\u001b[34m\u001b[1mAMP: \u001b[0mchecks passed ✅\n",
|
||||
"\u001b[34m\u001b[1moptimizer:\u001b[0m SGD(lr=0.01) with parameter groups 57 weight(decay=0.0), 60 weight(decay=0.0005), 60 bias\n",
|
||||
"\u001b[34m\u001b[1malbumentations: \u001b[0mBlur(p=0.01, blur_limit=(3, 7)), MedianBlur(p=0.01, blur_limit=(3, 7)), ToGray(p=0.01), CLAHE(p=0.01, clip_limit=(1, 4.0), tile_grid_size=(8, 8))\n",
|
||||
"\u001b[34m\u001b[1mtrain: \u001b[0mScanning /content/datasets/coco128/labels/train2017... 126 images, 2 backgrounds, 0 corrupt: 100% 128/128 [00:00<00:00, 1709.36it/s]\n",
|
||||
"\u001b[34m\u001b[1mtrain: \u001b[0mNew cache created: /content/datasets/coco128/labels/train2017.cache\n",
|
||||
"\u001b[34m\u001b[1mtrain: \u001b[0mCaching images (0.1GB ram): 100% 128/128 [00:00<00:00, 264.35it/s]\n",
|
||||
"\u001b[34m\u001b[1mval: \u001b[0mScanning /content/datasets/coco128/labels/train2017.cache... 126 images, 2 backgrounds, 0 corrupt: 100% 128/128 [00:00<?, ?it/s]\n",
|
||||
"\u001b[34m\u001b[1mval: \u001b[0mCaching images (0.1GB ram): 100% 128/128 [00:01<00:00, 107.05it/s]\n",
|
||||
"\n",
|
||||
"\u001b[34m\u001b[1mAutoAnchor: \u001b[0m4.27 anchors/target, 0.994 Best Possible Recall (BPR). Current anchors are a good fit to dataset ✅\n",
|
||||
"Plotting labels to runs/train/exp/labels.jpg... \n",
|
||||
"Image sizes 640 train, 640 val\n",
|
||||
"Using 2 dataloader workers\n",
|
||||
"Logging results to \u001b[1mruns/train/exp\u001b[0m\n",
|
||||
"Starting training for 3 epochs...\n",
|
||||
"\n",
|
||||
" Epoch GPU_mem box_loss obj_loss cls_loss Instances Size\n",
|
||||
" 0/2 3.91G 0.04618 0.07209 0.01703 232 640: 100% 8/8 [00:09<00:00, 1.17s/it]\n",
|
||||
" Class Images Instances P R mAP50 mAP50-95: 100% 4/4 [00:01<00:00, 2.01it/s]\n",
|
||||
" all 128 929 0.667 0.602 0.68 0.45\n",
|
||||
"\n",
|
||||
" Epoch GPU_mem box_loss obj_loss cls_loss Instances Size\n",
|
||||
" 1/2 4.76G 0.04622 0.06891 0.01817 201 640: 100% 8/8 [00:02<00:00, 3.78it/s]\n",
|
||||
" Class Images Instances P R mAP50 mAP50-95: 100% 4/4 [00:01<00:00, 2.16it/s]\n",
|
||||
" all 128 929 0.709 0.645 0.722 0.478\n",
|
||||
"\n",
|
||||
" Epoch GPU_mem box_loss obj_loss cls_loss Instances Size\n",
|
||||
" 2/2 4.76G 0.0436 0.0647 0.01698 227 640: 100% 8/8 [00:01<00:00, 4.19it/s]\n",
|
||||
" Class Images Instances P R mAP50 mAP50-95: 100% 4/4 [00:01<00:00, 2.95it/s]\n",
|
||||
" all 128 929 0.761 0.647 0.735 0.49\n",
|
||||
"\n",
|
||||
"3 epochs completed in 0.006 hours.\n",
|
||||
"Optimizer stripped from runs/train/exp/weights/last.pt, 14.8MB\n",
|
||||
"Optimizer stripped from runs/train/exp/weights/best.pt, 14.8MB\n",
|
||||
"\n",
|
||||
"Validating runs/train/exp/weights/best.pt...\n",
|
||||
"Fusing layers... \n",
|
||||
"Model summary: 157 layers, 7225885 parameters, 0 gradients, 16.4 GFLOPs\n",
|
||||
" Class Images Instances P R mAP50 mAP50-95: 100% 4/4 [00:06<00:00, 1.56s/it]\n",
|
||||
" all 128 929 0.759 0.646 0.734 0.49\n",
|
||||
" person 128 254 0.857 0.706 0.805 0.525\n",
|
||||
" bicycle 128 6 0.773 0.577 0.725 0.414\n",
|
||||
" car 128 46 0.664 0.435 0.551 0.24\n",
|
||||
" motorcycle 128 5 0.587 0.8 0.837 0.635\n",
|
||||
" airplane 128 6 1 0.989 0.995 0.715\n",
|
||||
" bus 128 7 0.635 0.714 0.753 0.651\n",
|
||||
" train 128 3 0.686 0.333 0.72 0.504\n",
|
||||
" truck 128 12 0.604 0.333 0.472 0.259\n",
|
||||
" boat 128 6 0.938 0.333 0.449 0.177\n",
|
||||
" traffic light 128 14 0.778 0.255 0.401 0.217\n",
|
||||
" stop sign 128 2 0.826 1 0.995 0.895\n",
|
||||
" bench 128 9 0.711 0.556 0.661 0.313\n",
|
||||
" bird 128 16 0.962 1 0.995 0.642\n",
|
||||
" cat 128 4 0.868 1 0.995 0.754\n",
|
||||
" dog 128 9 1 0.652 0.899 0.651\n",
|
||||
" horse 128 2 0.853 1 0.995 0.622\n",
|
||||
" elephant 128 17 0.909 0.882 0.934 0.698\n",
|
||||
" bear 128 1 0.696 1 0.995 0.995\n",
|
||||
" zebra 128 4 0.855 1 0.995 0.905\n",
|
||||
" giraffe 128 9 0.788 0.828 0.912 0.701\n",
|
||||
" backpack 128 6 0.835 0.5 0.738 0.311\n",
|
||||
" umbrella 128 18 0.785 0.814 0.859 0.48\n",
|
||||
" handbag 128 19 0.759 0.263 0.366 0.205\n",
|
||||
" tie 128 7 0.983 0.714 0.77 0.492\n",
|
||||
" suitcase 128 4 0.656 1 0.945 0.631\n",
|
||||
" frisbee 128 5 0.721 0.8 0.759 0.724\n",
|
||||
" skis 128 1 0.737 1 0.995 0.3\n",
|
||||
" snowboard 128 7 0.829 0.696 0.83 0.537\n",
|
||||
" sports ball 128 6 0.637 0.667 0.602 0.311\n",
|
||||
" kite 128 10 0.636 0.6 0.599 0.226\n",
|
||||
" baseball bat 128 4 0.501 0.25 0.468 0.205\n",
|
||||
" baseball glove 128 7 0.483 0.429 0.465 0.292\n",
|
||||
" skateboard 128 5 0.932 0.6 0.687 0.493\n",
|
||||
" tennis racket 128 7 0.77 0.429 0.547 0.332\n",
|
||||
" bottle 128 18 0.577 0.379 0.554 0.276\n",
|
||||
" wine glass 128 16 0.704 0.875 0.89 0.51\n",
|
||||
" cup 128 36 0.841 0.667 0.837 0.533\n",
|
||||
" fork 128 6 0.992 0.333 0.45 0.315\n",
|
||||
" knife 128 16 0.768 0.688 0.695 0.403\n",
|
||||
" spoon 128 22 0.838 0.47 0.639 0.384\n",
|
||||
" bowl 128 28 0.764 0.58 0.716 0.513\n",
|
||||
" banana 128 1 0.902 1 0.995 0.301\n",
|
||||
" sandwich 128 2 1 0 0.359 0.326\n",
|
||||
" orange 128 4 0.722 0.75 0.912 0.581\n",
|
||||
" broccoli 128 11 0.547 0.364 0.432 0.317\n",
|
||||
" carrot 128 24 0.619 0.625 0.724 0.495\n",
|
||||
" hot dog 128 2 0.409 1 0.828 0.762\n",
|
||||
" pizza 128 5 0.833 0.995 0.962 0.727\n",
|
||||
" donut 128 14 0.631 1 0.96 0.839\n",
|
||||
" cake 128 4 0.87 1 0.995 0.83\n",
|
||||
" chair 128 35 0.583 0.6 0.608 0.317\n",
|
||||
" couch 128 6 0.907 0.667 0.815 0.544\n",
|
||||
" potted plant 128 14 0.739 0.786 0.823 0.48\n",
|
||||
" bed 128 3 0.985 0.333 0.83 0.441\n",
|
||||
" dining table 128 13 0.821 0.357 0.578 0.342\n",
|
||||
" toilet 128 2 1 0.988 0.995 0.846\n",
|
||||
" tv 128 2 0.57 1 0.995 0.796\n",
|
||||
" laptop 128 3 1 0 0.593 0.312\n",
|
||||
" mouse 128 2 1 0 0.089 0.0445\n",
|
||||
" remote 128 8 1 0.624 0.634 0.538\n",
|
||||
" cell phone 128 8 0.622 0.417 0.421 0.187\n",
|
||||
" microwave 128 3 0.711 1 0.995 0.766\n",
|
||||
" oven 128 5 0.329 0.4 0.43 0.282\n",
|
||||
" sink 128 6 0.437 0.333 0.338 0.265\n",
|
||||
" refrigerator 128 5 0.567 0.8 0.799 0.536\n",
|
||||
" book 128 29 0.597 0.257 0.349 0.154\n",
|
||||
" clock 128 9 0.765 0.889 0.932 0.736\n",
|
||||
" vase 128 2 0.33 1 0.995 0.895\n",
|
||||
" scissors 128 1 1 0 0.497 0.0498\n",
|
||||
" teddy bear 128 21 0.856 0.569 0.841 0.547\n",
|
||||
" toothbrush 128 5 0.8 1 0.928 0.574\n",
|
||||
"Results saved to \u001b[1mruns/train/exp\u001b[0m\n"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "15glLzbQx5u0"
|
||||
},
|
||||
"source": [
|
||||
"# 4. Visualize"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"## Comet Logging and Visualization 🌟 NEW\n",
|
||||
"\n",
|
||||
"[Comet](https://www.comet.com/site/lp/yolov5-with-comet/?utm_source=yolov5&utm_medium=partner&utm_campaign=partner_yolov5_2022&utm_content=yolov5_colab) is now fully integrated with YOLOv5. Track and visualize model metrics in real time, save your hyperparameters, datasets, and model checkpoints, and visualize your model predictions with [Comet Custom Panels](https://www.comet.com/docs/v2/guides/comet-dashboard/code-panels/about-panels/?utm_source=yolov5&utm_medium=partner&utm_campaign=partner_yolov5_2022&utm_content=yolov5_colab)! Comet makes sure you never lose track of your work and makes it easy to share results and collaborate across teams of all sizes!\n",
|
||||
"\n",
|
||||
"Getting started is easy:\n",
|
||||
"```shell\n",
|
||||
"pip install comet_ml # 1. install\n",
|
||||
"export COMET_API_KEY=<Your API Key> # 2. paste API key\n",
|
||||
"python train.py --img 640 --epochs 3 --data coco128.yaml --weights yolov5s.pt # 3. train\n",
|
||||
"```\n",
|
||||
"To learn more about all of the supported Comet features for this integration, check out the [Comet Tutorial](https://docs.ultralytics.com/yolov5/tutorials/comet_logging_integration). If you'd like to learn more about Comet, head over to our [documentation](https://www.comet.com/docs/v2/?utm_source=yolov5&utm_medium=partner&utm_campaign=partner_yolov5_2022&utm_content=yolov5_colab). Get started by trying out the Comet Colab Notebook:\n",
|
||||
"[](https://colab.research.google.com/drive/1RG0WOQyxlDlo5Km8GogJpIEJlg_5lyYO?usp=sharing)\n",
|
||||
"\n",
|
||||
"<a href=\"https://bit.ly/yolov5-readme-comet2\">\n",
|
||||
"<img alt=\"Comet Dashboard\" src=\"https://user-images.githubusercontent.com/26833433/202851203-164e94e1-2238-46dd-91f8-de020e9d6b41.png\" width=\"1280\"/></a>"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "nWOsI5wJR1o3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"source": [
|
||||
"## ClearML Logging and Automation 🌟 NEW\n",
|
||||
"\n",
|
||||
"[ClearML](https://cutt.ly/yolov5-notebook-clearml) is completely integrated into YOLOv5 to track your experimentation, manage dataset versions and even remotely execute training runs. To enable ClearML (check cells above):\n",
|
||||
"\n",
|
||||
"- `pip install clearml`\n",
|
||||
"- run `clearml-init` to connect to a ClearML server (**deploy your own [open-source server](https://github.com/allegroai/clearml-server)**, or use our [free hosted server](https://cutt.ly/yolov5-notebook-clearml))\n",
|
||||
"\n",
|
||||
"You'll get all the great expected features from an experiment manager: live updates, model upload, experiment comparison etc. but ClearML also tracks uncommitted changes and installed packages for example. Thanks to that ClearML Tasks (which is what we call experiments) are also reproducible on different machines! With only 1 extra line, we can schedule a YOLOv5 training task on a queue to be executed by any number of ClearML Agents (workers).\n",
|
||||
"\n",
|
||||
"You can use ClearML Data to version your dataset and then pass it to YOLOv5 simply using its unique ID. This will help you keep track of your data without adding extra hassle. Explore the [ClearML Tutorial](https://docs.ultralytics.com/yolov5/tutorials/clearml_logging_integration) for details!\n",
|
||||
"\n",
|
||||
"<a href=\"https://cutt.ly/yolov5-notebook-clearml\">\n",
|
||||
"<img alt=\"ClearML Experiment Management UI\" src=\"https://github.com/thepycoder/clearml_screenshots/raw/main/scalars.jpg\" width=\"1280\"/></a>"
|
||||
],
|
||||
"metadata": {
|
||||
"id": "Lay2WsTjNJzP"
|
||||
}
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "-WPvRbS5Swl6"
|
||||
},
|
||||
"source": [
|
||||
"## Local Logging\n",
|
||||
"\n",
|
||||
"Training results are automatically logged with [Tensorboard](https://www.tensorflow.org/tensorboard) and [CSV](https://github.com/ultralytics/yolov5/pull/4148) loggers to `runs/train`, with a new experiment directory created for each new training as `runs/train/exp2`, `runs/train/exp3`, etc.\n",
|
||||
"\n",
|
||||
"This directory contains train and val statistics, mosaics, labels, predictions and augmentated mosaics, as well as metrics and charts including precision-recall (PR) curves and confusion matrices.\n",
|
||||
"\n",
|
||||
"<img alt=\"Local logging results\" src=\"https://user-images.githubusercontent.com/26833433/183222430-e1abd1b7-782c-4cde-b04d-ad52926bf818.jpg\" width=\"1280\"/>\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "Zelyeqbyt3GD"
|
||||
},
|
||||
"source": [
|
||||
"# Environments\n",
|
||||
"\n",
|
||||
"YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n",
|
||||
"\n",
|
||||
"- **Notebooks** with free GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/models/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n",
|
||||
"- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)\n",
|
||||
"- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)\n",
|
||||
"- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "6Qu7Iesl0p54"
|
||||
},
|
||||
"source": [
|
||||
"# Status\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"If this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), testing ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on macOS, Windows, and Ubuntu every 24 hours and on every commit.\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"metadata": {
|
||||
"id": "IEijrePND_2I"
|
||||
},
|
||||
"source": [
|
||||
"# Appendix\n",
|
||||
"\n",
|
||||
"Additional content below."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"metadata": {
|
||||
"id": "GMusP4OAxFu6"
|
||||
},
|
||||
"source": [
|
||||
"# YOLOv5 PyTorch HUB Inference (DetectionModels only)\n",
|
||||
"import torch\n",
|
||||
"\n",
|
||||
"model = torch.hub.load('ultralytics/yolov5', 'yolov5s', force_reload=True, trust_repo=True) # or yolov5n - yolov5x6 or custom\n",
|
||||
"im = 'https://ultralytics.com/images/zidane.jpg' # file, Path, PIL.Image, OpenCV, nparray, list\n",
|
||||
"results = model(im) # inference\n",
|
||||
"results.print() # or .show(), .save(), .crop(), .pandas(), etc."
|
||||
],
|
||||
"execution_count": null,
|
||||
"outputs": []
|
||||
}
|
||||
]
|
||||
}
|
97
yolov5/utils/__init__.py
Normal file
97
yolov5/utils/__init__.py
Normal file
@ -0,0 +1,97 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""utils/initialization."""
|
||||
|
||||
import contextlib
|
||||
import platform
|
||||
import threading
|
||||
|
||||
|
||||
def emojis(str=""):
|
||||
"""Returns an emoji-safe version of a string, stripped of emojis on Windows platforms."""
|
||||
return str.encode().decode("ascii", "ignore") if platform.system() == "Windows" else str
|
||||
|
||||
|
||||
class TryExcept(contextlib.ContextDecorator):
|
||||
"""A context manager and decorator for error handling that prints an optional message with emojis on exception."""
|
||||
|
||||
def __init__(self, msg=""):
|
||||
"""Initializes TryExcept with an optional message, used as a decorator or context manager for error handling."""
|
||||
self.msg = msg
|
||||
|
||||
def __enter__(self):
|
||||
"""Enter the runtime context related to this object for error handling with an optional message."""
|
||||
pass
|
||||
|
||||
def __exit__(self, exc_type, value, traceback):
|
||||
"""Context manager exit method that prints an error message with emojis if an exception occurred, always returns
|
||||
True.
|
||||
"""
|
||||
if value:
|
||||
print(emojis(f"{self.msg}{': ' if self.msg else ''}{value}"))
|
||||
return True
|
||||
|
||||
|
||||
def threaded(func):
|
||||
"""Decorator @threaded to run a function in a separate thread, returning the thread instance."""
|
||||
|
||||
def wrapper(*args, **kwargs):
|
||||
"""Runs the decorated function in a separate daemon thread and returns the thread instance."""
|
||||
thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)
|
||||
thread.start()
|
||||
return thread
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def join_threads(verbose=False):
|
||||
"""
|
||||
Joins all daemon threads, optionally printing their names if verbose is True.
|
||||
|
||||
Example: atexit.register(lambda: join_threads())
|
||||
"""
|
||||
main_thread = threading.current_thread()
|
||||
for t in threading.enumerate():
|
||||
if t is not main_thread:
|
||||
if verbose:
|
||||
print(f"Joining thread {t.name}")
|
||||
t.join()
|
||||
|
||||
|
||||
def notebook_init(verbose=True):
|
||||
"""Initializes notebook environment by checking requirements, cleaning up, and displaying system info."""
|
||||
print("Checking setup...")
|
||||
|
||||
import os
|
||||
import shutil
|
||||
|
||||
from ultralytics.utils.checks import check_requirements
|
||||
|
||||
from utils.general import check_font, is_colab
|
||||
from utils.torch_utils import select_device # imports
|
||||
|
||||
check_font()
|
||||
|
||||
import psutil
|
||||
|
||||
if check_requirements("wandb", install=False):
|
||||
os.system("pip uninstall -y wandb") # eliminate unexpected account creation prompt with infinite hang
|
||||
if is_colab():
|
||||
shutil.rmtree("/content/sample_data", ignore_errors=True) # remove colab /sample_data directory
|
||||
|
||||
# System info
|
||||
display = None
|
||||
if verbose:
|
||||
gb = 1 << 30 # bytes to GiB (1024 ** 3)
|
||||
ram = psutil.virtual_memory().total
|
||||
total, used, free = shutil.disk_usage("/")
|
||||
with contextlib.suppress(Exception): # clear display if ipython is installed
|
||||
from IPython import display
|
||||
|
||||
display.clear_output()
|
||||
s = f"({os.cpu_count()} CPUs, {ram / gb:.1f} GB RAM, {(total - free) / gb:.1f}/{total / gb:.1f} GB disk)"
|
||||
else:
|
||||
s = ""
|
||||
|
||||
select_device(newline=False)
|
||||
print(emojis(f"Setup complete ✅ {s}"))
|
||||
return display
|
134
yolov5/utils/activations.py
Normal file
134
yolov5/utils/activations.py
Normal file
@ -0,0 +1,134 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""Activation functions."""
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
class SiLU(nn.Module):
|
||||
"""Applies the Sigmoid-weighted Linear Unit (SiLU) activation function, also known as Swish."""
|
||||
|
||||
@staticmethod
|
||||
def forward(x):
|
||||
"""
|
||||
Applies the Sigmoid-weighted Linear Unit (SiLU) activation function.
|
||||
|
||||
https://arxiv.org/pdf/1606.08415.pdf.
|
||||
"""
|
||||
return x * torch.sigmoid(x)
|
||||
|
||||
|
||||
class Hardswish(nn.Module):
|
||||
"""Applies the Hardswish activation function, which is efficient for mobile and embedded devices."""
|
||||
|
||||
@staticmethod
|
||||
def forward(x):
|
||||
"""
|
||||
Applies the Hardswish activation function, compatible with TorchScript, CoreML, and ONNX.
|
||||
|
||||
Equivalent to x * F.hardsigmoid(x)
|
||||
"""
|
||||
return x * F.hardtanh(x + 3, 0.0, 6.0) / 6.0 # for TorchScript, CoreML and ONNX
|
||||
|
||||
|
||||
class Mish(nn.Module):
|
||||
"""Mish activation https://github.com/digantamisra98/Mish."""
|
||||
|
||||
@staticmethod
|
||||
def forward(x):
|
||||
"""Applies the Mish activation function, a smooth alternative to ReLU."""
|
||||
return x * F.softplus(x).tanh()
|
||||
|
||||
|
||||
class MemoryEfficientMish(nn.Module):
|
||||
"""Efficiently applies the Mish activation function using custom autograd for reduced memory usage."""
|
||||
|
||||
class F(torch.autograd.Function):
|
||||
"""Implements a custom autograd function for memory-efficient Mish activation."""
|
||||
|
||||
@staticmethod
|
||||
def forward(ctx, x):
|
||||
"""Applies the Mish activation function, a smooth ReLU alternative, to the input tensor `x`."""
|
||||
ctx.save_for_backward(x)
|
||||
return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
|
||||
|
||||
@staticmethod
|
||||
def backward(ctx, grad_output):
|
||||
"""Computes the gradient of the Mish activation function with respect to input `x`."""
|
||||
x = ctx.saved_tensors[0]
|
||||
sx = torch.sigmoid(x)
|
||||
fx = F.softplus(x).tanh()
|
||||
return grad_output * (fx + x * sx * (1 - fx * fx))
|
||||
|
||||
def forward(self, x):
|
||||
"""Applies the Mish activation function to the input tensor `x`."""
|
||||
return self.F.apply(x)
|
||||
|
||||
|
||||
class FReLU(nn.Module):
|
||||
"""FReLU activation https://arxiv.org/abs/2007.11824."""
|
||||
|
||||
def __init__(self, c1, k=3): # ch_in, kernel
|
||||
"""Initializes FReLU activation with channel `c1` and kernel size `k`."""
|
||||
super().__init__()
|
||||
self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
|
||||
self.bn = nn.BatchNorm2d(c1)
|
||||
|
||||
def forward(self, x):
|
||||
"""
|
||||
Applies FReLU activation with max operation between input and BN-convolved input.
|
||||
|
||||
https://arxiv.org/abs/2007.11824
|
||||
"""
|
||||
return torch.max(x, self.bn(self.conv(x)))
|
||||
|
||||
|
||||
class AconC(nn.Module):
|
||||
"""
|
||||
ACON activation (activate or not) function.
|
||||
|
||||
AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
|
||||
See "Activate or Not: Learning Customized Activation" https://arxiv.org/pdf/2009.04759.pdf.
|
||||
"""
|
||||
|
||||
def __init__(self, c1):
|
||||
"""Initializes AconC with learnable parameters p1, p2, and beta for channel-wise activation control."""
|
||||
super().__init__()
|
||||
self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
|
||||
self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
|
||||
self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
|
||||
|
||||
def forward(self, x):
|
||||
"""Applies AconC activation function with learnable parameters for channel-wise control on input tensor x."""
|
||||
dpx = (self.p1 - self.p2) * x
|
||||
return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
|
||||
|
||||
|
||||
class MetaAconC(nn.Module):
|
||||
"""
|
||||
ACON activation (activate or not) function.
|
||||
|
||||
AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
|
||||
See "Activate or Not: Learning Customized Activation" https://arxiv.org/pdf/2009.04759.pdf.
|
||||
"""
|
||||
|
||||
def __init__(self, c1, k=1, s=1, r=16):
|
||||
"""Initializes MetaAconC with params: channel_in (c1), kernel size (k=1), stride (s=1), reduction (r=16)."""
|
||||
super().__init__()
|
||||
c2 = max(r, c1 // r)
|
||||
self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
|
||||
self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
|
||||
self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
|
||||
self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
|
||||
# self.bn1 = nn.BatchNorm2d(c2)
|
||||
# self.bn2 = nn.BatchNorm2d(c1)
|
||||
|
||||
def forward(self, x):
|
||||
"""Applies a forward pass transforming input `x` using learnable parameters and sigmoid activation."""
|
||||
y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
|
||||
# batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
|
||||
# beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
|
||||
beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed
|
||||
dpx = (self.p1 - self.p2) * x
|
||||
return dpx * torch.sigmoid(beta * dpx) + self.p2 * x
|
440
yolov5/utils/augmentations.py
Normal file
440
yolov5/utils/augmentations.py
Normal file
@ -0,0 +1,440 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""Image augmentation functions."""
|
||||
|
||||
import math
|
||||
import random
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
import torch
|
||||
import torchvision.transforms as T
|
||||
import torchvision.transforms.functional as TF
|
||||
|
||||
from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
|
||||
from utils.metrics import bbox_ioa
|
||||
|
||||
IMAGENET_MEAN = 0.485, 0.456, 0.406 # RGB mean
|
||||
IMAGENET_STD = 0.229, 0.224, 0.225 # RGB standard deviation
|
||||
|
||||
|
||||
class Albumentations:
|
||||
"""Provides optional data augmentation for YOLOv5 using Albumentations library if installed."""
|
||||
|
||||
def __init__(self, size=640):
|
||||
"""Initializes Albumentations class for optional data augmentation in YOLOv5 with specified input size."""
|
||||
self.transform = None
|
||||
prefix = colorstr("albumentations: ")
|
||||
try:
|
||||
import albumentations as A
|
||||
|
||||
check_version(A.__version__, "1.0.3", hard=True) # version requirement
|
||||
|
||||
T = [
|
||||
A.RandomResizedCrop(height=size, width=size, scale=(0.8, 1.0), ratio=(0.9, 1.11), p=0.0),
|
||||
A.Blur(p=0.01),
|
||||
A.MedianBlur(p=0.01),
|
||||
A.ToGray(p=0.01),
|
||||
A.CLAHE(p=0.01),
|
||||
A.RandomBrightnessContrast(p=0.0),
|
||||
A.RandomGamma(p=0.0),
|
||||
A.ImageCompression(quality_lower=75, p=0.0),
|
||||
] # transforms
|
||||
self.transform = A.Compose(T, bbox_params=A.BboxParams(format="yolo", label_fields=["class_labels"]))
|
||||
|
||||
LOGGER.info(prefix + ", ".join(f"{x}".replace("always_apply=False, ", "") for x in T if x.p))
|
||||
except ImportError: # package not installed, skip
|
||||
pass
|
||||
except Exception as e:
|
||||
LOGGER.info(f"{prefix}{e}")
|
||||
|
||||
def __call__(self, im, labels, p=1.0):
|
||||
"""Applies transformations to an image and labels with probability `p`, returning updated image and labels."""
|
||||
if self.transform and random.random() < p:
|
||||
new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
|
||||
im, labels = new["image"], np.array([[c, *b] for c, b in zip(new["class_labels"], new["bboxes"])])
|
||||
return im, labels
|
||||
|
||||
|
||||
def normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):
|
||||
"""
|
||||
Applies ImageNet normalization to RGB images in BCHW format, modifying them in-place if specified.
|
||||
|
||||
Example: y = (x - mean) / std
|
||||
"""
|
||||
return TF.normalize(x, mean, std, inplace=inplace)
|
||||
|
||||
|
||||
def denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):
|
||||
"""Reverses ImageNet normalization for BCHW format RGB images by applying `x = x * std + mean`."""
|
||||
for i in range(3):
|
||||
x[:, i] = x[:, i] * std[i] + mean[i]
|
||||
return x
|
||||
|
||||
|
||||
def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
|
||||
"""Applies HSV color-space augmentation to an image with random gains for hue, saturation, and value."""
|
||||
if hgain or sgain or vgain:
|
||||
r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
|
||||
hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
|
||||
dtype = im.dtype # uint8
|
||||
|
||||
x = np.arange(0, 256, dtype=r.dtype)
|
||||
lut_hue = ((x * r[0]) % 180).astype(dtype)
|
||||
lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
|
||||
lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
|
||||
|
||||
im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
|
||||
cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed
|
||||
|
||||
|
||||
def hist_equalize(im, clahe=True, bgr=False):
|
||||
"""Equalizes image histogram, with optional CLAHE, for BGR or RGB image with shape (n,m,3) and range 0-255."""
|
||||
yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
|
||||
if clahe:
|
||||
c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
||||
yuv[:, :, 0] = c.apply(yuv[:, :, 0])
|
||||
else:
|
||||
yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
|
||||
return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
|
||||
|
||||
|
||||
def replicate(im, labels):
|
||||
"""
|
||||
Replicates half of the smallest object labels in an image for data augmentation.
|
||||
|
||||
Returns augmented image and labels.
|
||||
"""
|
||||
h, w = im.shape[:2]
|
||||
boxes = labels[:, 1:].astype(int)
|
||||
x1, y1, x2, y2 = boxes.T
|
||||
s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
|
||||
for i in s.argsort()[: round(s.size * 0.5)]: # smallest indices
|
||||
x1b, y1b, x2b, y2b = boxes[i]
|
||||
bh, bw = y2b - y1b, x2b - x1b
|
||||
yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
|
||||
x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
|
||||
im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax]
|
||||
labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
|
||||
|
||||
return im, labels
|
||||
|
||||
|
||||
def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
|
||||
"""Resizes and pads image to new_shape with stride-multiple constraints, returns resized image, ratio, padding."""
|
||||
shape = im.shape[:2] # current shape [height, width]
|
||||
if isinstance(new_shape, int):
|
||||
new_shape = (new_shape, new_shape)
|
||||
|
||||
# Scale ratio (new / old)
|
||||
r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
|
||||
if not scaleup: # only scale down, do not scale up (for better val mAP)
|
||||
r = min(r, 1.0)
|
||||
|
||||
# Compute padding
|
||||
ratio = r, r # width, height ratios
|
||||
new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
|
||||
dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
|
||||
if auto: # minimum rectangle
|
||||
dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
|
||||
elif scaleFill: # stretch
|
||||
dw, dh = 0.0, 0.0
|
||||
new_unpad = (new_shape[1], new_shape[0])
|
||||
ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
|
||||
|
||||
dw /= 2 # divide padding into 2 sides
|
||||
dh /= 2
|
||||
|
||||
if shape[::-1] != new_unpad: # resize
|
||||
im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
|
||||
top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
|
||||
left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
|
||||
im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
|
||||
return im, ratio, (dw, dh)
|
||||
|
||||
|
||||
def random_perspective(
|
||||
im, targets=(), segments=(), degrees=10, translate=0.1, scale=0.1, shear=10, perspective=0.0, border=(0, 0)
|
||||
):
|
||||
# torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))
|
||||
# targets = [cls, xyxy]
|
||||
"""Applies random perspective transformation to an image, modifying the image and corresponding labels."""
|
||||
height = im.shape[0] + border[0] * 2 # shape(h,w,c)
|
||||
width = im.shape[1] + border[1] * 2
|
||||
|
||||
# Center
|
||||
C = np.eye(3)
|
||||
C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
|
||||
C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
|
||||
|
||||
# Perspective
|
||||
P = np.eye(3)
|
||||
P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
|
||||
P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
|
||||
|
||||
# Rotation and Scale
|
||||
R = np.eye(3)
|
||||
a = random.uniform(-degrees, degrees)
|
||||
# a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
|
||||
s = random.uniform(1 - scale, 1 + scale)
|
||||
# s = 2 ** random.uniform(-scale, scale)
|
||||
R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
|
||||
|
||||
# Shear
|
||||
S = np.eye(3)
|
||||
S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
|
||||
S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
|
||||
|
||||
# Translation
|
||||
T = np.eye(3)
|
||||
T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
|
||||
T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
|
||||
|
||||
# Combined rotation matrix
|
||||
M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
|
||||
if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
|
||||
if perspective:
|
||||
im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
|
||||
else: # affine
|
||||
im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
|
||||
|
||||
if n := len(targets):
|
||||
use_segments = any(x.any() for x in segments) and len(segments) == n
|
||||
new = np.zeros((n, 4))
|
||||
if use_segments: # warp segments
|
||||
segments = resample_segments(segments) # upsample
|
||||
for i, segment in enumerate(segments):
|
||||
xy = np.ones((len(segment), 3))
|
||||
xy[:, :2] = segment
|
||||
xy = xy @ M.T # transform
|
||||
xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
|
||||
|
||||
# clip
|
||||
new[i] = segment2box(xy, width, height)
|
||||
|
||||
else: # warp boxes
|
||||
xy = np.ones((n * 4, 3))
|
||||
xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
|
||||
xy = xy @ M.T # transform
|
||||
xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
|
||||
|
||||
# create new boxes
|
||||
x = xy[:, [0, 2, 4, 6]]
|
||||
y = xy[:, [1, 3, 5, 7]]
|
||||
new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
|
||||
|
||||
# clip
|
||||
new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
|
||||
new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
|
||||
|
||||
# filter candidates
|
||||
i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
|
||||
targets = targets[i]
|
||||
targets[:, 1:5] = new[i]
|
||||
|
||||
return im, targets
|
||||
|
||||
|
||||
def copy_paste(im, labels, segments, p=0.5):
|
||||
"""
|
||||
Applies Copy-Paste augmentation by flipping and merging segments and labels on an image.
|
||||
|
||||
Details at https://arxiv.org/abs/2012.07177.
|
||||
"""
|
||||
n = len(segments)
|
||||
if p and n:
|
||||
h, w, c = im.shape # height, width, channels
|
||||
im_new = np.zeros(im.shape, np.uint8)
|
||||
for j in random.sample(range(n), k=round(p * n)):
|
||||
l, s = labels[j], segments[j]
|
||||
box = w - l[3], l[2], w - l[1], l[4]
|
||||
ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
|
||||
if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
|
||||
labels = np.concatenate((labels, [[l[0], *box]]), 0)
|
||||
segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
|
||||
cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (1, 1, 1), cv2.FILLED)
|
||||
|
||||
result = cv2.flip(im, 1) # augment segments (flip left-right)
|
||||
i = cv2.flip(im_new, 1).astype(bool)
|
||||
im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
|
||||
|
||||
return im, labels, segments
|
||||
|
||||
|
||||
def cutout(im, labels, p=0.5):
|
||||
"""
|
||||
Applies cutout augmentation to an image with optional label adjustment, using random masks of varying sizes.
|
||||
|
||||
Details at https://arxiv.org/abs/1708.04552.
|
||||
"""
|
||||
if random.random() < p:
|
||||
h, w = im.shape[:2]
|
||||
scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
|
||||
for s in scales:
|
||||
mask_h = random.randint(1, int(h * s)) # create random masks
|
||||
mask_w = random.randint(1, int(w * s))
|
||||
|
||||
# box
|
||||
xmin = max(0, random.randint(0, w) - mask_w // 2)
|
||||
ymin = max(0, random.randint(0, h) - mask_h // 2)
|
||||
xmax = min(w, xmin + mask_w)
|
||||
ymax = min(h, ymin + mask_h)
|
||||
|
||||
# apply random color mask
|
||||
im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
|
||||
|
||||
# return unobscured labels
|
||||
if len(labels) and s > 0.03:
|
||||
box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
|
||||
ioa = bbox_ioa(box, xywhn2xyxy(labels[:, 1:5], w, h)) # intersection over area
|
||||
labels = labels[ioa < 0.60] # remove >60% obscured labels
|
||||
|
||||
return labels
|
||||
|
||||
|
||||
def mixup(im, labels, im2, labels2):
|
||||
"""
|
||||
Applies MixUp augmentation by blending images and labels.
|
||||
|
||||
See https://arxiv.org/pdf/1710.09412.pdf for details.
|
||||
"""
|
||||
r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
|
||||
im = (im * r + im2 * (1 - r)).astype(np.uint8)
|
||||
labels = np.concatenate((labels, labels2), 0)
|
||||
return im, labels
|
||||
|
||||
|
||||
def box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):
|
||||
"""
|
||||
Filters bounding box candidates by minimum width-height threshold `wh_thr` (pixels), aspect ratio threshold
|
||||
`ar_thr`, and area ratio threshold `area_thr`.
|
||||
|
||||
box1(4,n) is before augmentation, box2(4,n) is after augmentation.
|
||||
"""
|
||||
w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
|
||||
w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
|
||||
ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
|
||||
return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
|
||||
|
||||
|
||||
def classify_albumentations(
|
||||
augment=True,
|
||||
size=224,
|
||||
scale=(0.08, 1.0),
|
||||
ratio=(0.75, 1.0 / 0.75), # 0.75, 1.33
|
||||
hflip=0.5,
|
||||
vflip=0.0,
|
||||
jitter=0.4,
|
||||
mean=IMAGENET_MEAN,
|
||||
std=IMAGENET_STD,
|
||||
auto_aug=False,
|
||||
):
|
||||
# YOLOv5 classification Albumentations (optional, only used if package is installed)
|
||||
"""Sets up and returns Albumentations transforms for YOLOv5 classification tasks depending on augmentation
|
||||
settings.
|
||||
"""
|
||||
prefix = colorstr("albumentations: ")
|
||||
try:
|
||||
import albumentations as A
|
||||
from albumentations.pytorch import ToTensorV2
|
||||
|
||||
check_version(A.__version__, "1.0.3", hard=True) # version requirement
|
||||
if augment: # Resize and crop
|
||||
T = [A.RandomResizedCrop(height=size, width=size, scale=scale, ratio=ratio)]
|
||||
if auto_aug:
|
||||
# TODO: implement AugMix, AutoAug & RandAug in albumentation
|
||||
LOGGER.info(f"{prefix}auto augmentations are currently not supported")
|
||||
else:
|
||||
if hflip > 0:
|
||||
T += [A.HorizontalFlip(p=hflip)]
|
||||
if vflip > 0:
|
||||
T += [A.VerticalFlip(p=vflip)]
|
||||
if jitter > 0:
|
||||
color_jitter = (float(jitter),) * 3 # repeat value for brightness, contrast, saturation, 0 hue
|
||||
T += [A.ColorJitter(*color_jitter, 0)]
|
||||
else: # Use fixed crop for eval set (reproducibility)
|
||||
T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]
|
||||
T += [A.Normalize(mean=mean, std=std), ToTensorV2()] # Normalize and convert to Tensor
|
||||
LOGGER.info(prefix + ", ".join(f"{x}".replace("always_apply=False, ", "") for x in T if x.p))
|
||||
return A.Compose(T)
|
||||
|
||||
except ImportError: # package not installed, skip
|
||||
LOGGER.warning(f"{prefix}⚠️ not found, install with `pip install albumentations` (recommended)")
|
||||
except Exception as e:
|
||||
LOGGER.info(f"{prefix}{e}")
|
||||
|
||||
|
||||
def classify_transforms(size=224):
|
||||
"""Applies a series of transformations including center crop, ToTensor, and normalization for classification."""
|
||||
assert isinstance(size, int), f"ERROR: classify_transforms size {size} must be integer, not (list, tuple)"
|
||||
# T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
|
||||
return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])
|
||||
|
||||
|
||||
class LetterBox:
|
||||
"""Resizes and pads images to specified dimensions while maintaining aspect ratio for YOLOv5 preprocessing."""
|
||||
|
||||
def __init__(self, size=(640, 640), auto=False, stride=32):
|
||||
"""Initializes a LetterBox object for YOLOv5 image preprocessing with optional auto sizing and stride
|
||||
adjustment.
|
||||
"""
|
||||
super().__init__()
|
||||
self.h, self.w = (size, size) if isinstance(size, int) else size
|
||||
self.auto = auto # pass max size integer, automatically solve for short side using stride
|
||||
self.stride = stride # used with auto
|
||||
|
||||
def __call__(self, im):
|
||||
"""
|
||||
Resizes and pads input image `im` (HWC format) to specified dimensions, maintaining aspect ratio.
|
||||
|
||||
im = np.array HWC
|
||||
"""
|
||||
imh, imw = im.shape[:2]
|
||||
r = min(self.h / imh, self.w / imw) # ratio of new/old
|
||||
h, w = round(imh * r), round(imw * r) # resized image
|
||||
hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w
|
||||
top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)
|
||||
im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)
|
||||
im_out[top : top + h, left : left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)
|
||||
return im_out
|
||||
|
||||
|
||||
class CenterCrop:
|
||||
"""Applies center crop to an image, resizing it to the specified size while maintaining aspect ratio."""
|
||||
|
||||
def __init__(self, size=640):
|
||||
"""Initializes CenterCrop for image preprocessing, accepting single int or tuple for size, defaults to 640."""
|
||||
super().__init__()
|
||||
self.h, self.w = (size, size) if isinstance(size, int) else size
|
||||
|
||||
def __call__(self, im):
|
||||
"""
|
||||
Applies center crop to the input image and resizes it to a specified size, maintaining aspect ratio.
|
||||
|
||||
im = np.array HWC
|
||||
"""
|
||||
imh, imw = im.shape[:2]
|
||||
m = min(imh, imw) # min dimension
|
||||
top, left = (imh - m) // 2, (imw - m) // 2
|
||||
return cv2.resize(im[top : top + m, left : left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)
|
||||
|
||||
|
||||
class ToTensor:
|
||||
"""Converts BGR np.array image from HWC to RGB CHW format, normalizes to [0, 1], and supports FP16 if half=True."""
|
||||
|
||||
def __init__(self, half=False):
|
||||
"""Initializes ToTensor for YOLOv5 image preprocessing, with optional half precision (half=True for FP16)."""
|
||||
super().__init__()
|
||||
self.half = half
|
||||
|
||||
def __call__(self, im):
|
||||
"""
|
||||
Converts BGR np.array image from HWC to RGB CHW format, and normalizes to [0, 1], with support for FP16 if
|
||||
`half=True`.
|
||||
|
||||
im = np.array HWC in BGR order
|
||||
"""
|
||||
im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1]) # HWC to CHW -> BGR to RGB -> contiguous
|
||||
im = torch.from_numpy(im) # to torch
|
||||
im = im.half() if self.half else im.float() # uint8 to fp16/32
|
||||
im /= 255.0 # 0-255 to 0.0-1.0
|
||||
return im
|
175
yolov5/utils/autoanchor.py
Normal file
175
yolov5/utils/autoanchor.py
Normal file
@ -0,0 +1,175 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""AutoAnchor utils."""
|
||||
|
||||
import random
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import yaml
|
||||
from tqdm import tqdm
|
||||
|
||||
from utils import TryExcept
|
||||
from utils.general import LOGGER, TQDM_BAR_FORMAT, colorstr
|
||||
|
||||
PREFIX = colorstr("AutoAnchor: ")
|
||||
|
||||
|
||||
def check_anchor_order(m):
|
||||
"""Checks and corrects anchor order against stride in YOLOv5 Detect() module if necessary."""
|
||||
a = m.anchors.prod(-1).mean(-1).view(-1) # mean anchor area per output layer
|
||||
da = a[-1] - a[0] # delta a
|
||||
ds = m.stride[-1] - m.stride[0] # delta s
|
||||
if da and (da.sign() != ds.sign()): # same order
|
||||
LOGGER.info(f"{PREFIX}Reversing anchor order")
|
||||
m.anchors[:] = m.anchors.flip(0)
|
||||
|
||||
|
||||
@TryExcept(f"{PREFIX}ERROR")
|
||||
def check_anchors(dataset, model, thr=4.0, imgsz=640):
|
||||
"""Evaluates anchor fit to dataset and adjusts if necessary, supporting customizable threshold and image size."""
|
||||
m = model.module.model[-1] if hasattr(model, "module") else model.model[-1] # Detect()
|
||||
shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
|
||||
scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
|
||||
wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
|
||||
|
||||
def metric(k): # compute metric
|
||||
"""Computes ratio metric, anchors above threshold, and best possible recall for YOLOv5 anchor evaluation."""
|
||||
r = wh[:, None] / k[None]
|
||||
x = torch.min(r, 1 / r).min(2)[0] # ratio metric
|
||||
best = x.max(1)[0] # best_x
|
||||
aat = (x > 1 / thr).float().sum(1).mean() # anchors above threshold
|
||||
bpr = (best > 1 / thr).float().mean() # best possible recall
|
||||
return bpr, aat
|
||||
|
||||
stride = m.stride.to(m.anchors.device).view(-1, 1, 1) # model strides
|
||||
anchors = m.anchors.clone() * stride # current anchors
|
||||
bpr, aat = metric(anchors.cpu().view(-1, 2))
|
||||
s = f"\n{PREFIX}{aat:.2f} anchors/target, {bpr:.3f} Best Possible Recall (BPR). "
|
||||
if bpr > 0.98: # threshold to recompute
|
||||
LOGGER.info(f"{s}Current anchors are a good fit to dataset ✅")
|
||||
else:
|
||||
LOGGER.info(f"{s}Anchors are a poor fit to dataset ⚠️, attempting to improve...")
|
||||
na = m.anchors.numel() // 2 # number of anchors
|
||||
anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
|
||||
new_bpr = metric(anchors)[0]
|
||||
if new_bpr > bpr: # replace anchors
|
||||
anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
|
||||
m.anchors[:] = anchors.clone().view_as(m.anchors)
|
||||
check_anchor_order(m) # must be in pixel-space (not grid-space)
|
||||
m.anchors /= stride
|
||||
s = f"{PREFIX}Done ✅ (optional: update model *.yaml to use these anchors in the future)"
|
||||
else:
|
||||
s = f"{PREFIX}Done ⚠️ (original anchors better than new anchors, proceeding with original anchors)"
|
||||
LOGGER.info(s)
|
||||
|
||||
|
||||
def kmean_anchors(dataset="./data/coco128.yaml", n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
|
||||
"""
|
||||
Creates kmeans-evolved anchors from training dataset.
|
||||
|
||||
Arguments:
|
||||
dataset: path to data.yaml, or a loaded dataset
|
||||
n: number of anchors
|
||||
img_size: image size used for training
|
||||
thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
|
||||
gen: generations to evolve anchors using genetic algorithm
|
||||
verbose: print all results
|
||||
|
||||
Return:
|
||||
k: kmeans evolved anchors
|
||||
|
||||
Usage:
|
||||
from utils.autoanchor import *; _ = kmean_anchors()
|
||||
"""
|
||||
from scipy.cluster.vq import kmeans
|
||||
|
||||
npr = np.random
|
||||
thr = 1 / thr
|
||||
|
||||
def metric(k, wh): # compute metrics
|
||||
"""Computes ratio metric, anchors above threshold, and best possible recall for YOLOv5 anchor evaluation."""
|
||||
r = wh[:, None] / k[None]
|
||||
x = torch.min(r, 1 / r).min(2)[0] # ratio metric
|
||||
# x = wh_iou(wh, torch.tensor(k)) # iou metric
|
||||
return x, x.max(1)[0] # x, best_x
|
||||
|
||||
def anchor_fitness(k): # mutation fitness
|
||||
"""Evaluates fitness of YOLOv5 anchors by computing recall and ratio metrics for an anchor evolution process."""
|
||||
_, best = metric(torch.tensor(k, dtype=torch.float32), wh)
|
||||
return (best * (best > thr).float()).mean() # fitness
|
||||
|
||||
def print_results(k, verbose=True):
|
||||
"""Sorts and logs kmeans-evolved anchor metrics and best possible recall values for YOLOv5 anchor evaluation."""
|
||||
k = k[np.argsort(k.prod(1))] # sort small to large
|
||||
x, best = metric(k, wh0)
|
||||
bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
|
||||
s = (
|
||||
f"{PREFIX}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr\n"
|
||||
f"{PREFIX}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, "
|
||||
f"past_thr={x[x > thr].mean():.3f}-mean: "
|
||||
)
|
||||
for x in k:
|
||||
s += "%i,%i, " % (round(x[0]), round(x[1]))
|
||||
if verbose:
|
||||
LOGGER.info(s[:-2])
|
||||
return k
|
||||
|
||||
if isinstance(dataset, str): # *.yaml file
|
||||
with open(dataset, errors="ignore") as f:
|
||||
data_dict = yaml.safe_load(f) # model dict
|
||||
from utils.dataloaders import LoadImagesAndLabels
|
||||
|
||||
dataset = LoadImagesAndLabels(data_dict["train"], augment=True, rect=True)
|
||||
|
||||
# Get label wh
|
||||
shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
|
||||
wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
|
||||
|
||||
# Filter
|
||||
i = (wh0 < 3.0).any(1).sum()
|
||||
if i:
|
||||
LOGGER.info(f"{PREFIX}WARNING ⚠️ Extremely small objects found: {i} of {len(wh0)} labels are <3 pixels in size")
|
||||
wh = wh0[(wh0 >= 2.0).any(1)].astype(np.float32) # filter > 2 pixels
|
||||
# wh = wh * (npr.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
|
||||
|
||||
# Kmeans init
|
||||
try:
|
||||
LOGGER.info(f"{PREFIX}Running kmeans for {n} anchors on {len(wh)} points...")
|
||||
assert n <= len(wh) # apply overdetermined constraint
|
||||
s = wh.std(0) # sigmas for whitening
|
||||
k = kmeans(wh / s, n, iter=30)[0] * s # points
|
||||
assert n == len(k) # kmeans may return fewer points than requested if wh is insufficient or too similar
|
||||
except Exception:
|
||||
LOGGER.warning(f"{PREFIX}WARNING ⚠️ switching strategies from kmeans to random init")
|
||||
k = np.sort(npr.rand(n * 2)).reshape(n, 2) * img_size # random init
|
||||
wh, wh0 = (torch.tensor(x, dtype=torch.float32) for x in (wh, wh0))
|
||||
k = print_results(k, verbose=False)
|
||||
|
||||
# Plot
|
||||
# k, d = [None] * 20, [None] * 20
|
||||
# for i in tqdm(range(1, 21)):
|
||||
# k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
|
||||
# fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
|
||||
# ax = ax.ravel()
|
||||
# ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
|
||||
# fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
|
||||
# ax[0].hist(wh[wh[:, 0]<100, 0],400)
|
||||
# ax[1].hist(wh[wh[:, 1]<100, 1],400)
|
||||
# fig.savefig('wh.png', dpi=200)
|
||||
|
||||
# Evolve
|
||||
f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
|
||||
pbar = tqdm(range(gen), bar_format=TQDM_BAR_FORMAT) # progress bar
|
||||
for _ in pbar:
|
||||
v = np.ones(sh)
|
||||
while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
|
||||
v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
|
||||
kg = (k.copy() * v).clip(min=2.0)
|
||||
fg = anchor_fitness(kg)
|
||||
if fg > f:
|
||||
f, k = fg, kg.copy()
|
||||
pbar.desc = f"{PREFIX}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}"
|
||||
if verbose:
|
||||
print_results(k, verbose)
|
||||
|
||||
return print_results(k).astype(np.float32)
|
70
yolov5/utils/autobatch.py
Normal file
70
yolov5/utils/autobatch.py
Normal file
@ -0,0 +1,70 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""Auto-batch utils."""
|
||||
|
||||
from copy import deepcopy
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from utils.general import LOGGER, colorstr
|
||||
from utils.torch_utils import profile
|
||||
|
||||
|
||||
def check_train_batch_size(model, imgsz=640, amp=True):
|
||||
"""Checks and computes optimal training batch size for YOLOv5 model, given image size and AMP setting."""
|
||||
with torch.cuda.amp.autocast(amp):
|
||||
return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size
|
||||
|
||||
|
||||
def autobatch(model, imgsz=640, fraction=0.8, batch_size=16):
|
||||
"""Estimates optimal YOLOv5 batch size using `fraction` of CUDA memory."""
|
||||
# Usage:
|
||||
# import torch
|
||||
# from utils.autobatch import autobatch
|
||||
# model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)
|
||||
# print(autobatch(model))
|
||||
|
||||
# Check device
|
||||
prefix = colorstr("AutoBatch: ")
|
||||
LOGGER.info(f"{prefix}Computing optimal batch size for --imgsz {imgsz}")
|
||||
device = next(model.parameters()).device # get model device
|
||||
if device.type == "cpu":
|
||||
LOGGER.info(f"{prefix}CUDA not detected, using default CPU batch-size {batch_size}")
|
||||
return batch_size
|
||||
if torch.backends.cudnn.benchmark:
|
||||
LOGGER.info(f"{prefix} ⚠️ Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}")
|
||||
return batch_size
|
||||
|
||||
# Inspect CUDA memory
|
||||
gb = 1 << 30 # bytes to GiB (1024 ** 3)
|
||||
d = str(device).upper() # 'CUDA:0'
|
||||
properties = torch.cuda.get_device_properties(device) # device properties
|
||||
t = properties.total_memory / gb # GiB total
|
||||
r = torch.cuda.memory_reserved(device) / gb # GiB reserved
|
||||
a = torch.cuda.memory_allocated(device) / gb # GiB allocated
|
||||
f = t - (r + a) # GiB free
|
||||
LOGGER.info(f"{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free")
|
||||
|
||||
# Profile batch sizes
|
||||
batch_sizes = [1, 2, 4, 8, 16]
|
||||
try:
|
||||
img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes]
|
||||
results = profile(img, model, n=3, device=device)
|
||||
except Exception as e:
|
||||
LOGGER.warning(f"{prefix}{e}")
|
||||
|
||||
# Fit a solution
|
||||
y = [x[2] for x in results if x] # memory [2]
|
||||
p = np.polyfit(batch_sizes[: len(y)], y, deg=1) # first degree polynomial fit
|
||||
b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size)
|
||||
if None in results: # some sizes failed
|
||||
i = results.index(None) # first fail index
|
||||
if b >= batch_sizes[i]: # y intercept above failure point
|
||||
b = batch_sizes[max(i - 1, 0)] # select prior safe point
|
||||
if b < 1 or b > 1024: # b outside of safe range
|
||||
b = batch_size
|
||||
LOGGER.warning(f"{prefix}WARNING ⚠️ CUDA anomaly detected, recommend restart environment and retry command.")
|
||||
|
||||
fraction = (np.polyval(p, b) + r + a) / t # actual fraction predicted
|
||||
LOGGER.info(f"{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅")
|
||||
return b
|
1
yolov5/utils/aws/__init__.py
Normal file
1
yolov5/utils/aws/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
26
yolov5/utils/aws/mime.sh
Normal file
26
yolov5/utils/aws/mime.sh
Normal file
@ -0,0 +1,26 @@
|
||||
# AWS EC2 instance startup 'MIME' script https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/
|
||||
# This script will run on every instance restart, not only on first start
|
||||
# --- DO NOT COPY ABOVE COMMENTS WHEN PASTING INTO USERDATA ---
|
||||
|
||||
Content-Type: multipart/mixed; boundary="//"
|
||||
MIME-Version: 1.0
|
||||
|
||||
--//
|
||||
Content-Type: text/cloud-config; charset="us-ascii"
|
||||
MIME-Version: 1.0
|
||||
Content-Transfer-Encoding: 7bit
|
||||
Content-Disposition: attachment; filename="cloud-config.txt"
|
||||
|
||||
#cloud-config
|
||||
cloud_final_modules:
|
||||
- [scripts-user, always]
|
||||
|
||||
--//
|
||||
Content-Type: text/x-shellscript; charset="us-ascii"
|
||||
MIME-Version: 1.0
|
||||
Content-Transfer-Encoding: 7bit
|
||||
Content-Disposition: attachment; filename="userdata.txt"
|
||||
|
||||
#!/bin/bash
|
||||
# --- paste contents of userdata.sh here ---
|
||||
--//
|
42
yolov5/utils/aws/resume.py
Normal file
42
yolov5/utils/aws/resume.py
Normal file
@ -0,0 +1,42 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
# Resume all interrupted trainings in yolov5/ dir including DDP trainings
|
||||
# Usage: $ python utils/aws/resume.py
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import yaml
|
||||
|
||||
FILE = Path(__file__).resolve()
|
||||
ROOT = FILE.parents[2] # YOLOv5 root directory
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.append(str(ROOT)) # add ROOT to PATH
|
||||
|
||||
port = 0 # --master_port
|
||||
path = Path("").resolve()
|
||||
for last in path.rglob("*/**/last.pt"):
|
||||
ckpt = torch.load(last)
|
||||
if ckpt["optimizer"] is None:
|
||||
continue
|
||||
|
||||
# Load opt.yaml
|
||||
with open(last.parent.parent / "opt.yaml", errors="ignore") as f:
|
||||
opt = yaml.safe_load(f)
|
||||
|
||||
# Get device count
|
||||
d = opt["device"].split(",") # devices
|
||||
nd = len(d) # number of devices
|
||||
ddp = nd > 1 or (nd == 0 and torch.cuda.device_count() > 1) # distributed data parallel
|
||||
|
||||
if ddp: # multi-GPU
|
||||
port += 1
|
||||
cmd = f"python -m torch.distributed.run --nproc_per_node {nd} --master_port {port} train.py --resume {last}"
|
||||
else: # single-GPU
|
||||
cmd = f"python train.py --resume {last}"
|
||||
|
||||
cmd += " > /dev/null 2>&1 &" # redirect output to dev/null and run in daemon thread
|
||||
print(cmd)
|
||||
os.system(cmd)
|
27
yolov5/utils/aws/userdata.sh
Normal file
27
yolov5/utils/aws/userdata.sh
Normal file
@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
# AWS EC2 instance startup script https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
|
||||
# This script will run only once on first instance start (for a re-start script see mime.sh)
|
||||
# /home/ubuntu (ubuntu) or /home/ec2-user (amazon-linux) is working dir
|
||||
# Use >300 GB SSD
|
||||
|
||||
cd home/ubuntu
|
||||
if [ ! -d yolov5 ]; then
|
||||
echo "Running first-time script." # install dependencies, download COCO, pull Docker
|
||||
git clone https://github.com/ultralytics/yolov5 -b master && sudo chmod -R 777 yolov5
|
||||
cd yolov5
|
||||
bash data/scripts/get_coco.sh && echo "COCO done." &
|
||||
sudo docker pull ultralytics/yolov5:latest && echo "Docker done." &
|
||||
python -m pip install --upgrade pip && pip install -r requirements.txt && python detect.py && echo "Requirements done." &
|
||||
wait && echo "All tasks done." # finish background tasks
|
||||
else
|
||||
echo "Running re-start script." # resume interrupted runs
|
||||
i=0
|
||||
list=$(sudo docker ps -qa) # container list i.e. $'one\ntwo\nthree\nfour'
|
||||
while IFS= read -r id; do
|
||||
((i++))
|
||||
echo "restarting container $i: $id"
|
||||
sudo docker start $id
|
||||
# sudo docker exec -it $id python train.py --resume # single-GPU
|
||||
sudo docker exec -d $id python utils/aws/resume.py # multi-scenario
|
||||
done <<<"$list"
|
||||
fi
|
72
yolov5/utils/callbacks.py
Normal file
72
yolov5/utils/callbacks.py
Normal file
@ -0,0 +1,72 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""Callback utils."""
|
||||
|
||||
import threading
|
||||
|
||||
|
||||
class Callbacks:
|
||||
"""Handles all registered callbacks for YOLOv5 Hooks."""
|
||||
|
||||
def __init__(self):
|
||||
"""Initializes a Callbacks object to manage registered YOLOv5 training event hooks."""
|
||||
self._callbacks = {
|
||||
"on_pretrain_routine_start": [],
|
||||
"on_pretrain_routine_end": [],
|
||||
"on_train_start": [],
|
||||
"on_train_epoch_start": [],
|
||||
"on_train_batch_start": [],
|
||||
"optimizer_step": [],
|
||||
"on_before_zero_grad": [],
|
||||
"on_train_batch_end": [],
|
||||
"on_train_epoch_end": [],
|
||||
"on_val_start": [],
|
||||
"on_val_batch_start": [],
|
||||
"on_val_image_end": [],
|
||||
"on_val_batch_end": [],
|
||||
"on_val_end": [],
|
||||
"on_fit_epoch_end": [], # fit = train + val
|
||||
"on_model_save": [],
|
||||
"on_train_end": [],
|
||||
"on_params_update": [],
|
||||
"teardown": [],
|
||||
}
|
||||
self.stop_training = False # set True to interrupt training
|
||||
|
||||
def register_action(self, hook, name="", callback=None):
|
||||
"""
|
||||
Register a new action to a callback hook.
|
||||
|
||||
Args:
|
||||
hook: The callback hook name to register the action to
|
||||
name: The name of the action for later reference
|
||||
callback: The callback to fire
|
||||
"""
|
||||
assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
|
||||
assert callable(callback), f"callback '{callback}' is not callable"
|
||||
self._callbacks[hook].append({"name": name, "callback": callback})
|
||||
|
||||
def get_registered_actions(self, hook=None):
|
||||
"""
|
||||
Returns all the registered actions by callback hook.
|
||||
|
||||
Args:
|
||||
hook: The name of the hook to check, defaults to all
|
||||
"""
|
||||
return self._callbacks[hook] if hook else self._callbacks
|
||||
|
||||
def run(self, hook, *args, thread=False, **kwargs):
|
||||
"""
|
||||
Loop through the registered actions and fire all callbacks on main thread.
|
||||
|
||||
Args:
|
||||
hook: The name of the hook to check, defaults to all
|
||||
args: Arguments to receive from YOLOv5
|
||||
thread: (boolean) Run callbacks in daemon thread
|
||||
kwargs: Keyword Arguments to receive from YOLOv5
|
||||
"""
|
||||
assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
|
||||
for logger in self._callbacks[hook]:
|
||||
if thread:
|
||||
threading.Thread(target=logger["callback"], args=args, kwargs=kwargs, daemon=True).start()
|
||||
else:
|
||||
logger["callback"](*args, **kwargs)
|
1378
yolov5/utils/dataloaders.py
Normal file
1378
yolov5/utils/dataloaders.py
Normal file
File diff suppressed because it is too large
Load Diff
73
yolov5/utils/docker/Dockerfile
Normal file
73
yolov5/utils/docker/Dockerfile
Normal file
@ -0,0 +1,73 @@
|
||||
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
|
||||
# Builds ultralytics/yolov5:latest image on DockerHub https://hub.docker.com/r/ultralytics/yolov5
|
||||
# Image is CUDA-optimized for YOLOv5 single/multi-GPU training and inference
|
||||
|
||||
# Start FROM PyTorch image https://hub.docker.com/r/pytorch/pytorch
|
||||
FROM pytorch/pytorch:2.0.0-cuda11.7-cudnn8-runtime
|
||||
|
||||
# Downloads to user config dir
|
||||
ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/
|
||||
|
||||
# Install linux packages
|
||||
ENV DEBIAN_FRONTEND noninteractive
|
||||
RUN apt update
|
||||
RUN TZ=Etc/UTC apt install -y tzdata
|
||||
RUN apt install --no-install-recommends -y gcc git zip curl htop libgl1 libglib2.0-0 libpython3-dev gnupg
|
||||
# RUN alias python=python3
|
||||
|
||||
# Security updates
|
||||
# https://security.snyk.io/vuln/SNYK-UBUNTU1804-OPENSSL-3314796
|
||||
RUN apt upgrade --no-install-recommends -y openssl
|
||||
|
||||
# Create working directory
|
||||
RUN rm -rf /usr/src/app && mkdir -p /usr/src/app
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
# Copy contents
|
||||
COPY . /usr/src/app
|
||||
|
||||
# Install pip packages
|
||||
COPY requirements.txt .
|
||||
RUN python3 -m pip install --upgrade pip wheel
|
||||
RUN pip install --no-cache -r requirements.txt albumentations comet gsutil notebook \
|
||||
coremltools onnx onnx-simplifier onnxruntime 'openvino-dev>=2023.0'
|
||||
# tensorflow tensorflowjs \
|
||||
|
||||
# Set environment variables
|
||||
ENV OMP_NUM_THREADS=1
|
||||
|
||||
# Cleanup
|
||||
ENV DEBIAN_FRONTEND teletype
|
||||
|
||||
|
||||
# Usage Examples -------------------------------------------------------------------------------------------------------
|
||||
|
||||
# Build and Push
|
||||
# t=ultralytics/yolov5:latest && sudo docker build -f utils/docker/Dockerfile -t $t . && sudo docker push $t
|
||||
|
||||
# Pull and Run
|
||||
# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t
|
||||
|
||||
# Pull and Run with local directory access
|
||||
# t=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v "$(pwd)"/datasets:/usr/src/datasets $t
|
||||
|
||||
# Kill all
|
||||
# sudo docker kill $(sudo docker ps -q)
|
||||
|
||||
# Kill all image-based
|
||||
# sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/yolov5:latest)
|
||||
|
||||
# DockerHub tag update
|
||||
# t=ultralytics/yolov5:latest tnew=ultralytics/yolov5:v6.2 && sudo docker pull $t && sudo docker tag $t $tnew && sudo docker push $tnew
|
||||
|
||||
# Clean up
|
||||
# sudo docker system prune -a --volumes
|
||||
|
||||
# Update Ubuntu drivers
|
||||
# https://www.maketecheasier.com/install-nvidia-drivers-ubuntu/
|
||||
|
||||
# DDP test
|
||||
# python -m torch.distributed.run --nproc_per_node 2 --master_port 1 train.py --epochs 3
|
||||
|
||||
# GCP VM from Image
|
||||
# docker.io/ultralytics/yolov5:latest
|
40
yolov5/utils/docker/Dockerfile-arm64
Normal file
40
yolov5/utils/docker/Dockerfile-arm64
Normal file
@ -0,0 +1,40 @@
|
||||
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
|
||||
# Builds ultralytics/yolov5:latest-arm64 image on DockerHub https://hub.docker.com/r/ultralytics/yolov5
|
||||
# Image is aarch64-compatible for Apple M1 and other ARM architectures i.e. Jetson Nano and Raspberry Pi
|
||||
|
||||
# Start FROM Ubuntu image https://hub.docker.com/_/ubuntu
|
||||
FROM arm64v8/ubuntu:22.10
|
||||
|
||||
# Downloads to user config dir
|
||||
ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/
|
||||
|
||||
# Install linux packages
|
||||
ENV DEBIAN_FRONTEND noninteractive
|
||||
RUN apt update
|
||||
RUN TZ=Etc/UTC apt install -y tzdata
|
||||
RUN apt install --no-install-recommends -y python3-pip git zip curl htop gcc libgl1 libglib2.0-0 libpython3-dev
|
||||
# RUN alias python=python3
|
||||
|
||||
# Install pip packages
|
||||
COPY requirements.txt .
|
||||
RUN python3 -m pip install --upgrade pip wheel
|
||||
RUN pip install --no-cache -r requirements.txt albumentations gsutil notebook \
|
||||
coremltools onnx onnxruntime
|
||||
# tensorflow-aarch64 tensorflowjs \
|
||||
|
||||
# Create working directory
|
||||
RUN mkdir -p /usr/src/app
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
# Copy contents
|
||||
COPY . /usr/src/app
|
||||
ENV DEBIAN_FRONTEND teletype
|
||||
|
||||
|
||||
# Usage Examples -------------------------------------------------------------------------------------------------------
|
||||
|
||||
# Build and Push
|
||||
# t=ultralytics/yolov5:latest-arm64 && sudo docker build --platform linux/arm64 -f utils/docker/Dockerfile-arm64 -t $t . && sudo docker push $t
|
||||
|
||||
# Pull and Run
|
||||
# t=ultralytics/yolov5:latest-arm64 && sudo docker pull $t && sudo docker run -it --ipc=host -v "$(pwd)"/datasets:/usr/src/datasets $t
|
42
yolov5/utils/docker/Dockerfile-cpu
Normal file
42
yolov5/utils/docker/Dockerfile-cpu
Normal file
@ -0,0 +1,42 @@
|
||||
# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
|
||||
# Builds ultralytics/yolov5:latest-cpu image on DockerHub https://hub.docker.com/r/ultralytics/yolov5
|
||||
# Image is CPU-optimized for ONNX, OpenVINO and PyTorch YOLOv5 deployments
|
||||
|
||||
# Start FROM Ubuntu image https://hub.docker.com/_/ubuntu
|
||||
FROM ubuntu:23.10
|
||||
|
||||
# Downloads to user config dir
|
||||
ADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/
|
||||
|
||||
# Install linux packages
|
||||
# g++ required to build 'tflite_support' and 'lap' packages, libusb-1.0-0 required for 'tflite_support' package
|
||||
RUN apt update \
|
||||
&& apt install --no-install-recommends -y python3-pip git zip curl htop libgl1 libglib2.0-0 libpython3-dev gnupg g++ libusb-1.0-0
|
||||
# RUN alias python=python3
|
||||
|
||||
# Remove python3.11/EXTERNALLY-MANAGED or use 'pip install --break-system-packages' avoid 'externally-managed-environment' Ubuntu nightly error
|
||||
RUN rm -rf /usr/lib/python3.11/EXTERNALLY-MANAGED
|
||||
|
||||
# Install pip packages
|
||||
COPY requirements.txt .
|
||||
RUN python3 -m pip install --upgrade pip wheel
|
||||
RUN pip install --no-cache -r requirements.txt albumentations gsutil notebook \
|
||||
coremltools onnx onnx-simplifier onnxruntime 'openvino-dev>=2023.0' \
|
||||
# tensorflow tensorflowjs \
|
||||
--extra-index-url https://download.pytorch.org/whl/cpu
|
||||
|
||||
# Create working directory
|
||||
RUN mkdir -p /usr/src/app
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
# Copy contents
|
||||
COPY . /usr/src/app
|
||||
|
||||
|
||||
# Usage Examples -------------------------------------------------------------------------------------------------------
|
||||
|
||||
# Build and Push
|
||||
# t=ultralytics/yolov5:latest-cpu && sudo docker build -f utils/docker/Dockerfile-cpu -t $t . && sudo docker push $t
|
||||
|
||||
# Pull and Run
|
||||
# t=ultralytics/yolov5:latest-cpu && sudo docker pull $t && sudo docker run -it --ipc=host -v "$(pwd)"/datasets:/usr/src/datasets $t
|
136
yolov5/utils/downloads.py
Normal file
136
yolov5/utils/downloads.py
Normal file
@ -0,0 +1,136 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""Download utils."""
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
import urllib
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
import torch
|
||||
|
||||
|
||||
def is_url(url, check=True):
|
||||
"""Determines if a string is a URL and optionally checks its existence online, returning a boolean."""
|
||||
try:
|
||||
url = str(url)
|
||||
result = urllib.parse.urlparse(url)
|
||||
assert all([result.scheme, result.netloc]) # check if is url
|
||||
return (urllib.request.urlopen(url).getcode() == 200) if check else True # check if exists online
|
||||
except (AssertionError, urllib.request.HTTPError):
|
||||
return False
|
||||
|
||||
|
||||
def gsutil_getsize(url=""):
|
||||
"""
|
||||
Returns the size in bytes of a file at a Google Cloud Storage URL using `gsutil du`.
|
||||
|
||||
Returns 0 if the command fails or output is empty.
|
||||
"""
|
||||
output = subprocess.check_output(["gsutil", "du", url], shell=True, encoding="utf-8")
|
||||
return int(output.split()[0]) if output else 0
|
||||
|
||||
|
||||
def url_getsize(url="https://ultralytics.com/images/bus.jpg"):
|
||||
"""Returns the size in bytes of a downloadable file at a given URL; defaults to -1 if not found."""
|
||||
response = requests.head(url, allow_redirects=True)
|
||||
return int(response.headers.get("content-length", -1))
|
||||
|
||||
|
||||
def curl_download(url, filename, *, silent: bool = False) -> bool:
|
||||
"""Download a file from a url to a filename using curl."""
|
||||
silent_option = "sS" if silent else "" # silent
|
||||
proc = subprocess.run(
|
||||
[
|
||||
"curl",
|
||||
"-#",
|
||||
f"-{silent_option}L",
|
||||
url,
|
||||
"--output",
|
||||
filename,
|
||||
"--retry",
|
||||
"9",
|
||||
"-C",
|
||||
"-",
|
||||
]
|
||||
)
|
||||
return proc.returncode == 0
|
||||
|
||||
|
||||
def safe_download(file, url, url2=None, min_bytes=1e0, error_msg=""):
|
||||
"""
|
||||
Downloads a file from a URL (or alternate URL) to a specified path if file is above a minimum size.
|
||||
|
||||
Removes incomplete downloads.
|
||||
"""
|
||||
from utils.general import LOGGER
|
||||
|
||||
file = Path(file)
|
||||
assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
|
||||
try: # url1
|
||||
LOGGER.info(f"Downloading {url} to {file}...")
|
||||
torch.hub.download_url_to_file(url, str(file), progress=LOGGER.level <= logging.INFO)
|
||||
assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check
|
||||
except Exception as e: # url2
|
||||
if file.exists():
|
||||
file.unlink() # remove partial downloads
|
||||
LOGGER.info(f"ERROR: {e}\nRe-attempting {url2 or url} to {file}...")
|
||||
# curl download, retry and resume on fail
|
||||
curl_download(url2 or url, file)
|
||||
finally:
|
||||
if not file.exists() or file.stat().st_size < min_bytes: # check
|
||||
if file.exists():
|
||||
file.unlink() # remove partial downloads
|
||||
LOGGER.info(f"ERROR: {assert_msg}\n{error_msg}")
|
||||
LOGGER.info("")
|
||||
|
||||
|
||||
def attempt_download(file, repo="ultralytics/yolov5", release="v7.0"):
|
||||
"""Downloads a file from GitHub release assets or via direct URL if not found locally, supporting backup
|
||||
versions.
|
||||
"""
|
||||
from utils.general import LOGGER
|
||||
|
||||
def github_assets(repository, version="latest"):
|
||||
"""Fetches GitHub repository release tag and asset names using the GitHub API."""
|
||||
if version != "latest":
|
||||
version = f"tags/{version}" # i.e. tags/v7.0
|
||||
response = requests.get(f"https://api.github.com/repos/{repository}/releases/{version}").json() # github api
|
||||
return response["tag_name"], [x["name"] for x in response["assets"]] # tag, assets
|
||||
|
||||
file = Path(str(file).strip().replace("'", ""))
|
||||
if not file.exists():
|
||||
# URL specified
|
||||
name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.
|
||||
if str(file).startswith(("http:/", "https:/")): # download
|
||||
url = str(file).replace(":/", "://") # Pathlib turns :// -> :/
|
||||
file = name.split("?")[0] # parse authentication https://url.com/file.txt?auth...
|
||||
if Path(file).is_file():
|
||||
LOGGER.info(f"Found {url} locally at {file}") # file already exists
|
||||
else:
|
||||
safe_download(file=file, url=url, min_bytes=1e5)
|
||||
return file
|
||||
|
||||
# GitHub assets
|
||||
assets = [f"yolov5{size}{suffix}.pt" for size in "nsmlx" for suffix in ("", "6", "-cls", "-seg")] # default
|
||||
try:
|
||||
tag, assets = github_assets(repo, release)
|
||||
except Exception:
|
||||
try:
|
||||
tag, assets = github_assets(repo) # latest release
|
||||
except Exception:
|
||||
try:
|
||||
tag = subprocess.check_output("git tag", shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
|
||||
except Exception:
|
||||
tag = release
|
||||
|
||||
if name in assets:
|
||||
file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
|
||||
safe_download(
|
||||
file,
|
||||
url=f"https://github.com/{repo}/releases/download/{tag}/{name}",
|
||||
min_bytes=1e5,
|
||||
error_msg=f"{file} missing, try downloading from https://github.com/{repo}/releases/{tag}",
|
||||
)
|
||||
|
||||
return str(file)
|
70
yolov5/utils/flask_rest_api/README.md
Normal file
70
yolov5/utils/flask_rest_api/README.md
Normal file
@ -0,0 +1,70 @@
|
||||
# Flask REST API
|
||||
|
||||
[REST](https://en.wikipedia.org/wiki/Representational_state_transfer) [API](https://en.wikipedia.org/wiki/API)s are commonly used to expose Machine Learning (ML) models to other services. This folder contains an example REST API created using Flask to expose the YOLOv5s model from [PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5/).
|
||||
|
||||
## Requirements
|
||||
|
||||
[Flask](https://palletsprojects.com/projects/flask/) is required. Install with:
|
||||
|
||||
```shell
|
||||
$ pip install Flask
|
||||
```
|
||||
|
||||
## Run
|
||||
|
||||
After Flask installation run:
|
||||
|
||||
```shell
|
||||
$ python3 restapi.py --port 5000
|
||||
```
|
||||
|
||||
Then use [curl](https://curl.se/) to perform a request:
|
||||
|
||||
```shell
|
||||
$ curl -X POST -F image=@zidane.jpg 'http://localhost:5000/v1/object-detection/yolov5s'
|
||||
```
|
||||
|
||||
The model inference results are returned as a JSON response:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"class": 0,
|
||||
"confidence": 0.8900438547,
|
||||
"height": 0.9318675399,
|
||||
"name": "person",
|
||||
"width": 0.3264600933,
|
||||
"xcenter": 0.7438579798,
|
||||
"ycenter": 0.5207948685
|
||||
},
|
||||
{
|
||||
"class": 0,
|
||||
"confidence": 0.8440024257,
|
||||
"height": 0.7155083418,
|
||||
"name": "person",
|
||||
"width": 0.6546785235,
|
||||
"xcenter": 0.427829951,
|
||||
"ycenter": 0.6334488392
|
||||
},
|
||||
{
|
||||
"class": 27,
|
||||
"confidence": 0.3771208823,
|
||||
"height": 0.3902671337,
|
||||
"name": "tie",
|
||||
"width": 0.0696444362,
|
||||
"xcenter": 0.3675483763,
|
||||
"ycenter": 0.7991207838
|
||||
},
|
||||
{
|
||||
"class": 27,
|
||||
"confidence": 0.3527112305,
|
||||
"height": 0.1540903747,
|
||||
"name": "tie",
|
||||
"width": 0.0336618312,
|
||||
"xcenter": 0.7814827561,
|
||||
"ycenter": 0.5065554976
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
An example python script to perform inference using [requests](https://docs.python-requests.org/en/master/) is given in `example_request.py`
|
0
yolov5/utils/flask_rest_api/__init__.py
Normal file
0
yolov5/utils/flask_rest_api/__init__.py
Normal file
17
yolov5/utils/flask_rest_api/example_request.py
Normal file
17
yolov5/utils/flask_rest_api/example_request.py
Normal file
@ -0,0 +1,17 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""Perform test request."""
|
||||
|
||||
import pprint
|
||||
|
||||
import requests
|
||||
|
||||
DETECTION_URL = "http://localhost:5000/v1/object-detection/yolov5s"
|
||||
IMAGE = "zidane.jpg"
|
||||
|
||||
# Read image
|
||||
with open(IMAGE, "rb") as f:
|
||||
image_data = f.read()
|
||||
|
||||
response = requests.post(DETECTION_URL, files={"image": image_data}).json()
|
||||
|
||||
pprint.pprint(response)
|
49
yolov5/utils/flask_rest_api/restapi.py
Normal file
49
yolov5/utils/flask_rest_api/restapi.py
Normal file
@ -0,0 +1,49 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""Run a Flask REST API exposing one or more YOLOv5s models."""
|
||||
|
||||
import argparse
|
||||
import io
|
||||
|
||||
import torch
|
||||
from flask import Flask, request
|
||||
from PIL import Image
|
||||
|
||||
app = Flask(__name__)
|
||||
models = {}
|
||||
|
||||
DETECTION_URL = "/v1/object-detection/<model>"
|
||||
|
||||
|
||||
@app.route(DETECTION_URL, methods=["POST"])
|
||||
def predict(model):
|
||||
"""Predict and return object detections in JSON format given an image and model name via a Flask REST API POST
|
||||
request.
|
||||
"""
|
||||
if request.method != "POST":
|
||||
return
|
||||
|
||||
if request.files.get("image"):
|
||||
# Method 1
|
||||
# with request.files["image"] as f:
|
||||
# im = Image.open(io.BytesIO(f.read()))
|
||||
|
||||
# Method 2
|
||||
im_file = request.files["image"]
|
||||
im_bytes = im_file.read()
|
||||
im = Image.open(io.BytesIO(im_bytes))
|
||||
|
||||
if model in models:
|
||||
results = models[model](im, size=640) # reduce size=320 for faster inference
|
||||
return results.pandas().xyxy[0].to_json(orient="records")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="Flask API exposing YOLOv5 model")
|
||||
parser.add_argument("--port", default=5000, type=int, help="port number")
|
||||
parser.add_argument("--model", nargs="+", default=["yolov5s"], help="model(s) to run, i.e. --model yolov5n yolov5s")
|
||||
opt = parser.parse_args()
|
||||
|
||||
for m in opt.model:
|
||||
models[m] = torch.hub.load("ultralytics/yolov5", m, force_reload=True, skip_validation=True)
|
||||
|
||||
app.run(host="0.0.0.0", port=opt.port) # debug=True causes Restarting with stat
|
1293
yolov5/utils/general.py
Normal file
1293
yolov5/utils/general.py
Normal file
File diff suppressed because it is too large
Load Diff
25
yolov5/utils/google_app_engine/Dockerfile
Normal file
25
yolov5/utils/google_app_engine/Dockerfile
Normal file
@ -0,0 +1,25 @@
|
||||
FROM gcr.io/google-appengine/python
|
||||
|
||||
# Create a virtualenv for dependencies. This isolates these packages from
|
||||
# system-level packages.
|
||||
# Use -p python3 or -p python3.7 to select python version. Default is version 2.
|
||||
RUN virtualenv /env -p python3
|
||||
|
||||
# Setting these environment variables are the same as running
|
||||
# source /env/bin/activate.
|
||||
ENV VIRTUAL_ENV /env
|
||||
ENV PATH /env/bin:$PATH
|
||||
|
||||
RUN apt-get update && apt-get install -y python-opencv
|
||||
|
||||
# Copy the application's requirements.txt and run pip to install all
|
||||
# dependencies into the virtualenv.
|
||||
ADD requirements.txt /app/requirements.txt
|
||||
RUN pip install -r /app/requirements.txt
|
||||
|
||||
# Add the application source code.
|
||||
ADD . /app
|
||||
|
||||
# Run a WSGI server to serve the application. gunicorn must be declared as
|
||||
# a dependency in requirements.txt.
|
||||
CMD gunicorn -b :$PORT main:app
|
@ -0,0 +1,6 @@
|
||||
# add these requirements in your app on top of the existing ones
|
||||
pip==23.3
|
||||
Flask==2.3.2
|
||||
gunicorn==22.0.0
|
||||
werkzeug>=3.0.1 # not directly required, pinned by Snyk to avoid a vulnerability
|
||||
zipp>=3.19.1 # not directly required, pinned by Snyk to avoid a vulnerability
|
16
yolov5/utils/google_app_engine/app.yaml
Normal file
16
yolov5/utils/google_app_engine/app.yaml
Normal file
@ -0,0 +1,16 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
runtime: custom
|
||||
env: flex
|
||||
|
||||
service: yolov5app
|
||||
|
||||
liveness_check:
|
||||
initial_delay_sec: 600
|
||||
|
||||
manual_scaling:
|
||||
instances: 1
|
||||
resources:
|
||||
cpu: 1
|
||||
memory_gb: 4
|
||||
disk_size_gb: 20
|
476
yolov5/utils/loggers/__init__.py
Normal file
476
yolov5/utils/loggers/__init__.py
Normal file
@ -0,0 +1,476 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""Logging utils."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
import pkg_resources as pkg
|
||||
import torch
|
||||
|
||||
from utils.general import LOGGER, colorstr, cv2
|
||||
from utils.loggers.clearml.clearml_utils import ClearmlLogger
|
||||
from utils.loggers.wandb.wandb_utils import WandbLogger
|
||||
from utils.plots import plot_images, plot_labels, plot_results
|
||||
from utils.torch_utils import de_parallel
|
||||
|
||||
LOGGERS = ("csv", "tb", "wandb", "clearml", "comet") # *.csv, TensorBoard, Weights & Biases, ClearML
|
||||
RANK = int(os.getenv("RANK", -1))
|
||||
|
||||
try:
|
||||
from torch.utils.tensorboard import SummaryWriter
|
||||
except ImportError:
|
||||
|
||||
def SummaryWriter(*args):
|
||||
"""Fall back to SummaryWriter returning None if TensorBoard is not installed."""
|
||||
return None # None = SummaryWriter(str)
|
||||
|
||||
|
||||
try:
|
||||
import wandb
|
||||
|
||||
assert hasattr(wandb, "__version__") # verify package import not local dir
|
||||
if pkg.parse_version(wandb.__version__) >= pkg.parse_version("0.12.2") and RANK in {0, -1}:
|
||||
try:
|
||||
wandb_login_success = wandb.login(timeout=30)
|
||||
except wandb.errors.UsageError: # known non-TTY terminal issue
|
||||
wandb_login_success = False
|
||||
if not wandb_login_success:
|
||||
wandb = None
|
||||
except (ImportError, AssertionError):
|
||||
wandb = None
|
||||
|
||||
try:
|
||||
import clearml
|
||||
|
||||
assert hasattr(clearml, "__version__") # verify package import not local dir
|
||||
except (ImportError, AssertionError):
|
||||
clearml = None
|
||||
|
||||
try:
|
||||
if RANK in {0, -1}:
|
||||
import comet_ml
|
||||
|
||||
assert hasattr(comet_ml, "__version__") # verify package import not local dir
|
||||
from utils.loggers.comet import CometLogger
|
||||
|
||||
else:
|
||||
comet_ml = None
|
||||
except (ImportError, AssertionError):
|
||||
comet_ml = None
|
||||
|
||||
|
||||
def _json_default(value):
|
||||
"""
|
||||
Format `value` for JSON serialization (e.g. unwrap tensors).
|
||||
|
||||
Fall back to strings.
|
||||
"""
|
||||
if isinstance(value, torch.Tensor):
|
||||
try:
|
||||
value = value.item()
|
||||
except ValueError: # "only one element tensors can be converted to Python scalars"
|
||||
pass
|
||||
return value if isinstance(value, float) else str(value)
|
||||
|
||||
|
||||
class Loggers:
|
||||
"""Initializes and manages various logging utilities for tracking YOLOv5 training and validation metrics."""
|
||||
|
||||
def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS):
|
||||
"""Initializes loggers for YOLOv5 training and validation metrics, paths, and options."""
|
||||
self.save_dir = save_dir
|
||||
self.weights = weights
|
||||
self.opt = opt
|
||||
self.hyp = hyp
|
||||
self.plots = not opt.noplots # plot results
|
||||
self.logger = logger # for printing results to console
|
||||
self.include = include
|
||||
self.keys = [
|
||||
"train/box_loss",
|
||||
"train/obj_loss",
|
||||
"train/cls_loss", # train loss
|
||||
"metrics/precision",
|
||||
"metrics/recall",
|
||||
"metrics/mAP_0.5",
|
||||
"metrics/mAP_0.5:0.95", # metrics
|
||||
"val/box_loss",
|
||||
"val/obj_loss",
|
||||
"val/cls_loss", # val loss
|
||||
"x/lr0",
|
||||
"x/lr1",
|
||||
"x/lr2",
|
||||
] # params
|
||||
self.best_keys = ["best/epoch", "best/precision", "best/recall", "best/mAP_0.5", "best/mAP_0.5:0.95"]
|
||||
for k in LOGGERS:
|
||||
setattr(self, k, None) # init empty logger dictionary
|
||||
self.csv = True # always log to csv
|
||||
self.ndjson_console = "ndjson_console" in self.include # log ndjson to console
|
||||
self.ndjson_file = "ndjson_file" in self.include # log ndjson to file
|
||||
|
||||
# Messages
|
||||
if not comet_ml:
|
||||
prefix = colorstr("Comet: ")
|
||||
s = f"{prefix}run 'pip install comet_ml' to automatically track and visualize YOLOv5 🚀 runs in Comet"
|
||||
self.logger.info(s)
|
||||
# TensorBoard
|
||||
s = self.save_dir
|
||||
if "tb" in self.include and not self.opt.evolve:
|
||||
prefix = colorstr("TensorBoard: ")
|
||||
self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/")
|
||||
self.tb = SummaryWriter(str(s))
|
||||
|
||||
# W&B
|
||||
if wandb and "wandb" in self.include:
|
||||
self.opt.hyp = self.hyp # add hyperparameters
|
||||
self.wandb = WandbLogger(self.opt)
|
||||
else:
|
||||
self.wandb = None
|
||||
|
||||
# ClearML
|
||||
if clearml and "clearml" in self.include:
|
||||
try:
|
||||
self.clearml = ClearmlLogger(self.opt, self.hyp)
|
||||
except Exception:
|
||||
self.clearml = None
|
||||
prefix = colorstr("ClearML: ")
|
||||
LOGGER.warning(
|
||||
f"{prefix}WARNING ⚠️ ClearML is installed but not configured, skipping ClearML logging."
|
||||
f" See https://docs.ultralytics.com/yolov5/tutorials/clearml_logging_integration#readme"
|
||||
)
|
||||
|
||||
else:
|
||||
self.clearml = None
|
||||
|
||||
# Comet
|
||||
if comet_ml and "comet" in self.include:
|
||||
if isinstance(self.opt.resume, str) and self.opt.resume.startswith("comet://"):
|
||||
run_id = self.opt.resume.split("/")[-1]
|
||||
self.comet_logger = CometLogger(self.opt, self.hyp, run_id=run_id)
|
||||
|
||||
else:
|
||||
self.comet_logger = CometLogger(self.opt, self.hyp)
|
||||
|
||||
else:
|
||||
self.comet_logger = None
|
||||
|
||||
@property
|
||||
def remote_dataset(self):
|
||||
"""Fetches dataset dictionary from remote logging services like ClearML, Weights & Biases, or Comet ML."""
|
||||
data_dict = None
|
||||
if self.clearml:
|
||||
data_dict = self.clearml.data_dict
|
||||
if self.wandb:
|
||||
data_dict = self.wandb.data_dict
|
||||
if self.comet_logger:
|
||||
data_dict = self.comet_logger.data_dict
|
||||
|
||||
return data_dict
|
||||
|
||||
def on_train_start(self):
|
||||
"""Initializes the training process for Comet ML logger if it's configured."""
|
||||
if self.comet_logger:
|
||||
self.comet_logger.on_train_start()
|
||||
|
||||
def on_pretrain_routine_start(self):
|
||||
"""Invokes pre-training routine start hook for Comet ML logger if available."""
|
||||
if self.comet_logger:
|
||||
self.comet_logger.on_pretrain_routine_start()
|
||||
|
||||
def on_pretrain_routine_end(self, labels, names):
|
||||
"""Callback that runs at the end of pre-training routine, logging label plots if enabled."""
|
||||
if self.plots:
|
||||
plot_labels(labels, names, self.save_dir)
|
||||
paths = self.save_dir.glob("*labels*.jpg") # training labels
|
||||
if self.wandb:
|
||||
self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]})
|
||||
if self.comet_logger:
|
||||
self.comet_logger.on_pretrain_routine_end(paths)
|
||||
if self.clearml:
|
||||
for path in paths:
|
||||
self.clearml.log_plot(title=path.stem, plot_path=path)
|
||||
|
||||
def on_train_batch_end(self, model, ni, imgs, targets, paths, vals):
|
||||
"""Logs training batch end events, plots images, and updates external loggers with batch-end data."""
|
||||
log_dict = dict(zip(self.keys[:3], vals))
|
||||
# Callback runs on train batch end
|
||||
# ni: number integrated batches (since train start)
|
||||
if self.plots:
|
||||
if ni < 3:
|
||||
f = self.save_dir / f"train_batch{ni}.jpg" # filename
|
||||
plot_images(imgs, targets, paths, f)
|
||||
if ni == 0 and self.tb and not self.opt.sync_bn:
|
||||
log_tensorboard_graph(self.tb, model, imgsz=(self.opt.imgsz, self.opt.imgsz))
|
||||
if ni == 10 and (self.wandb or self.clearml):
|
||||
files = sorted(self.save_dir.glob("train*.jpg"))
|
||||
if self.wandb:
|
||||
self.wandb.log({"Mosaics": [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]})
|
||||
if self.clearml:
|
||||
self.clearml.log_debug_samples(files, title="Mosaics")
|
||||
|
||||
if self.comet_logger:
|
||||
self.comet_logger.on_train_batch_end(log_dict, step=ni)
|
||||
|
||||
def on_train_epoch_end(self, epoch):
|
||||
"""Callback that updates the current epoch in Weights & Biases at the end of a training epoch."""
|
||||
if self.wandb:
|
||||
self.wandb.current_epoch = epoch + 1
|
||||
|
||||
if self.comet_logger:
|
||||
self.comet_logger.on_train_epoch_end(epoch)
|
||||
|
||||
def on_val_start(self):
|
||||
"""Callback that signals the start of a validation phase to the Comet logger."""
|
||||
if self.comet_logger:
|
||||
self.comet_logger.on_val_start()
|
||||
|
||||
def on_val_image_end(self, pred, predn, path, names, im):
|
||||
"""Callback that logs a validation image and its predictions to WandB or ClearML."""
|
||||
if self.wandb:
|
||||
self.wandb.val_one_image(pred, predn, path, names, im)
|
||||
if self.clearml:
|
||||
self.clearml.log_image_with_boxes(path, pred, names, im)
|
||||
|
||||
def on_val_batch_end(self, batch_i, im, targets, paths, shapes, out):
|
||||
"""Logs validation batch results to Comet ML during training at the end of each validation batch."""
|
||||
if self.comet_logger:
|
||||
self.comet_logger.on_val_batch_end(batch_i, im, targets, paths, shapes, out)
|
||||
|
||||
def on_val_end(self, nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusion_matrix):
|
||||
"""Logs validation results to WandB or ClearML at the end of the validation process."""
|
||||
if self.wandb or self.clearml:
|
||||
files = sorted(self.save_dir.glob("val*.jpg"))
|
||||
if self.wandb:
|
||||
self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]})
|
||||
if self.clearml:
|
||||
self.clearml.log_debug_samples(files, title="Validation")
|
||||
|
||||
if self.comet_logger:
|
||||
self.comet_logger.on_val_end(nt, tp, fp, p, r, f1, ap, ap50, ap_class, confusion_matrix)
|
||||
|
||||
def on_fit_epoch_end(self, vals, epoch, best_fitness, fi):
|
||||
"""Callback that logs metrics and saves them to CSV or NDJSON at the end of each fit (train+val) epoch."""
|
||||
x = dict(zip(self.keys, vals))
|
||||
if self.csv:
|
||||
file = self.save_dir / "results.csv"
|
||||
n = len(x) + 1 # number of cols
|
||||
s = "" if file.exists() else (("%20s," * n % tuple(["epoch"] + self.keys)).rstrip(",") + "\n") # add header
|
||||
with open(file, "a") as f:
|
||||
f.write(s + ("%20.5g," * n % tuple([epoch] + vals)).rstrip(",") + "\n")
|
||||
if self.ndjson_console or self.ndjson_file:
|
||||
json_data = json.dumps(dict(epoch=epoch, **x), default=_json_default)
|
||||
if self.ndjson_console:
|
||||
print(json_data)
|
||||
if self.ndjson_file:
|
||||
file = self.save_dir / "results.ndjson"
|
||||
with open(file, "a") as f:
|
||||
print(json_data, file=f)
|
||||
|
||||
if self.tb:
|
||||
for k, v in x.items():
|
||||
self.tb.add_scalar(k, v, epoch)
|
||||
elif self.clearml: # log to ClearML if TensorBoard not used
|
||||
self.clearml.log_scalars(x, epoch)
|
||||
|
||||
if self.wandb:
|
||||
if best_fitness == fi:
|
||||
best_results = [epoch] + vals[3:7]
|
||||
for i, name in enumerate(self.best_keys):
|
||||
self.wandb.wandb_run.summary[name] = best_results[i] # log best results in the summary
|
||||
self.wandb.log(x)
|
||||
self.wandb.end_epoch()
|
||||
|
||||
if self.clearml:
|
||||
self.clearml.current_epoch_logged_images = set() # reset epoch image limit
|
||||
self.clearml.current_epoch += 1
|
||||
|
||||
if self.comet_logger:
|
||||
self.comet_logger.on_fit_epoch_end(x, epoch=epoch)
|
||||
|
||||
def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
|
||||
"""Callback that handles model saving events, logging to Weights & Biases or ClearML if enabled."""
|
||||
if (epoch + 1) % self.opt.save_period == 0 and not final_epoch and self.opt.save_period != -1:
|
||||
if self.wandb:
|
||||
self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi)
|
||||
if self.clearml:
|
||||
self.clearml.task.update_output_model(
|
||||
model_path=str(last), model_name="Latest Model", auto_delete_file=False
|
||||
)
|
||||
|
||||
if self.comet_logger:
|
||||
self.comet_logger.on_model_save(last, epoch, final_epoch, best_fitness, fi)
|
||||
|
||||
def on_train_end(self, last, best, epoch, results):
|
||||
"""Callback that runs at the end of training to save plots and log results."""
|
||||
if self.plots:
|
||||
plot_results(file=self.save_dir / "results.csv") # save results.png
|
||||
files = ["results.png", "confusion_matrix.png", *(f"{x}_curve.png" for x in ("F1", "PR", "P", "R"))]
|
||||
files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter
|
||||
self.logger.info(f"Results saved to {colorstr('bold', self.save_dir)}")
|
||||
|
||||
if self.tb and not self.clearml: # These images are already captured by ClearML by now, we don't want doubles
|
||||
for f in files:
|
||||
self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats="HWC")
|
||||
|
||||
if self.wandb:
|
||||
self.wandb.log(dict(zip(self.keys[3:10], results)))
|
||||
self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]})
|
||||
# Calling wandb.log. TODO: Refactor this into WandbLogger.log_model
|
||||
if not self.opt.evolve:
|
||||
wandb.log_artifact(
|
||||
str(best if best.exists() else last),
|
||||
type="model",
|
||||
name=f"run_{self.wandb.wandb_run.id}_model",
|
||||
aliases=["latest", "best", "stripped"],
|
||||
)
|
||||
self.wandb.finish_run()
|
||||
|
||||
if self.clearml and not self.opt.evolve:
|
||||
self.clearml.log_summary(dict(zip(self.keys[3:10], results)))
|
||||
[self.clearml.log_plot(title=f.stem, plot_path=f) for f in files]
|
||||
self.clearml.log_model(
|
||||
str(best if best.exists() else last), "Best Model" if best.exists() else "Last Model", epoch
|
||||
)
|
||||
|
||||
if self.comet_logger:
|
||||
final_results = dict(zip(self.keys[3:10], results))
|
||||
self.comet_logger.on_train_end(files, self.save_dir, last, best, epoch, final_results)
|
||||
|
||||
def on_params_update(self, params: dict):
|
||||
"""Updates experiment hyperparameters or configurations in WandB, Comet, or ClearML."""
|
||||
if self.wandb:
|
||||
self.wandb.wandb_run.config.update(params, allow_val_change=True)
|
||||
if self.comet_logger:
|
||||
self.comet_logger.on_params_update(params)
|
||||
if self.clearml:
|
||||
self.clearml.task.connect(params)
|
||||
|
||||
|
||||
class GenericLogger:
|
||||
"""
|
||||
YOLOv5 General purpose logger for non-task specific logging
|
||||
Usage: from utils.loggers import GenericLogger; logger = GenericLogger(...).
|
||||
|
||||
Arguments:
|
||||
opt: Run arguments
|
||||
console_logger: Console logger
|
||||
include: loggers to include
|
||||
"""
|
||||
|
||||
def __init__(self, opt, console_logger, include=("tb", "wandb", "clearml")):
|
||||
"""Initializes a generic logger with optional TensorBoard, W&B, and ClearML support."""
|
||||
self.save_dir = Path(opt.save_dir)
|
||||
self.include = include
|
||||
self.console_logger = console_logger
|
||||
self.csv = self.save_dir / "results.csv" # CSV logger
|
||||
if "tb" in self.include:
|
||||
prefix = colorstr("TensorBoard: ")
|
||||
self.console_logger.info(
|
||||
f"{prefix}Start with 'tensorboard --logdir {self.save_dir.parent}', view at http://localhost:6006/"
|
||||
)
|
||||
self.tb = SummaryWriter(str(self.save_dir))
|
||||
|
||||
if wandb and "wandb" in self.include:
|
||||
self.wandb = wandb.init(
|
||||
project=web_project_name(str(opt.project)), name=None if opt.name == "exp" else opt.name, config=opt
|
||||
)
|
||||
else:
|
||||
self.wandb = None
|
||||
|
||||
if clearml and "clearml" in self.include:
|
||||
try:
|
||||
# Hyp is not available in classification mode
|
||||
hyp = {} if "hyp" not in opt else opt.hyp
|
||||
self.clearml = ClearmlLogger(opt, hyp)
|
||||
except Exception:
|
||||
self.clearml = None
|
||||
prefix = colorstr("ClearML: ")
|
||||
LOGGER.warning(
|
||||
f"{prefix}WARNING ⚠️ ClearML is installed but not configured, skipping ClearML logging."
|
||||
f" See https://docs.ultralytics.com/yolov5/tutorials/clearml_logging_integration"
|
||||
)
|
||||
else:
|
||||
self.clearml = None
|
||||
|
||||
def log_metrics(self, metrics, epoch):
|
||||
"""Logs metrics to CSV, TensorBoard, W&B, and ClearML; `metrics` is a dict, `epoch` is an int."""
|
||||
if self.csv:
|
||||
keys, vals = list(metrics.keys()), list(metrics.values())
|
||||
n = len(metrics) + 1 # number of cols
|
||||
s = "" if self.csv.exists() else (("%23s," * n % tuple(["epoch"] + keys)).rstrip(",") + "\n") # header
|
||||
with open(self.csv, "a") as f:
|
||||
f.write(s + ("%23.5g," * n % tuple([epoch] + vals)).rstrip(",") + "\n")
|
||||
|
||||
if self.tb:
|
||||
for k, v in metrics.items():
|
||||
self.tb.add_scalar(k, v, epoch)
|
||||
|
||||
if self.wandb:
|
||||
self.wandb.log(metrics, step=epoch)
|
||||
|
||||
if self.clearml:
|
||||
self.clearml.log_scalars(metrics, epoch)
|
||||
|
||||
def log_images(self, files, name="Images", epoch=0):
|
||||
"""Logs images to all loggers with optional naming and epoch specification."""
|
||||
files = [Path(f) for f in (files if isinstance(files, (tuple, list)) else [files])] # to Path
|
||||
files = [f for f in files if f.exists()] # filter by exists
|
||||
|
||||
if self.tb:
|
||||
for f in files:
|
||||
self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats="HWC")
|
||||
|
||||
if self.wandb:
|
||||
self.wandb.log({name: [wandb.Image(str(f), caption=f.name) for f in files]}, step=epoch)
|
||||
|
||||
if self.clearml:
|
||||
if name == "Results":
|
||||
[self.clearml.log_plot(f.stem, f) for f in files]
|
||||
else:
|
||||
self.clearml.log_debug_samples(files, title=name)
|
||||
|
||||
def log_graph(self, model, imgsz=(640, 640)):
|
||||
"""Logs model graph to all configured loggers with specified input image size."""
|
||||
if self.tb:
|
||||
log_tensorboard_graph(self.tb, model, imgsz)
|
||||
|
||||
def log_model(self, model_path, epoch=0, metadata=None):
|
||||
"""Logs the model to all configured loggers with optional epoch and metadata."""
|
||||
if metadata is None:
|
||||
metadata = {}
|
||||
# Log model to all loggers
|
||||
if self.wandb:
|
||||
art = wandb.Artifact(name=f"run_{wandb.run.id}_model", type="model", metadata=metadata)
|
||||
art.add_file(str(model_path))
|
||||
wandb.log_artifact(art)
|
||||
if self.clearml:
|
||||
self.clearml.log_model(model_path=model_path, model_name=model_path.stem)
|
||||
|
||||
def update_params(self, params):
|
||||
"""Updates logged parameters in WandB and/or ClearML if enabled."""
|
||||
if self.wandb:
|
||||
wandb.run.config.update(params, allow_val_change=True)
|
||||
if self.clearml:
|
||||
self.clearml.task.connect(params)
|
||||
|
||||
|
||||
def log_tensorboard_graph(tb, model, imgsz=(640, 640)):
|
||||
"""Logs the model graph to TensorBoard with specified image size and model."""
|
||||
try:
|
||||
p = next(model.parameters()) # for device, type
|
||||
imgsz = (imgsz, imgsz) if isinstance(imgsz, int) else imgsz # expand
|
||||
im = torch.zeros((1, 3, *imgsz)).to(p.device).type_as(p) # input image (WARNING: must be zeros, not empty)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore") # suppress jit trace warning
|
||||
tb.add_graph(torch.jit.trace(de_parallel(model), im, strict=False), [])
|
||||
except Exception as e:
|
||||
LOGGER.warning(f"WARNING ⚠️ TensorBoard graph visualization failure {e}")
|
||||
|
||||
|
||||
def web_project_name(project):
|
||||
"""Converts a local project name to a standardized web project name with optional suffixes."""
|
||||
if not project.startswith("runs/train"):
|
||||
return project
|
||||
suffix = "-Classify" if project.endswith("-cls") else "-Segment" if project.endswith("-seg") else ""
|
||||
return f"YOLOv5{suffix}"
|
222
yolov5/utils/loggers/clearml/README.md
Normal file
222
yolov5/utils/loggers/clearml/README.md
Normal file
@ -0,0 +1,222 @@
|
||||
# ClearML Integration
|
||||
|
||||
<img align="center" src="https://github.com/thepycoder/clearml_screenshots/raw/main/logos_dark.png#gh-light-mode-only" alt="Clear|ML"><img align="center" src="https://github.com/thepycoder/clearml_screenshots/raw/main/logos_light.png#gh-dark-mode-only" alt="Clear|ML">
|
||||
|
||||
## About ClearML
|
||||
|
||||
[ClearML](https://clear.ml/) is an [open-source](https://github.com/clearml/clearml) toolbox designed to save you time ⏱️.
|
||||
|
||||
🔨 Track every YOLOv5 training run in the <b>experiment manager</b>
|
||||
|
||||
🔧 Version and easily access your custom training data with the integrated ClearML <b>Data Versioning Tool</b>
|
||||
|
||||
🔦 <b>Remotely train and monitor</b> your YOLOv5 training runs using ClearML Agent
|
||||
|
||||
🔬 Get the very best mAP using ClearML <b>Hyperparameter Optimization</b>
|
||||
|
||||
🔭 Turn your newly trained <b>YOLOv5 model into an API</b> with just a few commands using ClearML Serving
|
||||
|
||||
And so much more. It's up to you how many of these tools you want to use, you can stick to the experiment manager, or chain them all together into an impressive pipeline!
|
||||
|
||||

|
||||
|
||||
## 🦾 Setting Things Up
|
||||
|
||||
To keep track of your experiments and/or data, ClearML needs to communicate to a server. You have 2 options to get one:
|
||||
|
||||
Either sign up for free to the [ClearML Hosted Service](https://clear.ml/) or you can set up your own server, see [here](https://clear.ml/docs/latest/docs/deploying_clearml/clearml_server). Even the server is open-source, so even if you're dealing with sensitive data, you should be good to go!
|
||||
|
||||
1. Install the `clearml` python package:
|
||||
|
||||
```bash
|
||||
pip install clearml
|
||||
```
|
||||
|
||||
2. Connect the ClearML SDK to the server by [creating credentials](https://app.clear.ml/settings/workspace-configuration) (go right top to Settings -> Workspace -> Create new credentials), then execute the command below and follow the instructions:
|
||||
|
||||
```bash
|
||||
clearml-init
|
||||
```
|
||||
|
||||
That's it! You're done 😎
|
||||
|
||||
## 🚀 Training YOLOv5 With ClearML
|
||||
|
||||
To enable ClearML experiment tracking, simply install the ClearML pip package.
|
||||
|
||||
```bash
|
||||
pip install clearml>=1.2.0
|
||||
```
|
||||
|
||||
This will enable integration with the YOLOv5 training script. Every training run from now on, will be captured and stored by the ClearML experiment manager.
|
||||
|
||||
If you want to change the `project_name` or `task_name`, use the `--project` and `--name` arguments of the `train.py` script, by default the project will be called `YOLOv5` and the task `Training`. PLEASE NOTE: ClearML uses `/` as a delimiter for subprojects, so be careful when using `/` in your project name!
|
||||
|
||||
```bash
|
||||
python train.py --img 640 --batch 16 --epochs 3 --data coco128.yaml --weights yolov5s.pt --cache
|
||||
```
|
||||
|
||||
or with custom project and task name:
|
||||
|
||||
```bash
|
||||
python train.py --project my_project --name my_training --img 640 --batch 16 --epochs 3 --data coco128.yaml --weights yolov5s.pt --cache
|
||||
```
|
||||
|
||||
This will capture:
|
||||
|
||||
- Source code + uncommitted changes
|
||||
- Installed packages
|
||||
- (Hyper)parameters
|
||||
- Model files (use `--save-period n` to save a checkpoint every n epochs)
|
||||
- Console output
|
||||
- Scalars (mAP_0.5, mAP_0.5:0.95, precision, recall, losses, learning rates, ...)
|
||||
- General info such as machine details, runtime, creation date etc.
|
||||
- All produced plots such as label correlogram and confusion matrix
|
||||
- Images with bounding boxes per epoch
|
||||
- Mosaic per epoch
|
||||
- Validation images per epoch
|
||||
- ...
|
||||
|
||||
That's a lot right? 🤯 Now, we can visualize all of this information in the ClearML UI to get an overview of our training progress. Add custom columns to the table view (such as e.g. mAP_0.5) so you can easily sort on the best performing model. Or select multiple experiments and directly compare them!
|
||||
|
||||
There even more we can do with all of this information, like hyperparameter optimization and remote execution, so keep reading if you want to see how that works!
|
||||
|
||||
## 🔗 Dataset Version Management
|
||||
|
||||
Versioning your data separately from your code is generally a good idea and makes it easy to acquire the latest version too. This repository supports supplying a dataset version ID, and it will make sure to get the data if it's not there yet. Next to that, this workflow also saves the used dataset ID as part of the task parameters, so you will always know for sure which data was used in which experiment!
|
||||
|
||||

|
||||
|
||||
### Prepare Your Dataset
|
||||
|
||||
The YOLOv5 repository supports a number of different datasets by using yaml files containing their information. By default datasets are downloaded to the `../datasets` folder in relation to the repository root folder. So if you downloaded the `coco128` dataset using the link in the yaml or with the scripts provided by yolov5, you get this folder structure:
|
||||
|
||||
```
|
||||
..
|
||||
|_ yolov5
|
||||
|_ datasets
|
||||
|_ coco128
|
||||
|_ images
|
||||
|_ labels
|
||||
|_ LICENSE
|
||||
|_ README.txt
|
||||
```
|
||||
|
||||
But this can be any dataset you wish. Feel free to use your own, as long as you keep to this folder structure.
|
||||
|
||||
Next, ⚠️**copy the corresponding yaml file to the root of the dataset folder**⚠️. This yaml files contains the information ClearML will need to properly use the dataset. You can make this yourself too, of course, just follow the structure of the example yamls.
|
||||
|
||||
Basically we need the following keys: `path`, `train`, `test`, `val`, `nc`, `names`.
|
||||
|
||||
```
|
||||
..
|
||||
|_ yolov5
|
||||
|_ datasets
|
||||
|_ coco128
|
||||
|_ images
|
||||
|_ labels
|
||||
|_ coco128.yaml # <---- HERE!
|
||||
|_ LICENSE
|
||||
|_ README.txt
|
||||
```
|
||||
|
||||
### Upload Your Dataset
|
||||
|
||||
To get this dataset into ClearML as a versioned dataset, go to the dataset root folder and run the following command:
|
||||
|
||||
```bash
|
||||
cd coco128
|
||||
clearml-data sync --project YOLOv5 --name coco128 --folder .
|
||||
```
|
||||
|
||||
The command `clearml-data sync` is actually a shorthand command. You could also run these commands one after the other:
|
||||
|
||||
```bash
|
||||
# Optionally add --parent <parent_dataset_id> if you want to base
|
||||
# this version on another dataset version, so no duplicate files are uploaded!
|
||||
clearml-data create --name coco128 --project YOLOv5
|
||||
clearml-data add --files .
|
||||
clearml-data close
|
||||
```
|
||||
|
||||
### Run Training Using A ClearML Dataset
|
||||
|
||||
Now that you have a ClearML dataset, you can very simply use it to train custom YOLOv5 🚀 models!
|
||||
|
||||
```bash
|
||||
python train.py --img 640 --batch 16 --epochs 3 --data clearml://<your_dataset_id> --weights yolov5s.pt --cache
|
||||
```
|
||||
|
||||
## 👀 Hyperparameter Optimization
|
||||
|
||||
Now that we have our experiments and data versioned, it's time to take a look at what we can build on top!
|
||||
|
||||
Using the code information, installed packages and environment details, the experiment itself is now **completely reproducible**. In fact, ClearML allows you to clone an experiment and even change its parameters. We can then just rerun it with these new parameters automatically, this is basically what HPO does!
|
||||
|
||||
To **run hyperparameter optimization locally**, we've included a pre-made script for you. Just make sure a training task has been run at least once, so it is in the ClearML experiment manager, we will essentially clone it and change its hyperparameters.
|
||||
|
||||
You'll need to fill in the ID of this `template task` in the script found at `utils/loggers/clearml/hpo.py` and then just run it :) You can change `task.execute_locally()` to `task.execute()` to put it in a ClearML queue and have a remote agent work on it instead.
|
||||
|
||||
```bash
|
||||
# To use optuna, install it first, otherwise you can change the optimizer to just be RandomSearch
|
||||
pip install optuna
|
||||
python utils/loggers/clearml/hpo.py
|
||||
```
|
||||
|
||||

|
||||
|
||||
## 🤯 Remote Execution (advanced)
|
||||
|
||||
Running HPO locally is really handy, but what if we want to run our experiments on a remote machine instead? Maybe you have access to a very powerful GPU machine on-site, or you have some budget to use cloud GPUs. This is where the ClearML Agent comes into play. Check out what the agent can do here:
|
||||
|
||||
- [YouTube video](https://www.youtube.com/watch?v=MX3BrXnaULs&feature=youtu.be)
|
||||
- [Documentation](https://clear.ml/docs/latest/docs/clearml_agent)
|
||||
|
||||
In short: every experiment tracked by the experiment manager contains enough information to reproduce it on a different machine (installed packages, uncommitted changes etc.). So a ClearML agent does just that: it listens to a queue for incoming tasks and when it finds one, it recreates the environment and runs it while still reporting scalars, plots etc. to the experiment manager.
|
||||
|
||||
You can turn any machine (a cloud VM, a local GPU machine, your own laptop ... ) into a ClearML agent by simply running:
|
||||
|
||||
```bash
|
||||
clearml-agent daemon --queue <queues_to_listen_to> [--docker]
|
||||
```
|
||||
|
||||
### Cloning, Editing And Enqueuing
|
||||
|
||||
With our agent running, we can give it some work. Remember from the HPO section that we can clone a task and edit the hyperparameters? We can do that from the interface too!
|
||||
|
||||
🪄 Clone the experiment by right-clicking it
|
||||
|
||||
🎯 Edit the hyperparameters to what you wish them to be
|
||||
|
||||
⏳ Enqueue the task to any of the queues by right-clicking it
|
||||
|
||||

|
||||
|
||||
### Executing A Task Remotely
|
||||
|
||||
Now you can clone a task like we explained above, or simply mark your current script by adding `task.execute_remotely()` and on execution it will be put into a queue, for the agent to start working on!
|
||||
|
||||
To run the YOLOv5 training script remotely, all you have to do is add this line to the training.py script after the clearml logger has been instantiated:
|
||||
|
||||
```python
|
||||
# ...
|
||||
# Loggers
|
||||
data_dict = None
|
||||
if RANK in {-1, 0}:
|
||||
loggers = Loggers(save_dir, weights, opt, hyp, LOGGER) # loggers instance
|
||||
if loggers.clearml:
|
||||
loggers.clearml.task.execute_remotely(queue="my_queue") # <------ ADD THIS LINE
|
||||
# Data_dict is either None is user did not choose for ClearML dataset or is filled in by ClearML
|
||||
data_dict = loggers.clearml.data_dict
|
||||
# ...
|
||||
```
|
||||
|
||||
When running the training script after this change, python will run the script up until that line, after which it will package the code and send it to the queue instead!
|
||||
|
||||
### Autoscaling workers
|
||||
|
||||
ClearML comes with autoscalers too! This tool will automatically spin up new remote machines in the cloud of your choice (AWS, GCP, Azure) and turn them into ClearML agents for you whenever there are experiments detected in the queue. Once the tasks are processed, the autoscaler will automatically shut down the remote machines, and you stop paying!
|
||||
|
||||
Check out the autoscalers getting started video below.
|
||||
|
||||
[](https://youtu.be/j4XVMAaUt3E)
|
1
yolov5/utils/loggers/clearml/__init__.py
Normal file
1
yolov5/utils/loggers/clearml/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
228
yolov5/utils/loggers/clearml/clearml_utils.py
Normal file
228
yolov5/utils/loggers/clearml/clearml_utils.py
Normal file
@ -0,0 +1,228 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
"""Main Logger class for ClearML experiment tracking."""
|
||||
|
||||
import glob
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import matplotlib.image as mpimg
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import yaml
|
||||
from ultralytics.utils.plotting import Annotator, colors
|
||||
|
||||
try:
|
||||
import clearml
|
||||
from clearml import Dataset, Task
|
||||
|
||||
assert hasattr(clearml, "__version__") # verify package import not local dir
|
||||
except (ImportError, AssertionError):
|
||||
clearml = None
|
||||
|
||||
|
||||
def construct_dataset(clearml_info_string):
|
||||
"""Load in a clearml dataset and fill the internal data_dict with its contents."""
|
||||
dataset_id = clearml_info_string.replace("clearml://", "")
|
||||
dataset = Dataset.get(dataset_id=dataset_id)
|
||||
dataset_root_path = Path(dataset.get_local_copy())
|
||||
|
||||
# We'll search for the yaml file definition in the dataset
|
||||
yaml_filenames = list(glob.glob(str(dataset_root_path / "*.yaml")) + glob.glob(str(dataset_root_path / "*.yml")))
|
||||
if len(yaml_filenames) > 1:
|
||||
raise ValueError(
|
||||
"More than one yaml file was found in the dataset root, cannot determine which one contains "
|
||||
"the dataset definition this way."
|
||||
)
|
||||
elif not yaml_filenames:
|
||||
raise ValueError(
|
||||
"No yaml definition found in dataset root path, check that there is a correct yaml file "
|
||||
"inside the dataset root path."
|
||||
)
|
||||
with open(yaml_filenames[0]) as f:
|
||||
dataset_definition = yaml.safe_load(f)
|
||||
|
||||
assert set(dataset_definition.keys()).issuperset({"train", "test", "val", "nc", "names"}), (
|
||||
"The right keys were not found in the yaml file, make sure it at least has the following keys: ('train', 'test', 'val', 'nc', 'names')"
|
||||
)
|
||||
|
||||
data_dict = {
|
||||
"train": (
|
||||
str((dataset_root_path / dataset_definition["train"]).resolve()) if dataset_definition["train"] else None
|
||||
)
|
||||
}
|
||||
data_dict["test"] = (
|
||||
str((dataset_root_path / dataset_definition["test"]).resolve()) if dataset_definition["test"] else None
|
||||
)
|
||||
data_dict["val"] = (
|
||||
str((dataset_root_path / dataset_definition["val"]).resolve()) if dataset_definition["val"] else None
|
||||
)
|
||||
data_dict["nc"] = dataset_definition["nc"]
|
||||
data_dict["names"] = dataset_definition["names"]
|
||||
|
||||
return data_dict
|
||||
|
||||
|
||||
class ClearmlLogger:
|
||||
"""
|
||||
Log training runs, datasets, models, and predictions to ClearML.
|
||||
|
||||
This logger sends information to ClearML at app.clear.ml or to your own hosted server. By default, this information
|
||||
includes hyperparameters, system configuration and metrics, model metrics, code information and basic data metrics
|
||||
and analyses.
|
||||
|
||||
By providing additional command line arguments to train.py, datasets, models and predictions can also be logged.
|
||||
"""
|
||||
|
||||
def __init__(self, opt, hyp):
|
||||
"""
|
||||
- Initialize ClearML Task, this object will capture the experiment
|
||||
- Upload dataset version to ClearML Data if opt.upload_dataset is True.
|
||||
|
||||
Arguments:
|
||||
opt (namespace) -- Commandline arguments for this run
|
||||
hyp (dict) -- Hyperparameters for this run
|
||||
|
||||
"""
|
||||
self.current_epoch = 0
|
||||
# Keep tracked of amount of logged images to enforce a limit
|
||||
self.current_epoch_logged_images = set()
|
||||
# Maximum number of images to log to clearML per epoch
|
||||
self.max_imgs_to_log_per_epoch = 16
|
||||
# Get the interval of epochs when bounding box images should be logged
|
||||
# Only for detection task though!
|
||||
if "bbox_interval" in opt:
|
||||
self.bbox_interval = opt.bbox_interval
|
||||
self.clearml = clearml
|
||||
self.task = None
|
||||
self.data_dict = None
|
||||
if self.clearml:
|
||||
self.task = Task.init(
|
||||
project_name="YOLOv5" if str(opt.project).startswith("runs/") else opt.project,
|
||||
task_name=opt.name if opt.name != "exp" else "Training",
|
||||
tags=["YOLOv5"],
|
||||
output_uri=True,
|
||||
reuse_last_task_id=opt.exist_ok,
|
||||
auto_connect_frameworks={"pytorch": False, "matplotlib": False},
|
||||
# We disconnect pytorch auto-detection, because we added manual model save points in the code
|
||||
)
|
||||
# ClearML's hooks will already grab all general parameters
|
||||
# Only the hyperparameters coming from the yaml config file
|
||||
# will have to be added manually!
|
||||
self.task.connect(hyp, name="Hyperparameters")
|
||||
self.task.connect(opt, name="Args")
|
||||
|
||||
# Make sure the code is easily remotely runnable by setting the docker image to use by the remote agent
|
||||
self.task.set_base_docker(
|
||||
"ultralytics/yolov5:latest",
|
||||
docker_arguments='--ipc=host -e="CLEARML_AGENT_SKIP_PYTHON_ENV_INSTALL=1"',
|
||||
docker_setup_bash_script="pip install clearml",
|
||||
)
|
||||
|
||||
# Get ClearML Dataset Version if requested
|
||||
if opt.data.startswith("clearml://"):
|
||||
# data_dict should have the following keys:
|
||||
# names, nc (number of classes), test, train, val (all three relative paths to ../datasets)
|
||||
self.data_dict = construct_dataset(opt.data)
|
||||
# Set data to data_dict because wandb will crash without this information and opt is the best way
|
||||
# to give it to them
|
||||
opt.data = self.data_dict
|
||||
|
||||
def log_scalars(self, metrics, epoch):
|
||||
"""
|
||||
Log scalars/metrics to ClearML.
|
||||
|
||||
Arguments:
|
||||
metrics (dict) Metrics in dict format: {"metrics/mAP": 0.8, ...}
|
||||
epoch (int) iteration number for the current set of metrics
|
||||
"""
|
||||
for k, v in metrics.items():
|
||||
title, series = k.split("/")
|
||||
self.task.get_logger().report_scalar(title, series, v, epoch)
|
||||
|
||||
def log_model(self, model_path, model_name, epoch=0):
|
||||
"""
|
||||
Log model weights to ClearML.
|
||||
|
||||
Arguments:
|
||||
model_path (PosixPath or str) Path to the model weights
|
||||
model_name (str) Name of the model visible in ClearML
|
||||
epoch (int) Iteration / epoch of the model weights
|
||||
"""
|
||||
self.task.update_output_model(
|
||||
model_path=str(model_path), name=model_name, iteration=epoch, auto_delete_file=False
|
||||
)
|
||||
|
||||
def log_summary(self, metrics):
|
||||
"""
|
||||
Log final metrics to a summary table.
|
||||
|
||||
Arguments:
|
||||
metrics (dict) Metrics in dict format: {"metrics/mAP": 0.8, ...}
|
||||
"""
|
||||
for k, v in metrics.items():
|
||||
self.task.get_logger().report_single_value(k, v)
|
||||
|
||||
def log_plot(self, title, plot_path):
|
||||
"""
|
||||
Log image as plot in the plot section of ClearML.
|
||||
|
||||
Arguments:
|
||||
title (str) Title of the plot
|
||||
plot_path (PosixPath or str) Path to the saved image file
|
||||
"""
|
||||
img = mpimg.imread(plot_path)
|
||||
fig = plt.figure()
|
||||
ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect="auto", xticks=[], yticks=[]) # no ticks
|
||||
ax.imshow(img)
|
||||
|
||||
self.task.get_logger().report_matplotlib_figure(title, "", figure=fig, report_interactive=False)
|
||||
|
||||
def log_debug_samples(self, files, title="Debug Samples"):
|
||||
"""
|
||||
Log files (images) as debug samples in the ClearML task.
|
||||
|
||||
Arguments:
|
||||
files (List(PosixPath)) a list of file paths in PosixPath format
|
||||
title (str) A title that groups together images with the same values
|
||||
"""
|
||||
for f in files:
|
||||
if f.exists():
|
||||
it = re.search(r"_batch(\d+)", f.name)
|
||||
iteration = int(it.groups()[0]) if it else 0
|
||||
self.task.get_logger().report_image(
|
||||
title=title, series=f.name.replace(f"_batch{iteration}", ""), local_path=str(f), iteration=iteration
|
||||
)
|
||||
|
||||
def log_image_with_boxes(self, image_path, boxes, class_names, image, conf_threshold=0.25):
|
||||
"""
|
||||
Draw the bounding boxes on a single image and report the result as a ClearML debug sample.
|
||||
|
||||
Arguments:
|
||||
image_path (PosixPath) the path the original image file
|
||||
boxes (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class]
|
||||
class_names (dict): dict containing mapping of class int to class name
|
||||
image (Tensor): A torch tensor containing the actual image data
|
||||
"""
|
||||
if (
|
||||
len(self.current_epoch_logged_images) < self.max_imgs_to_log_per_epoch
|
||||
and self.current_epoch >= 0
|
||||
and (self.current_epoch % self.bbox_interval == 0 and image_path not in self.current_epoch_logged_images)
|
||||
):
|
||||
im = np.ascontiguousarray(np.moveaxis(image.mul(255).clamp(0, 255).byte().cpu().numpy(), 0, 2))
|
||||
annotator = Annotator(im=im, pil=True)
|
||||
for i, (conf, class_nr, box) in enumerate(zip(boxes[:, 4], boxes[:, 5], boxes[:, :4])):
|
||||
color = colors(i)
|
||||
|
||||
class_name = class_names[int(class_nr)]
|
||||
confidence_percentage = round(float(conf) * 100, 2)
|
||||
label = f"{class_name}: {confidence_percentage}%"
|
||||
|
||||
if conf > conf_threshold:
|
||||
annotator.rectangle(box.cpu().numpy(), outline=color)
|
||||
annotator.box_label(box.cpu().numpy(), label=label, color=color)
|
||||
|
||||
annotated_image = annotator.result()
|
||||
self.task.get_logger().report_image(
|
||||
title="Bounding Boxes", series=image_path.name, iteration=self.current_epoch, image=annotated_image
|
||||
)
|
||||
self.current_epoch_logged_images.add(image_path)
|
90
yolov5/utils/loggers/clearml/hpo.py
Normal file
90
yolov5/utils/loggers/clearml/hpo.py
Normal file
@ -0,0 +1,90 @@
|
||||
# Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
|
||||
|
||||
from clearml import Task
|
||||
|
||||
# Connecting ClearML with the current process,
|
||||
# from here on everything is logged automatically
|
||||
from clearml.automation import HyperParameterOptimizer, UniformParameterRange
|
||||
from clearml.automation.optuna import OptimizerOptuna
|
||||
|
||||
task = Task.init(
|
||||
project_name="Hyper-Parameter Optimization",
|
||||
task_name="YOLOv5",
|
||||
task_type=Task.TaskTypes.optimizer,
|
||||
reuse_last_task_id=False,
|
||||
)
|
||||
|
||||
# Example use case:
|
||||
optimizer = HyperParameterOptimizer(
|
||||
# This is the experiment we want to optimize
|
||||
base_task_id="<your_template_task_id>",
|
||||
# here we define the hyper-parameters to optimize
|
||||
# Notice: The parameter name should exactly match what you see in the UI: <section_name>/<parameter>
|
||||
# For Example, here we see in the base experiment a section Named: "General"
|
||||
# under it a parameter named "batch_size", this becomes "General/batch_size"
|
||||
# If you have `argparse` for example, then arguments will appear under the "Args" section,
|
||||
# and you should instead pass "Args/batch_size"
|
||||
hyper_parameters=[
|
||||
UniformParameterRange("Hyperparameters/lr0", min_value=1e-5, max_value=1e-1),
|
||||
UniformParameterRange("Hyperparameters/lrf", min_value=0.01, max_value=1.0),
|
||||
UniformParameterRange("Hyperparameters/momentum", min_value=0.6, max_value=0.98),
|
||||
UniformParameterRange("Hyperparameters/weight_decay", min_value=0.0, max_value=0.001),
|
||||
UniformParameterRange("Hyperparameters/warmup_epochs", min_value=0.0, max_value=5.0),
|
||||
UniformParameterRange("Hyperparameters/warmup_momentum", min_value=0.0, max_value=0.95),
|
||||
UniformParameterRange("Hyperparameters/warmup_bias_lr", min_value=0.0, max_value=0.2),
|
||||
UniformParameterRange("Hyperparameters/box", min_value=0.02, max_value=0.2),
|
||||
UniformParameterRange("Hyperparameters/cls", min_value=0.2, max_value=4.0),
|
||||
UniformParameterRange("Hyperparameters/cls_pw", min_value=0.5, max_value=2.0),
|
||||
UniformParameterRange("Hyperparameters/obj", min_value=0.2, max_value=4.0),
|
||||
UniformParameterRange("Hyperparameters/obj_pw", min_value=0.5, max_value=2.0),
|
||||
UniformParameterRange("Hyperparameters/iou_t", min_value=0.1, max_value=0.7),
|
||||
UniformParameterRange("Hyperparameters/anchor_t", min_value=2.0, max_value=8.0),
|
||||
UniformParameterRange("Hyperparameters/fl_gamma", min_value=0.0, max_value=4.0),
|
||||
UniformParameterRange("Hyperparameters/hsv_h", min_value=0.0, max_value=0.1),
|
||||
UniformParameterRange("Hyperparameters/hsv_s", min_value=0.0, max_value=0.9),
|
||||
UniformParameterRange("Hyperparameters/hsv_v", min_value=0.0, max_value=0.9),
|
||||
UniformParameterRange("Hyperparameters/degrees", min_value=0.0, max_value=45.0),
|
||||
UniformParameterRange("Hyperparameters/translate", min_value=0.0, max_value=0.9),
|
||||
UniformParameterRange("Hyperparameters/scale", min_value=0.0, max_value=0.9),
|
||||
UniformParameterRange("Hyperparameters/shear", min_value=0.0, max_value=10.0),
|
||||
UniformParameterRange("Hyperparameters/perspective", min_value=0.0, max_value=0.001),
|
||||
UniformParameterRange("Hyperparameters/flipud", min_value=0.0, max_value=1.0),
|
||||
UniformParameterRange("Hyperparameters/fliplr", min_value=0.0, max_value=1.0),
|
||||
UniformParameterRange("Hyperparameters/mosaic", min_value=0.0, max_value=1.0),
|
||||
UniformParameterRange("Hyperparameters/mixup", min_value=0.0, max_value=1.0),
|
||||
UniformParameterRange("Hyperparameters/copy_paste", min_value=0.0, max_value=1.0),
|
||||
],
|
||||
# this is the objective metric we want to maximize/minimize
|
||||
objective_metric_title="metrics",
|
||||
objective_metric_series="mAP_0.5",
|
||||
# now we decide if we want to maximize it or minimize it (accuracy we maximize)
|
||||
objective_metric_sign="max",
|
||||
# let us limit the number of concurrent experiments,
|
||||
# this in turn will make sure we don't bombard the scheduler with experiments.
|
||||
# if we have an auto-scaler connected, this, by proxy, will limit the number of machine
|
||||
max_number_of_concurrent_tasks=1,
|
||||
# this is the optimizer class (actually doing the optimization)
|
||||
# Currently, we can choose from GridSearch, RandomSearch or OptimizerBOHB (Bayesian optimization Hyper-Band)
|
||||
optimizer_class=OptimizerOptuna,
|
||||
# If specified only the top K performing Tasks will be kept, the others will be automatically archived
|
||||
save_top_k_tasks_only=5, # 5,
|
||||
compute_time_limit=None,
|
||||
total_max_jobs=20,
|
||||
min_iteration_per_job=None,
|
||||
max_iteration_per_job=None,
|
||||
)
|
||||
|
||||
# report every 10 seconds, this is way too often, but we are testing here
|
||||
optimizer.set_report_period(10 / 60)
|
||||
# You can also use the line below instead to run all the optimizer tasks locally, without using queues or agent
|
||||
# an_optimizer.start_locally(job_complete_callback=job_complete_callback)
|
||||
# set the time limit for the optimization process (2 hours)
|
||||
optimizer.set_time_limit(in_minutes=120.0)
|
||||
# Start the optimization process in the local environment
|
||||
optimizer.start_locally()
|
||||
# wait until process is done (notice we are controlling the optimization process in the background)
|
||||
optimizer.wait()
|
||||
# make sure background optimization stopped
|
||||
optimizer.stop()
|
||||
|
||||
print("We are done, good bye")
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user