Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: Machine Learning

CoreML Modelからパラメータを取得する v2

Posted on 12月 30, 2020 by Takaaki Naganoya

CoreML Modelのファイル(.mlmodelc)から入力パラメータおよび出力データの情報を取得するAppleScriptです。

テストに使ったのはMS Classifier(299×299ピクセルの画像を入力)で、入力画像をGundamのモビルスーツとして扱い、連邦軍機体かジオン軍機体かを判定するCoreML Modelです。

機械学習モデルのパラメータ/モデル解析を行うツール「Netron」にはWebアプリ版もあるので、JavaScriptやPythonで解析できてしまうのかもしれません(Netronのソースを読んでみたら、そういう感じのファイルだけ入っていて驚かされました)。

AppleScript名:CoreML Modelからパラメータを取得する v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/12/28
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — 10.13 or later
use framework "Foundation"
use framework "CoreML"
use scripting additions

set aVer to system version of (system info) –Get OS Version

considering numeric strings
  if aVer < "10.15" then
    –macOS 10.14。10.13は未検証
    
set mlFile to POSIX path of (choose folder) –mlmodelcを指定。macOS 10.14のFinder上ではフォルダに見えてしまう
  else
    –macOS 10.15 or later
    
set mlFile to POSIX path of (choose file of type {"com.apple.coreml.mlmodelc"}) –mlmodelcを指定。macOS 10.15以降のFinder上ではファイルに見える
  end if
end considering

set mlURL to current application’s |NSURL|’s fileURLWithPath:mlFile
set aModel to current application’s MLModel’s modelWithContentsOfURL:mlURL |error|:(missing value)
if aModel = missing value then return –mlmodelファイルだとエラーになる

set aMLDesc to aModel’s modelDescription
set inputDesc to aMLDesc’s inputDescriptionsByName()

–Input Information
set kList to inputDesc’s allKeys() as list
–> {"image"}

set vList to inputDesc’s allValues() as list
–> {(MLFeatureDescription) image : Image (Color, 299 x 299)}

–Output Information
set outputDeck to aMLDesc’s outputDescriptionsByName()
set k2List to outputDeck’s allKeys() as list
–> {"classLabel", "classLabelProbs"}

set v2List to outputDeck’s allValues() as list
–> {(MLFeatureDescription) classLabel : String, (MLFeatureDescription) classLabelProbs : Dictionary (String → Double)}

set vResList to {}
repeat with v in v2List
  set the end of vResList to v’s |name|() as string
end repeat
return vResList
–> {"classLabel", "classLabelProbs"}

★Click Here to Open This Script 

Posted in Machine Learning | Tagged 10.14savvy 10.15savvy 11.0savvy MLFeatureDescription MLModel NSURL | Leave a comment

機械学習で学習したMSの画像を連邦・ジオン軍判定してフォルダ分け v2

Posted on 11月 20, 2018 by Takaaki Naganoya

Create MLでガンダムのMS画像(連邦、ジオン区分け)を学習したCore ML Modelをもとに、画像をどちらの軍所属機体かを判定してフォルダ分けするAppleScriptです。

機械学習(深層学習)データをもとに判定を行って対話型処理ではなくバッチ処理的なフローでデータを「なんとなく」推論して区分けを行うサンプルです。非力なIOT機器が機械学習データをもとに推論処理できるぐらいなので、機械学習データを使ってAppleScriptで推論処理できないはずがありません。推論処理時間もさほどかからず、機械学習データを一括処理的なワークフローの中で利用することが可能です。

例によって「戦場の絆」の公式ページから落としてきたMSの画像を連邦軍とジオン軍、および両軍の鹵獲機体の4フォルダに分けてCreate MLで学習させてみました。

実行するとMS画像が入っているフォルダ(各自ご用意ください)と、連邦軍機体(efsf)およびジオン軍機体(zeon)を仕分けるフォルダを聞かれます。あとはプログラム側がなんとなく推論して仕分けを行います。

前回掲載のモデルもそうですが、きちんと学習後にテストデータで評価を行っています。だいたい8割ぐらいのヒット率ではあるものの、特定の画像については間違えることがあらかじめわかっています。

