7 단계 : 데이터 분할 8 : 모델 훈련 9 단계 : 모델 평가 10 단계 : 모델 배포 11 :
import requests import pandas as pd from dotenv import load_dotenv import os # Load the .env file load_dotenv() def fetch_crypto_data(api_uri): response = requests.get( api_uri, params={ "market": "cadli", "instrument": "BTC-USD", "limit": 5000, "aggregate": 1, "fill": "true", "apply_mapping": "true", "response_format": "JSON" }, headers={"Content-type": "application/json; charset=UTF-8"} ) if response.status_code == 200: print('API Connection Successful! \nFetching the data...') data = response.json() data_list = data.get('Data', []) df = pd.DataFrame(data_list) df['DATE'] = pd.to_datetime(df['TIMESTAMP'], unit='s') return df # Return the DataFrame else: raise Exception(f"API Error: {response.status_code} - {response.text}")이 코드는 MongoDB에 연결하고 API를 통해 비트 코인 가격 데이터를 검색하며 최신 기록 된 날짜 이후에 모든 새 항목으로 데이터베이스를 업데이트합니다.
. 사전 반품 및 기본 Zenml 명령
가상 환경을 활성화하십시오 :
Zenml 명령 :
import requests import pandas as pd from dotenv import load_dotenv import os # Load the .env file load_dotenv() def fetch_crypto_data(api_uri): response = requests.get( api_uri, params={ "market": "cadli", "instrument": "BTC-USD", "limit": 5000, "aggregate": 1, "fill": "true", "apply_mapping": "true", "response_format": "JSON" }, headers={"Content-type": "application/json; charset=UTF-8"} ) if response.status_code == 200: print('API Connection Successful! \nFetching the data...') data = response.json() data_list = data.get('Data', []) df = pd.DataFrame(data_list) df['DATE'] = pd.to_datetime(df['TIMESTAMP'], unit='s') return df # Return the DataFrame else: raise Exception(f"API Error: {response.status_code} - {response.text}")
#Install zenml pip install zenml #To Launch zenml server and dashboard locally pip install "zenml[server]" #To check the zenml Version: zenml version #To initiate a new repository zenml init #To run the dashboard locally: zenml login --local #To know the status of our zenml Pipelines zenml show #To shutdown the zenml server zenml clean
#Integrating mlflow with ZenML zenml integration install mlflow -y #Register the experiment tracker zenml experiment-tracker register mlflow_tracker --flavor=mlflow #Registering the model deployer zenml model-deployer register mlflow --flavor=mlflow #Registering the stack zenml stack register local-mlflow-stack-new -a default -o default -d mlflow -e mlflow_tracker --set #To view the stack list zenml stack --list
mlflow 모델 배포자 를 사용하여 continuous_deployment_pipeline () 를 사용하여 훈련 된 모델을 배포합니다.
기존_Services = mlflow_model_deployer_component.find_model_server () > 파이프 라인 이름 및 파이프 라인 단계 이름과 같은 주어진 매개 변수를 기반으로 사용 가능한 배포 서비스를 검색합니다. 서비스를 사용할 수없는 경우 배포 파이프 라인이 수행되지 않았거나 배포 파이프 라인과 관련된 문제가 발생 했으므로 런타임 에러를 던집니다. .
결론
이 기사에서는 엔드 투 엔드, 프로덕션 준비 비트 코인 가격 예측 MLOPS 프로젝트를 성공적으로 구축했습니다. API를 통해 데이터를 획득하고이를 전처리하는 것부터 모델 교육, 평가 및 배포에 이르기까지 우리의 프로젝트는 개발을 생산과 연결하는 데 MLOPS의 중요한 역할을 강조합니다. 우리는 비트 코인 가격을 실시간으로 예측하는 미래를 형성하는 데 한 걸음 더 가까워졌습니다. API는 CCDATA API의 비트 코인 가격 데이터와 같은 외부 데이터에 대한 원활한 액세스를 제공하여 기존 데이터 세트가 필요하지 않습니다.
q1. Zenml은 무료로 사용할 수 있습니까?
import requests
import pandas as pd
from dotenv import load_dotenv
import os
# Load the .env file
load_dotenv()
def fetch_crypto_data(api_uri):
response = requests.get(
api_uri,
params={
"market": "cadli",
"instrument": "BTC-USD",
"limit": 5000,
"aggregate": 1,
"fill": "true",
"apply_mapping": "true",
"response_format": "JSON"
},
headers={"Content-type": "application/json; charset=UTF-8"}
)
if response.status_code == 200:
print('API Connection Successful! \nFetching the data...')
data = response.json()
data_list = data.get('Data', [])
df = pd.DataFrame(data_list)
df['DATE'] = pd.to_datetime(df['TIMESTAMP'], unit='s')
return df # Return the DataFrame
else:
raise Exception(f"API Error: {response.status_code} - {response.text}")
prediction_service_loader () import os
from pymongo import MongoClient
from dotenv import load_dotenv
from data.management.api import fetch_crypto_data # Import the API function
import pandas as pd
load_dotenv()
MONGO_URI = os.getenv("MONGO_URI")
API_URI = os.getenv("API_URI")
client = MongoClient(MONGO_URI, ssl=True, ssl_certfile=None, ssl_ca_certs=None)
db = client['crypto_data']
collection = db['historical_data']
try:
latest_entry = collection.find_one(sort=[("DATE", -1)]) # Find the latest date
if latest_entry:
last_date = pd.to_datetime(latest_entry['DATE']).strftime('%Y-%m-%d')
else:
last_date = '2011-03-27' # Default start date if MongoDB is empty
print(f"Fetching data starting from {last_date}...")
new_data_df = fetch_crypto_data(API_URI)
if latest_entry:
new_data_df = new_data_df[new_data_df['DATE'] > last_date]
if not new_data_df.empty:
data_to_insert = new_data_df.to_dict(orient='records')
result = collection.insert_many(data_to_insert)
print(f"Inserted {len(result.inserted_ids)} new records into MongoDB.")
else:
print("No new data to insert.")
except Exception as e:
print(f"An error occurred: {e}")
a. 예, Zenml은 로컬 개발에서 생산 파이프 라인으로의 전환을 1 줄의 코드만큼 쉽게 만드는 완벽한 오픈 소스 MLOPS 프레임 워크입니다. mlflow는 무엇에 사용됩니까? MLFLOW는 실험을 추적하고 버전 모델링 및 배포 할 수있는 도구를 제공함으로써 머신 러닝 개발을보다 쉽게 할 수 있습니다. 서버 데몬을 디버깅하는 방법 오류가 실행되지 않습니까?
위 내용은 MLOPS를 사용한 비트 코인 가격 예측의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!