이 기사는 데이터 과학 블로그 톤의
의 일부로 출판되었습니다.
: 나를 따르지 않고 자신의 분석을 수행하십시오.
ingest_data.py 에 대한 코드 샘플
와우! Mlops의 가장 중요한 부분 중 하나를 만들고 배우는 것을 축하합니다. 처음 이후로 약간 압도해도 괜찮습니다. 첫 번째 생산 등급 ML 모델을 실행할 때 모든 것이 합리적이므로 너무 많은 스트레스를받지 마십시오.
다음 단계는 모델을 최종 사용자에게 투사 할 플라스크 앱을 만드는 것입니다. 이를 위해 템플릿 폴더 내에 app.py 및 index.html을 만들어야합니다. 아래 코드를 따라 app.py를 만듭니다 :
.
<.com> render.com으로 이동하여 프로젝트의 Github 저장소를 렌더링하도록 연결하십시오.
<.> 그게 다야. 첫 번째 MLOPS 프로젝트를 성공적으로 만들었습니다. 당신이 그것을 즐겼기를 바랍니다!
# Make sure you have Python 3.10 or above installed
python --version
# Make a new Python environment using any method
python3.10 -m venv myenv
# Activate the environment
source myenv/bin/activate
# Install the requirements from the provided source above
pip install -r requirements.txt
# Install the Zenml server
pip install zenml[server] == 0.66.0
# Initialize the Zenml server
zenml init
# Launch the Zenml dashboard
zenml up
import logging
import pandas as pd
from abc import ABC, abstractmethod
# Setup logging configuration
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
# Abstract Base Class for Data Ingestion Strategy
# ------------------------------------------------
# This class defines a common interface for different data ingestion strategies.
# Subclasses must implement the `ingest` method.
class DataIngestionStrategy(ABC):
@abstractmethod
def ingest(self, file_path: str) -> pd.DataFrame:
"""
Abstract method to ingest data from a file into a DataFrame.
Parameters:
file_path (str): The path to the data file to ingest.
Returns:
pd.DataFrame: A dataframe containing the ingested data.
"""
pass
# Concrete Strategy for XLSX File Ingestion
# -----------------------------------------
# This strategy handles the ingestion of data from an XLSX file.
class XLSXIngestion(DataIngestionStrategy):
def __init__(self, sheet_name=0):
"""
Initializes the XLSXIngestion with optional sheet name.
Parameters:
sheet_name (str or int): The sheet name or index to read, default is the first sheet.
"""
self.sheet_name = sheet_name
def ingest(self, file_path: str) -> pd.DataFrame:
"""
Ingests data from an XLSX file into a DataFrame.
Parameters:
file_path (str): The path to the XLSX file.
Returns:
pd.DataFrame: A dataframe containing the ingested data.
"""
try:
logging.info(f"Attempting to read XLSX file: {file_path}")
df = pd.read_excel(file_path,dtype={'InvoiceNo': str, 'StockCode': str, 'Description':str}, sheet_name=self.sheet_name)
logging.info(f"Successfully read XLSX file: {file_path}")
return df
except FileNotFoundError:
logging.error(f"File not found: {file_path}")
except pd.errors.EmptyDataError:
logging.error(f"File is empty: {file_path}")
except Exception as e:
logging.error(f"An error occurred while reading the XLSX file: {e}")
return pd.DataFrame()
# Context Class for Data Ingestion
# --------------------------------
# This class uses a DataIngestionStrategy to ingest data from a file.
class DataIngestor:
def __init__(self, strategy: DataIngestionStrategy):
"""
Initializes the DataIngestor with a specific data ingestion strategy.
Parameters:
strategy (DataIngestionStrategy): The strategy to be used for data ingestion.
"""
self._strategy = strategy
def set_strategy(self, strategy: DataIngestionStrategy):
"""
Sets a new strategy for the DataIngestor.
Parameters:
strategy (DataIngestionStrategy): The new strategy to be used for data ingestion.
"""
logging.info("Switching data ingestion strategy.")
self._strategy = strategy
def ingest_data(self, file_path: str) -> pd.DataFrame:
"""
Executes the data ingestion using the current strategy.
Parameters:
file_path (str): The path to the data file to ingest.
Returns:
pd.DataFrame: A dataframe containing the ingested data.
"""
logging.info("Ingesting data using the current strategy.")
return self._strategy.ingest(file_path)
# Example usage
if __name__ == "__main__":
# Example file path for XLSX file
# file_path = "../data/raw/your_data_file.xlsx"
# XLSX Ingestion Example
# xlsx_ingestor = DataIngestor(XLSXIngestion(sheet_name=0))
# df = xlsx_ingestor.ingest_data(file_path)
# Show the first few rows of the ingested DataFrame if successful
# if not df.empty:
# logging.info("Displaying the first few rows of the ingested data:")
# print(df.head())
pass csv
MLOPS는 ML 라이프 사이클을 단순화하여 자동화 된 파이프 라인을 통한 오류를 줄이고 효율성을 높입니다.
위 내용은 Zenml 프로젝트를 사용하여 mlops 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!