実行にあたっては、macOS 10.14上でCoreML Modelを組み込んだフレームワーク「msDetector.framework」をインストールして、本ScriptをScript Debugger上で動作させてください。

–> Download msDetector.framework (To ~/Library/Frameworks/)

–> Download msDetector (Code Signed executable AppleScript applet with Framework and libraries in its bundle)

Core MLで判定時に詳細なデータを出力させ、その可能性が0.8を上回るものだけを処理するようにしてみました。ただ、全力で間違った判定を行うケースもあるため、単なる「気休め」です。

テストデータでは、連邦軍側が72機体中間違いが9個(正解87.5%)、ジオン軍側が57機体中間違いが3個(正解95%)。鹵獲機体のデータを排除すると、もう少しいい値が出るかもしれません。ただ、学習させたデータとほぼ同じデータ(数が少ない)で再度判定を行っているだけなので、このぐらいの確度が出ないと逆に困ります。

また、確度が高くないものは排除するように処理したので、確度が低い機体の画像バリエーションを増やして学習画像数を足すと正解の確率が上がるのではないか、などと「なんとなく」考えています。

Create MLでは、もっときちんとした表データやタグ付き自然言語テキストデータ(日本語だと形態素への区分けはあらかじめやっておく必要アリ?)の学習が行えるようなので(自然言語テキストの学習例は英語のものしか見かけないけれども)いろいろやっておきたいところです。

今回は「アニメとかゲームに出てくるMSの画像」の判定という、実用性をまったく考えないで行なってみたものですが、自分の身の回りで有用性の高そうな処理といえば……アイコンやプレゼン用資料の作成画像を学習させておおまかなジャンル分けをしておき(メール系のアイコンとか)、未知のアイコン素材をダウンロードしてきたら機械学習データをもとに自動でフォルダ分けするとかでしょうか。

さすがにアイコン画像だとデフォルメされすぎていて、MicrosoftのAzure Computer Vision APIとかでも画像認識してくれなさそうなので。

AppleScript名:機械学習で学習したMSの画像の連邦軍、ジオン軍判定してフォルダ分け v2.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/11/20
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.7" — Mojave (10.14) or later & Script Debugger
use framework "Foundation"
use framework "AppKit"
use framework "msDetector"
use scripting additions

property |NSURL| : a reference to current application’s |NSURL|
property NSArray : a reference to current application’s NSArray
property NSString : a reference to current application’s NSString
property NSPredicate : a reference to current application’s NSPredicate
property NSFileManager : a reference to current application’s NSFileManager
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor
property NSURLTypeIdentifierKey : a reference to current application’s NSURLTypeIdentifierKey

set aFol to POSIX path of (choose folder with prompt "Choose MS Image folder to go!")
set efsfFol to POSIX path of (choose folder with prompt "EFSF folder")
set zeonFol to POSIX path of (choose folder with prompt "Zeon folder")

–指定フォルダ以下のファイルをすべて取得(再帰ですべて取得)
set aSel to retFullpathsWithinAFolderWithRecursive(aFol) of me

–取得したファイルリストを指定UTIでフィルタリング
set filRes2 to filterPOSIXpathListByUTI(aSel, "public.image") of me

–機械学習モデルを用いて区分けを行い、任意の画像の連邦軍(efsf)、ジオン軍(zeon)へのフォルダ分け(コピー)
set msClassifier to current application’s msClassify’s alloc()’s init()

repeat with i in filRes2
  set aFile to contents of i
  
set aImage to (current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile)
  
  
set resDict to (msClassifier’s ImageClassifierWithImageAndRetDict:aImage) –returns NSDictionary
  
  
–Dictinaryのvalueをソートして、最も値の大きいvalueのkeyを求める
  
set sortedArray to (current application’s NSMutableArray’s arrayWithArray:(resDict’s allValues()))
  (
sortedArray’s sortUsingSelector:"compare:")
  
set aRes to (last item of (sortedArray as list)) –末尾のアイテムが一番値の大きい数値
  
