python图像分类_用于实现用python和django编写的图像分类的Keras UI
KerasUI是一種可視化工具,可以在圖像分類中輕松訓(xùn)練模型,并允許將模型作為服務(wù)使用,只需調(diào)用API。
https://github.com/zeppaman/KerasUI?
主要特點(diǎn):
用oauth2驗(yàn)證
允許完整的模型定制
可以上傳尚未訓(xùn)練的模型并通過API消費(fèi)
測試表格和視覺檢查網(wǎng)絡(luò)如何工作
批量上傳訓(xùn)練集
用法
運(yùn)行standalone.bat或sh standalone.bat(這將安裝需求應(yīng)用遷移并運(yùn)行服務(wù)器,相同的腳本適用于UNIX和Windows)
使用創(chuàng)建管理員用戶 python manage.py createsuperuser
導(dǎo)航到http://127.0.0.1:8000/
這需要python 3+,如果安裝了多個版本,請根據(jù)(即pip3)更改腳本。
如何管理數(shù)據(jù)集
Keras UI允許將數(shù)據(jù)集項(圖像)上載到Web應(yīng)用程序中。您可以逐個執(zhí)行此操作,也可以一次性添加包含許多圖像的zip文件。它管理多個數(shù)據(jù)集,因此您可以將事物分開。加載圖像后,可以單擊“訓(xùn)練”按鈕并運(yùn)行訓(xùn)練過程。這將訓(xùn)練您定義的模型,而無需您進(jìn)行任何交互。你將獲得訓(xùn)練結(jié)果,如果你很挑剔,你可以轉(zhuǎn)到日志文件,看看系統(tǒng)輸出了什么
如何使用Web UI進(jìn)行測試
為避免失眠,提供了一個簡單的表格,可以上傳圖像并獲得結(jié)果。
如何使用API UI或郵遞員來測試API
在Web UI中看到的所有內(nèi)容都可以使用API進(jìn)行復(fù)制。
API使用情況
此應(yīng)用程序使用oauth2來驗(yàn)證請求,因此需要的第一步是獲取令牌。這是密碼流的一個簡單示例。請記住必須啟用該應(yīng)用程序(首次運(yùn)行時不會默認(rèn)創(chuàng)建)。
Assumingclient hUiSQJcR9ZrmWSecwh1gloi7pqGTOclss4GwIt1osecret ZuuLK21sQ2uZxk8dVG7k6pO474FBlM6DEQs7FQvDh28gdLtbCDJwFFi0YlTlLsbz9ddjUa7Lun6ifYwkfwyGMD95WsCuzibFWIMpsZHMA039RIv1mOsYUO5nK5ZVv1hB POST to http://127.0.0.1:8000/o/token/ Headers:Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JWContent-Type: application/x-www-form-urlencoded Body:grant_type:passwordusername:adminpassword:admin2019!回應(yīng)是
{ "access_token": "h6WeZwYwqahFDqGDRr6mcToyAm3Eae", "expires_in": 36000, "token_type": "Bearer", "scope": "read write", "refresh_token": "eg97atDWMfqC1lYKW81XCvltj0sism"}獲取預(yù)測的API可以在json post或form post中使用。在json post中,圖像以base64字符串形式發(fā)送。這種使用服務(wù)的雙重方式非常有用,因?yàn)榭梢詫⑵滏溄拥奖韱位蛑苯优cwget或curl工具一起使用,也可以在應(yīng)用程序中使用它。
POST http://127.0.0.1:8000/api/test/ Headers:Content-Type:application/jsonAuthorization:Bearer Body{ "image":", "dataset":1}響應(yīng)?
{ "result": ""}教程
該項目是Codeproject上圖像分類上下文的一部分。這里是技術(shù)部分的演練,解釋它是如何構(gòu)建的以及它是如何工作的。
項目堆棧:
python
django框架
keras,tensorflow,numpy
sqlite(或您喜歡的其他數(shù)據(jù)庫)
使用的工具:
Visual Studio代碼
郵差
一個Web瀏覽器
項目設(shè)置
該項目基于Django,因此首先要做的是使用CLI創(chuàng)建一個Django項目。這需要從pip安裝Django。
django-admin startproject kerasui ' create the project此命令將生成以下結(jié)構(gòu):?
kerasui/ manage.py kerasui/ __init__.py settings.py urls.py wsgi.py這些文件是:
外部kerasui / root目錄只是項目的容器。內(nèi)部mysite /目錄是項目的實(shí)際Python包。它的名稱是需要用來導(dǎo)入其中任何內(nèi)容的Python包名稱(例如mysite.urls)。
manage.py:一個命令行實(shí)用程序,允許以各種方式與此Django項目進(jìn)行交互??梢栽趈ango-admin和manage.py中閱讀有關(guān)manage.py的所有詳細(xì)信息。
__init__.py:一個空文件,告訴Python該目錄應(yīng)該被視為Python包。如果是Python初學(xué)者,請閱讀官方Python文檔中有關(guān)包的更多信息。
kerasui / settings.py:此Django項目的設(shè)置/配置。Django設(shè)置將告訴有關(guān)設(shè)置如何工作的所有信息。
kerasui / urls.py:此Django項目的URL聲明; Django支持的站點(diǎn)的“目錄”??梢栽赨RL調(diào)度程序中閱讀有關(guān)URL的更多信息。
kerasui / wsgi.py:與WSGI兼容的Web服務(wù)器的入口點(diǎn),用于為項目提供服務(wù)。有關(guān)更多詳細(xì)信息,請參閱如何使用WSGI進(jìn)行部署。
運(yùn)行
要檢查是否一切正常,只需使用內(nèi)置服務(wù)器運(yùn)行django
python manage.py runserver也可以使用setup visual studio代碼來運(yùn)行django /
這是django配置:?
{ // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}\\kerasui\\manage.py", "args": [ "runserver", "--noreload", "--nothreading" ], "django": true } ]}設(shè)置配置
這里配置的基本部分告訴:
使用oauth 2和會話認(rèn)證使:常規(guī)Web用戶登錄并使用網(wǎng)站和休息沙箱,API用戶獲取令牌并查詢API服務(wù)
使用SQLite(可以更改為移動到任何其他數(shù)據(jù)庫)
添加所有Django模塊(以及兩個自定義:管理UI和API)
啟用cors
第一次運(yùn)行
Django使用遷移系統(tǒng)從您定義的模型生成遷移文件。要應(yīng)用遷移,只需運(yùn)行migrate命令(makemigration即可從模型創(chuàng)建遷移文件)。
用戶數(shù)據(jù)庫開始為空,因此需要創(chuàng)建admin用戶才能登錄。這是通過createsuperadmin命令完成的
python manage.py migratepython manage.py createsuperuseradmin\admin2019!它是如何構(gòu)建的
該應(yīng)用程序分為3個模塊:
管理部分: Web UI,模塊和所有核心內(nèi)容
后臺工作者:是一個可以在后臺執(zhí)行的Django命令,用于根據(jù)數(shù)據(jù)集訓(xùn)練模型
API:此部分公開API以從外部與應(yīng)用程序交互。例如,這允許從第三方應(yīng)用程序向數(shù)據(jù)集添加項目。此外,最常見的用法是發(fā)送圖像并獲得預(yù)測結(jié)果
管理
在Django上創(chuàng)建一個應(yīng)用程序:
python manage.py startapp management這將創(chuàng)建主文件。在這個模塊中,使用的最多是模型和模型表示:
module.py:這里是所有具有現(xiàn)場規(guī)格的型號。通過這樣的類定義,所有都被設(shè)置為對實(shí)體具有可用的CRUD
admin.py:此圖層描述了如何使用表單顯示和編輯數(shù)據(jù)。
數(shù)據(jù)模型非常簡單。假設(shè)只想為每個數(shù)據(jù)集訓(xùn)練一個模型
DataSet:它包含模型,模型設(shè)置和數(shù)據(jù)集的名稱。
DataSetItem:它包含數(shù)據(jù)集項,因此每行一個圖像附加標(biāo)簽。
這里只是一個模型和模型表示的示例:
#from admin.pyclass DataSetForm( forms.ModelForm ): process =forms.CharField( widget=forms.Textarea(attrs={'rows':40, 'cols':115}), initial=settings.PROCESS_TEMPLATE ) model_labels =forms.CharField(initial="[]") class Meta: model = DataSet fields = ['name', 'process','epochs','batchSize','verbose','model_labels','model'] widgets = { 'process': forms.Textarea(attrs={'rows':20, 'cols':200}), } def train(modeladmin, request, queryset): for dataset in queryset: DataSetAdmin.train_async(dataset.id) class DataSetAdmin(admin.ModelAdmin): list_display = ('name','epochs','batchSize','verbose','progress') inlines = [ # DataSetItemInline, ] form=DataSetForm actions = [train] change_list_template = "dataset_changelist.html" @staticmethod def train(datasetid): call_command('train',datasetid) @staticmethod def train_async(datasetid): t = threading.Thread(target=DataSetAdmin.train, args=(datasetid,)) t.setDaemon(True) t.start() admin.site.register(DataSet,DataSetAdmin) #from model.py class DataSet(models.Model): name= models.CharField(max_length=200) process = models.CharField(max_length=5000, default=settings.PROCESS_TEMPLATE) model = models.ImageField(upload_to=path_model_name,max_length=300,db_column='modelPath',blank=True, null=True) #weights = models.ImageField(upload_to=path_model_name,max_length=300,db_column='weightPath',blank=True, null=True) batchSize = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(1)],default=10) epochs = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(1)],default=10) verbose = models.BooleanField(default=True) progress = models.FloatField(default=0) model_labels= models.CharField(max_length=200) def __str__(self): return self.nameDjango采用代碼優(yōu)先方法,因此需要運(yùn)行python manage.py makemigrations以生成將應(yīng)用于數(shù)據(jù)庫的遷移文件。
python manage.py makemigrations背景工作者
要創(chuàng)建后臺工作程序,需要一個模塊來托管它,使用了管理模塊。在其中需要創(chuàng)建一個management文件夾。其上的每個文件都可以python manage.py commandname通過API 運(yùn)行或通過API 運(yùn)行。
在例子中,通過常規(guī)的Django動作在后臺進(jìn)程中啟動命令
這是相關(guān)部分:
class DataSetAdmin(admin.ModelAdmin): actions = [train] # .... @staticmethod def train(datasetid): call_command('train',datasetid) @staticmethod def train_async(datasetid): t = threading.Thread(target=DataSetAdmin.train, args=(datasetid,)) t.setDaemon(True) t.start()API
API是在一個單獨(dú)的應(yīng)用程序中創(chuàng)建的
python manage.py startapp API基本上所有CRUD模型都可以通過API公開,但是需要指定如何序列化它
class DataSetItemSerializer(serializers.HyperlinkedModelSerializer): image = Base64ImageField() dataset= serializers.PrimaryKeyRelatedField(many=False, read_only=True) class Meta: model = DataSetItem # Fields to expose via API fields = ('label', 'image', 'dataset') class DataSetSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = DataSet fields = ('name', 'process')還需要創(chuàng)建ViewSet模型和數(shù)據(jù)表示之間的映射:
class DataSetItemViewSet(viewsets.ModelViewSet): queryset = DataSetItem.objects.all() serializer_class = DataSetItemSerializer class DataSetViewSet(viewsets.ModelViewSet): queryset = DataSet.objects.all() serializer_class = DataSetSerializer最后需要定義所有路由并將viwset映射到url。這足以將模型用作api
router = routers.DefaultRouter()router.register(r'users', views.UserViewSet)router.register(r'datasetitem', views.DataSetItemViewSet)router.register(r'dataset', views.DataSetViewSet)router.register(r'test', views.TestItemViewSet, basename='test') # Wire up our API using automatic URL routing.# Additionally, we include login URLs for the browsable API.urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),] urlpatterns += staticfiles_urlpatterns()訓(xùn)練
算法非常簡單:
從數(shù)據(jù)集中獲取所有圖像
將它們標(biāo)準(zhǔn)化并添加到帶標(biāo)簽的列表中
創(chuàng)建模型在數(shù)據(jù)集模型中的指定方式
訓(xùn)練它
這是查詢數(shù)據(jù)集項和加載圖像的代碼段:
def load_data(self, datasetid): self.stdout.write("loading images") train_data = [] images = DataSetItem.objects.filter(dataset=datasetid) labels = [x['label'] for x in DataSetItem.objects.values('label').distinct()] for image in images: self.stdout.write("Loading {0}".format(image.image)) image_path = image.image.path if "DS_Store" not in image_path: index=[x for x in range(len(labels)) if labels[x]==image.label] label = to_categorical([index,],len(labels)) img = Image.open(image_path) img = img.convert('L') img = img.resize((self.IMAGE_SIZE, self.IMAGE_SIZE), Image.ANTIALIAS) train_data.append([np.array(img), np.array(label[0])]) return train_data看一眼:
labels = [x['label'] for x in DataSetItem.objects.values('label').distinct()]label = to_categorical([index,],len(labels))這為所有標(biāo)簽分配了一個順序,即["CAT","DOGS"]然后to_categorical將位置索引轉(zhuǎn)換為單熱表示。用簡單的話說,這使得CAT = [1,0]和DOG = [0,1]
訓(xùn)練模型
model=Sequential() exec(dataset.process) model.add(Dense(len(labels), activation = 'softmax')) model.fit(training_images, training_labels, batch_size=dataset.batchSize, epochs=dataset.epochs, verbose=dataset.verbose)請注意,dataset.process是在Web管理員中輸入的python模型定義,可以根據(jù)需要進(jìn)行調(diào)整。最后一層添加到用戶回調(diào)之外,以確保與數(shù)組大小匹配。
擬合方法只是使用所有數(shù)據(jù)運(yùn)行訓(xùn)練(。
最后存儲訓(xùn)練有素的模型:
datasetToSave=DataSet.objects.get(pk=datasetid)datasetToSave.progress=100datasetToSave.model_labels=json.dumps(labels)temp_file_name=str(uuid.uuid4())+'.h5'model.save(temp_file_name)datasetToSave.model.save('weights.h5',File(open(temp_file_name, mode='rb')))os.remove(temp_file_name)datasetToSave.save()請注意還保存標(biāo)簽順序beacuse必須與模型相同才能匹配one-hot約定。
預(yù)測
有一種常見的方法,給定樣本和數(shù)據(jù)集,檢索模型,加載模型并進(jìn)行預(yù)測。這是一段代碼:
def predict(image_path,datasetid): dataset=DataSet.objects.get(pk=datasetid) modelpath=dataset.model.path model=load_model(modelpath) labels=json.loads(dataset.model_labels) img = Image.open(image_path) img = img.convert('L') img = img.resize((256, 256), Image.ANTIALIAS) result= model.predict(np.array(img).reshape(-1,256,256, 1)) max=result[0] idx=0 for i in range(1,len(result)): if max max=result[i] idx=i return labels[idx]使用模型加載模型load_model(modelpath),標(biāo)簽來自數(shù)據(jù)庫。模型預(yù)測輸出作為值列表,選擇較高的索引并用于檢索在訓(xùn)練時分配給網(wǎng)絡(luò)輸出的正確標(biāo)簽。
關(guān)于圖書
《深度學(xué)習(xí)之TensorFlow:入門、原理與進(jìn)階實(shí)戰(zhàn)》和《Python帶我起飛——入門、進(jìn)階、商業(yè)實(shí)戰(zhàn)》兩本圖書是代碼醫(yī)生團(tuán)隊精心編著的 AI入門與提高的精品圖書。配套資源豐富:配套視頻、QQ讀者群、實(shí)例源碼、 配套論壇:http://bbs.aianaconda.com?。更多請見:https://www.aianaconda.com
總結(jié)
以上是生活随笔為你收集整理的python图像分类_用于实现用python和django编写的图像分类的Keras UI的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在线手册
- 下一篇: ZZULIOJ 1096: 水仙花数(函