Написание собственного предиктора
Подключите собственный код предварительной обработки и модели
«Написание собственного предиктора» — бесплатный урок MLOps Academy на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения MLOps Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс MLOps Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
When Built-ins Fall Short
The built-in runtimes cover sklearn, PyTorch, and friends. But when your model needs special logic, you write your own. A custom predictor gives you full control. 🛠️
It Is Just a Container
A custom predictor is your own container image that speaks the KServe protocol. You package your code, model, and dependencies into one image and hand it to KServe.
The KServe Python SDK
The kserve Python package gives you a base class to extend. You subclass kserve.Model and fill in how your model loads and predicts.
import kserve
class MyModel(kserve.Model):
def __init__(self, name):
super().__init__(name)
self.ready = FalseImplement load()
The load method reads your model from disk into memory once at startup. When it finishes, you set ready to True so KServe knows it can serve.
def load(self):
self.model = joblib.load("/mnt/models/model.joblib")
self.ready = TrueImplement predict()
The predict method takes the request payload, runs your model, and returns the result as a dict. This is where your real inference logic lives.
def predict(self, payload, headers=None):
rows = payload["instances"]
preds = self.model.predict(rows)
return {"predictions": preds.tolist()}Custom Preprocessing Fits Here
Need to reshape inputs or apply business rules before inference? Put that logic right inside predict or in a preprocess step. The runtime never had to know about it.
Start the Model Server
You wire your class into a ModelServer and start it. KServe's server handles HTTP, health, and the protocol so you only write model code. ModelServer runs the loop.
if __name__ == "__main__":
model = MyModel("custom-model")
model.load()
kserve.ModelServer().start([model])Package It in a Dockerfile
You build a container that installs kserve, copies your code, and runs the server. This Dockerfile produces the image KServe will launch.
FROM python:3.11-slim
RUN pip install kserve joblib scikit-learn
COPY model.py /app/model.py
CMD ["python", "/app/model.py"]Point the Spec at Your Image
In the InferenceService, the predictor uses a plain containers block instead of a model format. You name your image and KServe runs it.
spec:
predictor:
containers:
- name: kserve-container
image: my-registry/custom-model:latestMounting Your Model
You can still set a storageUri, and KServe mounts the downloaded model at a known path your code reads. The container and the storageUri work together.
Same Protocol, Your Logic
Because you implement the standard endpoints, clients call your custom predictor exactly like a built-in one. The protocol stays identical, only the internals are yours.
Quick Check
You subclass kserve.Model for a custom predictor. Which method loads the model into memory?
Recap
You built a custom predictor by subclassing kserve.Model, filling in load and predict, and shipping it as a container. Same protocol, your own logic. Awesome work! 🎉
Часто задаваемые вопросы
Урок «Написание собственного предиктора» бесплатный?
Да — полный текст урока «Написание собственного предиктора» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс MLOps Academy, подпишись на CoddyKit PRO. Курс MLOps Academy содержит 4 уроков всего.
Чему я научусь в уроке «Написание собственного предиктора»?
Подключите собственный код предварительной обработки и модели Ты практикуешь MLOps Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать MLOps Academy?
Предыдущий опыт не требуется. MLOps Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Написание собственного предиктора»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке MLOps Academy?
Да. Каждый урок MLOps Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Ресурс InferenceService
- Масштабирование до нуля и обратно
- Написание собственного предиктора
- Сравнение KServe и Seldon Core