set resKey to first item of ((resDict’s allKeysForObject:aRes) as list) –最大値をもとにKeyを求める
  
  
–可能性の高いものだけ処理してみる(自信たっぷりに全力で間違えることもけっこうある)
  
if (aRes as real) > 0.8 then
    if resKey begins with "efsf" then
      –efsf & efsf_stolen
      
set aRes to (my copyFileAt:aFile toFolder:efsfFol)
    else
      –zeon & zeon_stolen
      
set aRes to (my copyFileAt:aFile toFolder:zeonFol)
    end if
  end if
end repeat

–POSIX path listから指定UTIに含まれるものをPOSIX pathのリストで返す
on filterPOSIXpathListByUTI(aList, targUTI)
  set newList to {}
  
repeat with i in aList
    set j to contents of i
    
set tmpUTI to my retUTIfromPath(j)
    
set utiRes to my filterUTIList({tmpUTI}, targUTI)
    
if utiRes is not equal to {} then
      set the end of newList to j
    end if
  end repeat
  
return newList
end filterPOSIXpathListByUTI

–指定のPOSIX pathのファイルのUTIを求める
on retUTIfromPath(aPOSIXPath)
  set aURL to |NSURL|’s fileURLWithPath:aPOSIXPath
  
set {theResult, theValue} to aURL’s getResourceValue:(reference) forKey:NSURLTypeIdentifierKey |error|:(missing value)
  
  
if theResult = true then
    return theValue as string
  else
    return theResult
  end if
end retUTIfromPath

–UTIリストが指定UTIに含まれているかどうか演算を行う
on filterUTIList(aUTIList, aUTIstr)
  set anArray to NSArray’s arrayWithArray:aUTIList
  
set aPred to NSPredicate’s predicateWithFormat_("SELF UTI-CONFORMS-TO %@", aUTIstr)
  
set bRes to (anArray’s filteredArrayUsingPredicate:aPred) as list
  
return bRes
end filterUTIList

–指定フォルダ以下のすべてのファイルを再帰で取得
on retFullpathsWithinAFolderWithRecursive(aFol)
  set anArray to NSMutableArray’s array()
  
set aPath to NSString’s stringWithString:aFol
  
set dirEnum to NSFileManager’s defaultManager()’s enumeratorAtPath:aPath
  
  
repeat
    set aName to (dirEnum’s nextObject())
    
if aName = missing value then exit repeat
    
set aFullPath to aPath’s stringByAppendingPathComponent:aName
    
anArray’s addObject:(aFullPath as string)
  end repeat
  
  
return anArray as list
end retFullpathsWithinAFolderWithRecursive

on copyFileAt:POSIXPath toFolder:folderPath
  set POSIXPath to NSString’s stringWithString:POSIXPath
  
set folderPOSIXPath to NSString’s stringWithString:folderPath
  
set theName to POSIXPath’s lastPathComponent()
  
set newPath to folderPOSIXPath’s stringByAppendingPathComponent:theName
  
set fileManager to NSFileManager’s defaultManager()
  
set theResult to fileManager’s copyItemAtPath:POSIXPath toPath:newPath |error|:(missing value)
  
return (theResult as integer = 1)
end copyFileAt:toFolder:

★Click Here to Open This Script 

Posted in file File path Image list Machine Learning Record | Tagged 10.14savvy NSArray NSFileManager NSMutableArray NSPredicate NSSortDescriptor NSString NSURL NSURLTypeIdentifierKey | 1 Comment

Bayes推定による文章仕分け(Classifier)

Posted on 11月 12, 2018 by Takaaki Naganoya

ベイズ推定を計算するオープンソースのプログラム「Bayes」をCocoaフレームワーク化した「BayesKit」を呼び出してベイズ推定の計算を行うAppleScriptです。

–> Download BayesKit.framework (To ~/Library/Frameworks)

macOS 10.14以外はスクリプトエディタ/Script Debugger上で実行可能で、10.14のみScript Debugger上での実行を必要とします(この仕様、いい加減かったるいので戻してほしい)。

スパムメール選別用途御用達のベイズ推定の演算を行なってみました。プログラムに添付されていたサンプルは英語の文章を処理するようにできていましたが、予想どおり日本語の文章をそのまま与えると単語切り分けが行えずに計算がうまく行きません。

