鍵.png)
Python + BaiduTransAPI :快速檢索千篇英文文獻(xiàn)(附源碼)
讓我們創(chuàng)建并初始化開發(fā)環(huán)境。
python3 -m venv env
source env/bin/activate
安裝所需的軟件包:
pip install django djangorestframework sklearn numpy
打開命令行并輸入注釋以創(chuàng)建和復(fù)制存儲 Django 項(xiàng)目的目錄。為此應(yīng)用程序創(chuàng)建一個(gè)目錄并將其復(fù)制(cd)到該目錄中。
mkdir DjangoMLAPI
cd DjangoMLAPI
django-admin startproject api
我們已經(jīng)創(chuàng)建了一個(gè) Django 項(xiàng)目,其中將包含我們正在處理的所有代碼。它還將包含數(shù)據(jù)庫配置和應(yīng)用程序設(shè)置。
“項(xiàng)目”對應(yīng)于我們正在開發(fā)的應(yīng)用程序,而 Django 將項(xiàng)目中的包稱為“應(yīng)用程序”。主要包將是 API。
Start Project API 創(chuàng)建了大量運(yùn)行我們的項(xiàng)目所需的樣板代碼。它將類似于左側(cè)的文件樹。
外部 /api 文件夾只包含我們項(xiàng)目的所有代碼。
我們項(xiàng)目的主要 python 包是內(nèi)部的 /api。
python manage.py runserver
如果您在 Web 瀏覽器中輸入 127.0.0.1:8000,您應(yīng)該會看到默認(rèn)的 Django 歡迎網(wǎng)頁。
之后,我們將在我們的項(xiàng)目中創(chuàng)建一個(gè)“應(yīng)用程序”。這將傳播 API 背后的機(jī)器學(xué)習(xí)。我們將命名這個(gè)聲音預(yù)測器。
cd api
python manage.py startapp soundpredictor
我們添加了一個(gè)名為 /soundpredictor 的文件夾,里面有很多文件。
view.py包含可以在每個(gè)請求上運(yùn)行的代碼。因此,我們在方程中添加了矢量化和回歸邏輯。
apps.py是我們將在其中指定配置類的文件。這段代碼只會執(zhí)行一次,所以我們最終會把代碼放在那里加載我們的模型
讓我們將此應(yīng)用程序添加到 APPS_INSTALLED。打開 /api/api/settings.py 并將“聲音預(yù)測器”添加到 APPS_INSTALLED。
APPS_INSTALLED = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'predictor'
]
在 /soundpredictor 中創(chuàng)建一個(gè)名為 /models 的文件夾很重要。將經(jīng)過訓(xùn)練的模型移動(dòng)到此目錄中。
請注意,在真實(shí)的生產(chǎn)環(huán)境中,這樣我們就不必在每次模型更改時(shí)重新部署應(yīng)用程序。但是,在這種情況下,我們只會在應(yīng)用程序中包含模型。
我們必須將這些行添加到設(shè)置中。此代碼將加載模型。
MODELS = os.path.join(BASE_DIR, 'soundpredictor/models')
編寫在應(yīng)用程序啟動(dòng)時(shí)加載模型的代碼。在 /api/soundpredictor/apps.py 中部署代碼。創(chuàng)建模型路徑并將模型加載到單獨(dú)的變量中。
from django.apps import AppConfig
from django.conf import settings
import os
import pickle
class soundpredictorConfig(AppConfig):
path = os.path.join(settings.MODELS, 'models.p')
with open(path, 'rb') as pickled:
data = pickle.load(pickled)
regressor = data['regressor']
vectorize = data['vectorize']
現(xiàn)在我們需要?jiǎng)?chuàng)建一個(gè)視圖來鼓勵(lì)我們的回歸邏輯。打開 /api/predictor/views.py 并使用此代碼進(jìn)行更新。
from django.shortcuts import render
from .apps import soundpredictorConfig
from django.http import JsonResponse
from rest_framework.views import APIView
class call_model(APIView):
def get(self,request):
if request.method == 'GET':
sound = request.GET.get('sound')
vector = PredictorConfig.vectorizer.transform([sound])
prediction = soundpredictorConfig.regressor.predict(vector)[0]
response = {'dog': prediction}
return JsonResponse(response)
最后一步是將 URL 添加到我們的模型中,以便我們可以訪問它們。請將以下代碼添加到 /api/api/urls.py 中的 urls.py 文件中:
from django.urls import path
from predictor import viewsurlpatterns = [
path('classify/', views.call_model.as_view())
]
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
urlpatterns = [
url(r"^api/v1/", include(router.urls)),
]
要開始該項(xiàng)目,請打開一個(gè) jupyter notebook。運(yùn)行命令,
pip3 install jupyter notebook
ipython kernel install --user --name=venv
創(chuàng)建一個(gè)目錄來存儲筆記本文件,
mkdir research
cd research
jupyter notebook
這種預(yù)測分析是訓(xùn)練模型根據(jù)它的語氣來預(yù)測動(dòng)物是否是鴨子。
因此,我們將使用虛構(gòu)數(shù)據(jù)訓(xùn)練模型。這表明它將以與您可能創(chuàng)建的任何其他 sklearn 模型相同的方式工作。
該算法將根據(jù)動(dòng)物發(fā)出的聲音確定它是否是鴨子。
創(chuàng)建虛構(gòu)數(shù)據(jù)后,每個(gè)內(nèi)部列表中的第一個(gè)索引是動(dòng)物的聲音,第二個(gè)索引是指示動(dòng)物是否是鴨子的布爾標(biāo)簽。
data = [
['Honk', 1],
['Woof', 0],
['ruff', 0],
['bowwow', 0],
['cackle', 1],
['moo', 0],
['meow', 0],
['clang', 1],
['buzz', 0],
['quack', 0],
['pika', 0]
]
下一個(gè)任務(wù)是將上述數(shù)據(jù)轉(zhuǎn)換為特征和標(biāo)簽列表。
X = []
y = []
for i in data:
X.append( i[0] )
y.append( i[1] )
在我們將特征轉(zhuǎn)換為列表后,擬合向量化器,并轉(zhuǎn)換特征。
from sklearn.feature_extraction.text import CountVectorizer
vectorize = CountVectorizer()
X_vectorized = vectorize.fit_transform(X)
我們正處于訓(xùn)練線性回歸模型的最后一步,
from sklearn.linear_model import LinearRegression
import numpy as npregressor = LinearRegression()
regressor.fit(X_vectorized, y)
我們必須用幾個(gè)例子來測試它以檢查模型是否正常工作,
test_feature = vectorizer.transform(['Honk'])
prediction = regressor.predict(test_feature)
print(prediction)
test_feature = vectorizer.transform(['bowwow'])
prediction = regressor.predict(test_feature)
print(prediction)
test_feature = vectorizer.transform(['meoww'])
prediction = regressor.predict(test_feature)
print(prediction)]
#=> [1.]
#=> [0.]
#=> [0.36363636]
模型看起來很完美。
Pickle 我們的模型到一個(gè)字節(jié)流中,以便它可以將它們存儲在應(yīng)用程序中。
import pickle
pick = {
'vectorize': vectorize,
'regressor': regressor
}
pickle.dump( pick, open( 'models' + ".p", "wb" ) )
我們可以使用以下命令運(yùn)行服務(wù)器:
python manage.py runserver
添加幾個(gè) curl 請求來測試它。我們可以直接在瀏覽器地址欄中輸入網(wǎng)址。
curl -X GET http://127.0.0.1:8000/classify/?sound=buzz
#=> {"duck": 0.0}
curl -X GET http://127.0.0.1:8000/classify/?sound=quack
#=> {"duck": 1.0}
這個(gè)模型正在工作!接近 1 的數(shù)字表示它是一只鴨子,接近 0 的數(shù)字表示它不是一只鴨子。
我們也可以在瀏覽器中檢查這些。在網(wǎng)址:
http://127.0.0.1:8000/classify/?sound=buzz
http://127.0.0.1:8000/classify/?sound=quack
Django API 可以加載和運(yùn)行經(jīng)過訓(xùn)練的機(jī)器學(xué)習(xí)模型,并使用 URL 測試應(yīng)用程序。
下載Python源代碼: plot_iris_svc.py
下載Jupyter notebook源代碼: plot_iris_svc.ipynb
本文章轉(zhuǎn)載微信公眾號@機(jī)器學(xué)習(xí)算法與知識圖譜
Python + BaiduTransAPI :快速檢索千篇英文文獻(xiàn)(附源碼)
掌握ChatGPT API集成的方便指南
node.js + express + docker + mysql + jwt 實(shí)現(xiàn)用戶管理restful api
nodejs + mongodb 編寫 restful 風(fēng)格博客 api
表格插件wpDataTables-將 WordPress 表與 Google Sheets API 連接
手把手教你用Python和Flask創(chuàng)建REST API
使用 Django 和 Django REST 框架構(gòu)建 RESTful API:實(shí)現(xiàn) CRUD 操作
ASP.NET Web API快速入門介紹
2024年在線市場平臺的11大最佳支付解決方案