そこで、掲載サンプルScriptのように単語ごとに手動で半角スペースを入れてみました。

本来であれば、形態素解析辞書を使って単語ごとに切り分け、さらに単語の活用形をどうにかする必要があるはずですが、そこまで神経質にならずに簡易日本語パーサーで単語に分解し、助詞などを削除しデータとして与えることでそこそこの実用性は確保できるのではないかと思われます(これだと固有名詞がバラバラになる可能性は否定できませんが)。

NSLinguisticTagger+macOS 10.14で日本語文章の形態素解析+品詞解析は行えることを期待したいですが、未確認です。ただ、できた場合でも固有名詞への配慮がどの程度あるかは不明です。

AppleScript名:Bayes推定による文章仕分け(Classifier).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/11/12
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan(10.11) or later
use framework "Foundation"
use framework "BayesKit" –https://github.com/kevincobain2000/Bayes
use scripting additions

property Bayes : a reference to current application’s Bayes
property FeaturesVector : a reference to current application’s FeaturesVector
property NSMutableArray : a reference to current application’s NSMutableArray

–set positiveStr to "word word good good"
–set negativeStr to "thiss word bad bad"
set positiveStr to "良い 良い 良い 良い 。"
set negativeStr to "悪 悪 悪 悪 悪 。"

set classifierObj to Bayes’s alloc()’s init()
set featuresVec to FeaturesVector’s alloc()’s init()

set featuresArray to NSMutableArray’s arrayWithArray:{"tokens"}

featuresVec’s appendFeatures:positiveStr forFeatures:featuresArray
classifierObj’s train:(featuresVec’s features) forlabel:"positive"

featuresVec’s appendFeatures:negativeStr forFeatures:featuresArray
classifierObj’s train:(featuresVec’s features) forlabel:"negative"

–set toGuess to "word"
set toGuess to "良い 。"

featuresVec’s appendFeatures:toGuess forFeatures:featuresArray
classifierObj’s guessNaiveBayes:(featuresVec’s features)

set vRes to (classifierObj’s probabilities) as record
–> {positive:0.6400000453, negative:0.32000002265}–English Sample Words OK
–> {positive:1.0, negative:0.0}–Japanese Sample Words OK

★Click Here to Open This Script 

Posted in Machine Learning Record Text | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSMutableArray | Leave a comment

squeezeNetで画像のオブジェクト認識を行い、結果をCSV出力してNumbersでオープン

Posted on 11月 12, 2018 by Takaaki Naganoya

Core MLモデル「squeezeNet.mlmodel」を用いて画像のオブジェクト認識を行い、結果をデスクトップにCSV形式でデータ書き出しを行い、NumbersでオープンするAppleScriptです。

–> Download squeezeNetKit.framework (To ~/Library/Frameworks)

macOS 10.13上ではスクリプトエディタ、Script Debugger上で、macOS 10.14上ではScript Debugger上で動作します(AppleScript Appletでも動作)。

さまざまなCore MLモデルを用いて画像認識を行わせてはみたものの、最もスコアの高いもののラベルだけを返させても、結果がまったく内容にそぐわないケースが多く見られます。


▲機械学習の評価値が1.0に近いものは確度が高く、0.0に近いものは判断に迷った末に消極的に出した値。経験則でいえば、最高スコアの項目が0.7以上のスコアでないといまひとつのようです(0.7以上でもダメな時はダメなわけで、、、)

画像認識については、結果があまりに的外れで「なんじゃこら?」というケースが多いので、確認のためにCSVデータ出力させてNumbers上で確認させてみることにしてみました。そのためにありあわせのサブルーチンを組み合わせて作ったものです。

スコアが高い順に結果を並べて確認してみると、最も高いスコアの値であっても0.0に近い評価値であることがあり、「何も考えずに最高スコアのラベルだけ取ってくるのはものすごく危険」なことがよくわかります。


▲squeezeNet.mlmodelをNetronでビジュアライズしたところ(一部抜粋)

AppleScript名:SqueezeNetでオブジェクト判定して結果をCSV書き出ししてNumbersでオープン.scpt
–  Created by: Takaaki Naganoya
–  Created on: 2018/11/11
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use framework "AppKit"
use framework "squeezeNetKit"
use scripting additions

property NSUUID : a reference to current application’s NSUUID
property NSArray : a reference to current application’s NSArray
property NSImage : a reference to current application’s NSImage
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

set aFile to POSIX path of (choose file of type {"public.image"})
set aImage to NSImage’s alloc()’s initWithContentsOfFile:aFile
set resDict to (current application’s imageClassifier’s alloc()’s init()’s ImageClassifierWithImageAndRetDict:aImage)

set kArray to (resDict’s allKeys())
set vArray to (resDict’s allValues())
set aLen to kArray’s |count|()

set anArray to NSMutableArray’s new()

repeat with i from 0 to (aLen – 1)
  set tmpKey to (kArray’s objectAtIndex:i) as string
  
set tmpVal to (vArray’s objectAtIndex:i) as real
  (
anArray’s addObject:{aKey:tmpKey, aVal:tmpVal})
end repeat

–Sort by value
set bList to sortRecListByLabel(anArray, "aVal", false) of me

–record in list –> 2D list
set cList to convRecInListTo2DList(bList) of me

–デスクトップにCSVファイルを書き出してNumbersでオープン
set aPath to (((path to desktop) as string) & (NSUUID’s UUID()’s UUIDString()) as string) & ".csv"
set fRes to saveAsCSV(cList, aPath) of me
tell application "Numbers"
  open (aPath as alias)
end tell

–リストに入れたレコードを、指定の属性ラベルの値でソート
on sortRecListByLabel(aRecList as list, aLabelStr as string, ascendF as boolean)
  set aArray to NSArray’s arrayWithArray:aRecList
  
set sortDesc to NSSortDescriptor’s alloc()’s initWithKey:aLabelStr ascending:ascendF
  
set sortDescArray to NSArray’s arrayWithObjects:sortDesc
  
set sortedArray to aArray’s sortedArrayUsingDescriptors:sortDescArray
  
set bList to (sortedArray) as anything
  
return bList
end sortRecListByLabel

on convRecInListTo2DList(aList)
  set anArray to NSMutableArray’s arrayWithArray:aList
  
set fItem to anArray’s objectAtIndex:0
  
set keyList to fItem’s allKeys() as list
  
set aCount to anArray’s |count|()
  
  
set allArray to NSMutableArray’s new()
  
  
repeat with i from 1 to aCount
    set anItem to (anArray’s objectAtIndex:(i – 1))
    
set tmpItem to {}
    
    
repeat with ii in keyList
      set tmpDat to (anItem’s valueForKeyPath:(contents of ii))
      
if tmpDat is not equal to missing value then
        set the end of tmpItem to tmpDat
      else
        set the end of tmpItem to ""
      end if
    end repeat
    (
allArray’s addObject:tmpItem)
  end repeat
  
  
set allList to allArray as list
  
set the beginning of allList to keyList
  
return allList
end convRecInListTo2DList

–CSV Kit

–2D List to CSV file
on saveAsCSV(aList, aPath)
  –set crlfChar to (ASCII character 13) & (ASCII character 10)
  
set crlfChar to (string id 13) & (string id 10)
  
set LF to (string id 10)
  
set wholeText to ""
  
  
repeat with i in aList
    set newLine to {}
    
    
–Sanitize (Double Quote)
    
repeat with ii in i
      set jj to ii as text
      
set kk to repChar(jj, string id 34, (string id 34) & (string id 34)) of me –Escape Double Quote
      
set the end of newLine to kk
    end repeat
    
    
–Change Delimiter
    
set aLineText to ""
    
set curDelim to AppleScript’s text item delimiters
    
set AppleScript’s text item delimiters to "\",\""
    
set aLineList to newLine as text
    
set AppleScript’s text item delimiters to curDelim
    
    
set aLineText to repChar(aLineList, return, "") of me –delete return
    
set aLineText to repChar(aLineText, LF, "") of me –delete lf
    
    
set wholeText to wholeText & "\"" & aLineText & "\"" & crlfChar –line terminator: CR+LF
  end repeat
  
  
if (aPath as string) does not end with ".csv" then
    set bPath to aPath & ".csv" as Unicode text
  else
    set bPath to aPath as Unicode text
  end if
  
  
write_to_file(wholeText, bPath, false) of me
  
end saveAsCSV

on write_to_file(this_data, target_file, append_data)
  tell current application
    try
      set the target_file to the target_file as text
      
set the open_target_file to open for access file target_file with write permission
      
if append_data is false then set eof of the open_target_file to 0
      
write this_data to the open_target_file starting at eof
      
close access the open_target_file
      
return true
    on error error_message
      try
        close access file target_file
      end try
      
return error_message
    end try
  end tell
end write_to_file

on repChar(origText as text, targChar as text, repChar as text)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to targChar
  
set tmpList to text items of origText
  
set AppleScript’s text item delimiters to repChar
  
set retText to tmpList as string
  
set AppleScript’s text item delimiters to curDelim
  
return retText
end repChar

★Click Here to Open This Script 

Posted in file Image list Machine Learning Record Sort | Tagged 10.13savvy 10.14savvy NSArray NSImage NSMutableArray NSSortDescriptor NSUUID Numbers | Leave a comment

機械学習モデルをもとに画像のシーン判定

Posted on 11月 6, 2018 by Takaaki Naganoya

Appleが配布しているCoreML Model「Places205-GoogLeNet」を用いて、指定画像のシーン判定を行うAppleScriptです。

Appleが公式に配布している6つのCoreML Modelのうち、「Places205-GoogLeNet」を組み込んだFrameworkを作成して、これをAppleScriptから呼び出しています。

sceneDetection.frameworkをインストールしたうえで、macOS 10.13上ではスクリプトエディタ/Script Debuggerから、macOS 10.14ではScript Debuggerから本Scriptを実行します(AppleScriptアプレットでも動作します)。

「Places205-GoogLeNet」は、

Detects the scene of an image from 205 categories such as an airport terminal, bedroom, forest, coast, and more.

と、画像の内容から、画面やシーン、場所について「だいたいこんなところ」と判定してくれるModelのようです。ただ、日本国内の景色を渡してみると、得られる判定結果にはいまひとつ「ちょっと違う」と感じるものであります。


▲左:crosswalk(横断歩道)実際には自動車販売店と道路(Car shop & road)、右:desert/sand(砂漠、砂)実際にはAirport


▲左:river(川)実際には海、右:bridge(橋) 実際には橋ではありません

–> Download sceneDetection.framework (To ~/Library/Frameworks)


▲GoogLeNetPlaces.mlmodelをNetronでビジュアライズしたところ

AppleScript名:GoogLeNetPlacesでシーン判定.scpt
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use framework "AppKit"
use framework "sceneDetection"
use scripting additions

set aFile to POSIX path of (choose file of type {"public.image"})
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile
set msDict to (current application’s sceneDetector’s alloc()’s init()’s GoogLeNetPlacesWithImage:aImage) as string
–> "crosswalk"

★Click Here to Open This Script 

Posted in file Image Machine Learning | Tagged 10.13savvy 10.14savvy NSImage | Leave a comment

CreateMLで機械学習したモデルを利用して、MS画像の連邦、ジオン軍判定

Posted on 11月 6, 2018 by Takaaki Naganoya

「戦場の絆」のホームページからダウンロードしたMSの画像を学習させた機械学習モデルを使用して、指定のMS画像が地球連邦軍(EFSF)かジオン軍(zeon)かを判定するAppleScriptです。


■©創通・サンライズ 学習時に299×299ピクセルに縮小されるので、モノアイとかそういう部分が特徴量として検出されることはないもよう

両軍合わせて180機体ほどの画像を学習させただけなので、正直なところ判定間違いが多いですが、増やしていくとけっこう簡単に判定できそうです(数万ファイルぐらい画像を学習させるともっと明確な傾向が出てくるかも?)。


▲学習させたMS画像データ。efsf、efsf_stole(鹵獲機体)、zeon、zeon_stole(鹵獲機体)に分けてみた。CoreMLで任意のMS画像がこれらのどのグループに所属する可能性が最も高いかをフォルダ名で返してくることになる

macOS 10.14上のスクリプトエディタは野良Frameworkを認識してくれないので、macOS 10.14.x+Script Debugger上で実行する必要があります。あと、AppleScriptアプレットに書き出して実行すると野良Frameworkを認識して実行するので、アプレットに書き出して実行するとScript DebuggerのないmacOS 10.14環境でも動作確認できます。

Xcode上でSwift Playgroundを用いて認識していた時よりも認識精度が下がっているように見えます。結局画像は299×299ピクセルぐらいに縮小されて判定されるので、判定前に画像余白部分をトリミングしておくと認識精度が上がりそうな気もします。

299×299ピクセルに縮小されると、さすがにモノアイが特徴量として認識される可能性も低く、色とかポーズとか構図とかで識別されているのでしょう。


▲作成したmodelをNetronでビジュアライズしたところ

CreateMLで機械学習モデルを作るのがとても簡単であることがわかり、機械学習モデルを呼び出すためのAppleScriptのコードがとてもシンプルなことがわかり、さらに学習モデルを用いた画像分類が短い時間で行えることを確認できました。

現在のところ、1つの機械学習モデル(.mlmodel)を使うためにそのモデルを組み込んだFrameworkを必要としている状態ですが、機械学習モデル自体も外部からパスで指定して柔軟に指定できるようにしたいところです。

これで調子に乗って手書き文字画像データ(Mnist)をCreateMLで機械学習して、手書き文字の画像をスキャナから読み取って手軽に手書き文字認識できるかも?! と、鼻息荒くテストしてみましたが、期待したような精度では判定されないことを思い知らされたのでした。

–> Download msDetector.framework (To ~/Library/Frameworks)

AppleScript名:機械学習で学習したMSの画像の連邦軍、ジオン軍判定.scpt
use AppleScript version "2.7" — Mojave (10.14) or later
use framework "Foundation"
use framework "AppKit"
use framework "msDetector"
use scripting additions

set aFile to POSIX path of (choose file of type {"public.image"})
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile
set msRes to current application’s msClassify’s alloc()’s init()’s ImageClassifierWithImage:aImage
–> "efsf" / "zeon"

★Click Here to Open This Script 

Posted in file Image Machine Learning | Tagged 10.14savvy NSImage | Leave a comment

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • macOS 13, Ventura(継続更新)
  • アラートダイアログ上にWebViewで3Dコンテンツを表示(WebGL+three.js)v3
  • UI Browserがgithub上でソース公開され、オープンソースに
  • macOS 13 TTS Voice環境に変更
  • Xcode 14.2でAppleScript App Templateを復活させる
  • 2022年に書いた価値あるAppleScript
  • ChatGPTで文章のベクトル化(Embedding)
  • 新発売:AppleScriptからSiriを呼び出そう!
  • iWork 12.2がリリースされた
  • 従来と異なるmacOS 13の性格?
  • 新発売:CotEditor Scripting Book with AppleScript
  • macOS 13対応アップデート:AppleScript実践的テクニック集(1)GUI Scripting
  • AS関連データの取り扱いを容易にする(はずの)privateDataTypeLib
  • macOS 13でNSNotFoundバグふたたび
  • macOS 12.5.1、11.6.8でFinderのselectionでスクリーンショット画像をopenできない問題
  • ChatGPTでchatに対する応答文を取得
  • 新発売:iWork Scripting Book with AppleScript
  • Finderの隠し命令openVirtualLocationが発見される
  • macOS 13.1アップデートでスクリプトエディタの挙動がようやくまともに
  • あのコン過去ログビューワー(暫定版)

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1390) 10.14savvy (586) 10.15savvy (434) 11.0savvy (277) 12.0savvy (185) 13.0savvy (55) CotEditor (60) Finder (47) iTunes (19) Keynote (98) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (41) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (117) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (56) Pages (37) Safari (41) Script Editor (20) WKUserContentController (21) WKUserScript (20) WKUserScriptInjectionTimeAtDocumentEnd (18) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • drive
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC