AI_ML_DL’s diary

人工知能、機械学習、ディープラーニングの日記

Deepfake Detection Challenge - 1

Deepfake Detection Challenge - 1

Identify videos with facial or voice manipulations

 

*コンペに参加

・コンペに参加する必須条件の1つは、規則を遵守することである。

・そのためには、規則を正しく理解しなければならない。

・今回は、データセットの特殊性により、データの使用、管理等に関する注意事項が、提供元から、非常に細かいところまで定義されているように思う。

・データ使用の許諾契約書を正確に理解するのは、母国語であっても容易ではない。慎重に読み進むことが求められる。

 

*本コンペに参加しようと思った理由

1.ビデオデータを扱えるようになりたい。

2.画像にしても、音声にしても、えっ、fakeかどうか見分けられるの?、できたらすごいな、と思った。

 

*文献調査等

Detecting Face2Face Facial Reenactment in Videos, P. Kumar et al., arXiv 21 Jan 2020

・これは、FaceForensics dataset(FaceForensics++は、DeepFakes, Face2Face, FaceSwap, NeuralTextuesの4つの手法で処理して作成されたデータベースであるが、本論文では、Face2Faceで作成されたデータセットを用いている)を用いて、ビデオ画像からFakeかどうか判定する方法を検討したもの。

・Fake Videoを作る方法:2.1. Generation Techniques

・Fake Videoを見破るこれまでの方法:2.2. Detection Algorithms

・見破る方法の提案:Proposed Detection Algorism

 Face2Face reenactment techniqueで作成されたFake videoを見破る方法の提案である。

f:id:AI_ML_DL:20200213155447p:plain

f:id:AI_ML_DL:20200213155602p:plain

 

DeeperForensics-1.0: A Large-Scale Dataset for Real-World Face Forgery Detection, L. Jiang et al., arXiv 9 Jan 2020

・Fake videoのデータベース作成

・既存のデータベースの10倍の規模

・既存のデータベースよりも高品質なfake videoを作成する方法

*なぜ高品質なデータベースが必要なのか:Fake かどうかを見分けるモデルの性能は、トレーニングに用いるデータベースの質に依存するからである。

・したがって、この論文では、作成したデータベースの性能を測るために、Fakeを見破る能力の高いモデルが用いられている。

・C3D, TSN, I3D, ResNet+LSTM, XceptionNetなどが、データベースの性能評価のために用いられている。

*ということは、DeeperForensics-1.0でトレーニングしたこれらのモデルは、fakeを見破る能力が高いということになる。ただし、ResNet+LSTMとXceptionNet は、汎用的に用いられている手法である。

f:id:AI_ML_DL:20200213160228p:plain

 

Recurrent Convolutional Strategies for Face Manipuration Detection in Videos, E. Sabir et al., arXiv 16 May 2019

f:id:AI_ML_DL:20200213151203p:plain

 

Deepfake Video Detection Using Recurrent Neural Networks, D. Güera and E. J. Delp, AVSS, pages 1-6, IEEE, 2018

f:id:AI_ML_DL:20200213155035p:plain

 

*コンペに直接関連した文献が、少なくとも、これだけあることに驚いた。(ほんの一部かもしれない)

 

*明日は、コンペのdiscussionとnotebookから学ぼう。

 

つづく 


 

f:id:AI_ML_DL:20200213073253p:plain

style=104 iteration=1

f:id:AI_ML_DL:20200213073341p:plain

style=104 iteration=20

f:id:AI_ML_DL:20200213073421p:plain

style=104 iteration=500

 

Machine Learning without DNN - 2

Machine Learning without DNN - 2

 

ニューラルネットを使わない機械学習の勉強をする。

・テキストは、

A. Géron, Hands-On Machine Learning with Scikit-Learn & TensorFlow, March 2017: First Edition, O'Reilly

・論文は、

Comparison between XGBoost, LightGBM and CatBoost Using a Home Credit Dataset, E. AI-Daoud, International Journal of Computer and Information Engineering, 13, (2019) 6-10

LightGBM: A Highly Efficient Gradient Boosting Decision Tree, G. Ke et al., NIPS 2017

XGBoost: A Acalable Tree Boosting System, T. Chen and C. Guestrin, arXive 10 Jun 2016

CatBoost: gradient boosting with categorical features support, A. V. Dorogush et ai., arXiv 24 Oct 2018

・Ensemble Learning and Random Forestsと、XGBoost, LightGBM, CatBoostなどを勉強しよう。

 

*今日は、Boostingを勉強しよう。

 

Boosting

Boosting (originally called hypothesis boosting) refers to any Ensemble method that can conbine several weak learners into a strong learner.

The general idea of most boosting methods is to train predictors sequentially, each trying to correct its predecessor.

There are  many boosting methods available, but by far the most popular are AdaBoost (short for Adaptive Boosting) and Gradient Boosting.

・・・・・

skip AdaBoost

・・・・・

Gradient Boosting

Anothe vary popular Boosting algorithm is Gradient Boosting.

Just like Adaboost, Gradient Boosting works by sequentially adding predictors to an ensemble, each one correcting its predecessor.

However, instead of tweaking the instance weights at every iteration like AdaBoostdoes, this method tries to fit the new predictor to the residual errors made by the previous predictor.

Let's go through a simple regression example using Decision Trees as the base predictors (of course Gradient Boosting also works great with regression tasks).

This is called Gradient Tree Boosting, or Gradient Boosted Regression Trees (GBRT).

First, Let's fit a DecisionTreeRegressor to the training set (for example, a noisy quadratic training set):

    from sklearn.tree import DecisionTreeRegressor

    tree_reg1 = DecisionTreeRegressor(max_depth=2)

    tree_reg1.fit(X, y)

Now train a second DecisionTreeRegressor on the residual errors made by the first predictor:

    y2 = y - tree_reg1.predict(X)

    tree_reg2 = DecisionTreeRegressor(max_depth=2)

    tree_reg2.fit(X, y2)

 Then we train a third regressor on the residual errors made by the second predictor:

    y3 = y2 - tree_reg2.predict(X)

    tree_reg3 = DecisionTreeRegressor(max_depth=2)

    terr_reg3.fit(X, y3)

Now we have an ensemble containing three trees.

It can make predictions on a new instance simply by adding up the predictions of all the trees:

    y_pred = sum(tree.predict(X_new) for tree in (tree_reg1, tree_reg2, tree_reg3))

 

A simpler way to train GBRT (Gradient Boosted Regression Trees) ensemble is to use Scikit-Learn's GradientBoostingRegressor class.

Much like the RandomForestRegressor class, it has hyperparameters to control the growth of Decision Trees (e.g., max_depth, min_samples_leaf, and so on), as well as hyperparameters to control the ensemble training, such as the number of trees (n_estimators).

The following code creates the same ensemble as the previous one:

    from sklearn.ensemble import GradientBoostingRegressor

    gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=3, learning_rate=1.0)

    gbrt.fit(X, y)

 

*ここで、Scikit-learnについて思い出したことがある。誰か忘れたが、twitterで、scikit-learnのHPがずっと昔のままだ。こんな重要なツールを放置しておいてはいけない、というような内容の発言をしていた。

・ということで、HPをチェックした。

・記憶が間違っていなければ、大きく変わっている。

・ついでに、AnacondaのScikit-learnをアップデートしてみた。

・0.21.2 から0.22.1へのアップデートだったが、関連モジュール・パッケージが多くて、時間がかかった。

・さらに、気になるLightGBMで検索したら、次の記事があった。まだ実験段階だが、高速かつデータ欠損に対応しているようだ。ただし、予測精度が向上するとまでは記述されていない。

Scikit-learn 0.21 introduces two new experimental implementations of gradient boosting trees, namely HistGradientBoostingClassifier and HistGradientBoostingRegressor, inspired by LightGBM (See [LightGBM]).

These histogram-based estimators can be orders of magnitude faster than GradientBoostingClassifier and GradientBoostingRegressor when the number of samples is larger than tens of thousands of samples.

They also have built-in support for missing values, which avoids the need for an imputer.

These fast estimators first bin the input samples X into integer-valued bins (typically 256 bins) which tremendously reduces the number of splitting points to consider, and allows the algorithm to leverage integer-based data structures (histograms) instead of relying on sorted continuous values when building the trees. The API of these estimators is slightly different, and some of the features from GradientBoostingClassifier and GradientBoostingRegressor are not yet supported: in particular sample weights, and some loss functions.

These estimators are still experimental: their predictions and their API might change without any deprecation cycle. To use them, you need to explicitly import enable_hist_gradient_boosting:

 

*テキストに沿って、基本的なところを学んでおこう。丸写しだけど!

The learning_rate hyperparameter scales the contribution of each tree.

If you set it to a low value, such as 0.1, you will need more trees in the ensemble to fit the training set, but the prediction will usually generalize better.

This is a regularization technique called shrinkage.

Figure 7-10 shows two GBRT ensembles trained with a low learning rate: the one on the left (lr=0.1, estimators=3) does not have enough trees to fit the training set, while the one on the right (lr=0.1, estimators=200) has too many trees and overfits the training set. 

In order to find the optimal number of trees, you can use early stopping (see Chapter 4). 

A simple way to implement this is to use the staged_predict() method: it returns an iterator over the predictions made by the ensemble at each stage of training (with one tree, two tree, atc.).

The following code trains a GBRT (Gradient Boosted Regression Trees) ensemble with 120 trees, then measures the validation error at each stage of training to find the optimal number of trees, and finally trains another GBRT ensemble using the optimal number of trees:

    import numpy as np

    from sklearn.model_selection import train_test_split

    from sklearn.metrics import mean_square_error

    X_train, X_val, y_train, y_val = train_test_split(X, y)

    gbrt = GradientBoostingRegressor(max_depth=2, n_estimators=120)

    gbrt.fit(X_train, y_train)

    errors = [mean_squared_error(y_val, y_pred)

                  for y_pred in gbrt.staged_predict(X_val)]

    bst_n_estimators = np.argmin(errors)

    gbrt_best=GradientBoostingRegressor(max_depth=2,n_estimators=bst_n_estimators)

    gbrt_best.fit(X_train, y_train)

*これは、過学習が起きるまで学習させ、最適tree numberを見つけ、その最適tree numberで再度、学習させる方法であるが、次に示すのは、validation errorが改善されなくなったら、学習をやめ、その時点まで学習したモデルで、予測するという方法、いわゆるearly stoppingである。

It is also possible to implement early stopping by actually stopping training early (instead of training a large number of trees first and then looking back to find the optimal number).

You can do so by setting warm_start=True, which makes Scikit-Learn keep existing trees when the fit() method is called, allowing incremental training. The following code stops training when the validation error does not improve for five iterations in a row:

    gbrt = GradientBoostingRegressor(max_depth=2, warm_start=True)

    min_val_error = float("inf")

    error_going_up = 0

    for n_estimators in range(1, 120):

         gbrt.n_estimators = n_estimators

         gbrt.fit(X_train, y_train)

         y_pred = gbrt.predict(X_val)

         val_error = mean_squared_error(y_val, y_pred)

         if val_error < min_val_error:

             min_val_error = val_error

             error_going_up = 0

         else:

             error_going_up += 1

             if error_going_up == 5:

                 break  # early stopping

 

The GradientBoostingRegressor class also supports a subsample hyperparameter, which specifies the fraction of training instances to be used for training each tree.

For example, if subsample=0.25, then each tree is trained on 25% of the training instances, selected randomly.

As you can probably guess by now, this trades a higher bias for a lower variance.

It also speeds up training considerably.

This technique is called Stochastic Gradient Boosting.

 

* XGBoost, LightGBM, CatBoost等について。

論文読んでいるけど、難しい。

背伸びしすぎず、今回のテーマは、いったん終了する。

 

*明日からは、Kaggleのコンペ、Deepfake Detection Challengeに挑戦してみよう。

 

f:id:AI_ML_DL:20200212071545p:plain

style=103 iteration=1

f:id:AI_ML_DL:20200212071643p:plain

style=103 iteration=20

f:id:AI_ML_DL:20200212071726p:plain

style=103 iteration=500

 

Machine Learning without DNN - 1

Machine Learning without DNN - 1

 

*今日は、ニューラルネットを使わない機械学習の勉強をする。

・テキストは、A. Géron, Hands-On Machine Learning with Scikit-Learn & TensorFlow, March 2017: First Edition, O'Reilly

・昨年、第2版が出版されたが、手元にあるのは初版である。

・Chapter 7 : Ensemble Learning and Random Forestsと、XGBoost, LightGBMなどを勉強しよう。

 

1. The Machine Learning Landscape

What Is Machine Learning?

Machine Learning is the science (and art) of programming computers so they can learn from data.

A computer program is said to learn from experience E with respect to some task T and some performance measure P, if its performance on T, as measured by P, improves with experience E. ---Tom Mitchell, 1997

For example, your spam filter is a Machine Learning program that can learn to flag spam given example of spam emails (e.g., flagged by users) and example of regular (nonspam, also called "ham") emails. The examples that the system uses to learn are called the training set. Each training example is called a training instance (or sample). In this case, the task T is to flag spam for new emails, the experience E is the training data, and the performance measure P needs to be defined; for example, you can use the ratio of correctly classified emails. This particular performance measure is called accuracy and it is often used in classification tasks.

If you just downloaded a copy of Wikipedia, your computer has a lot more data, but it is not suddenly better at any task. Thus it is not Machine Learning.

Why Use Machine Learning?

To summarize, Machine Learning is great for:

・Problems for which existing solutions require a lot of hand-tuning or long list of rules: one Machine Learning algorithm can often simplify code and perform better.

・Complex problems for which there is no good solution at all using a traditional approach: the best Machine Learning techniques can find a solution.

・Fluctuating environments: a Machine Learning system can adapt to new data.

・Getting insights about complex problems and large amounts of data.

Types of Machine Learning Systems

There are so many different types of Machine Learning systems that it is useful to classify them in broad categories based on:

・Whether or not they are trained with human supervision (supervised, unsupervised, semisupervised, and Reinforcement Learning)

・Whether or not they can learn incrementally on the fly (online versus batch learning)

・Whether they work by simply comparing new data points to known data points, or instead detect patterns in the training data and build a predictive model, much like scientist do (instance-based versus model-based learning)

Supervised/Unsupervised Learning

Supervised learning

In supervised learning, the training data you feed to the algolism includes the desired solutions, called lables.

A typical supervised learning task is classification. The spam filter is a good example of this: it is trained with many example emailes along with their class (spam or ham), and it must learn how to classify new emailes.

Another typical task is to predict a target numeric value, such as a price of a car, given a set of features (mileage, age, brand, etc.) called predictors. This sort of task is called regression. To train the system, you need to give it many examples of cars, including both their predictors and their lables (i.e., their prices).

Here are some of the most important supervised learning algorithms (covered in this book):

・k-Nearest Neighbors

・Linear Regression

・Logistic Regression

・Support Vector Machines (SVMs)

・Decision Trees and Random Ferests

・Neural networks

Unsupervised learning

In unsupervised learning, as you might guess, the training data is unlabled. The system tries to learn without a teacher.

Here are some of the most important unsupervised learning algolisms (we will cover dimensionality reduction in Chapter 8):

・Clustering

    - k-Means

    - Hierarchical Cluater Analysis (HCA)

    - Expectation Maximization

・Visualization and dimensionality reduction

    - Principal Component Analysis (PCA)

    - Kernel PCA

    - Locally-Linear Embedding (LLE)

    - t-distributed Stochastic Neighbor Embedding (t-SNE)

・Association rule learning

    - Apriori

    - Eclat

Semisupervised learning

Some algorithms can deal with partially labled training data, usually a lot of unlabled data and a little bit of labled data. This is called semisupervised learning.

Reinforcement Learning

Batch and Online Learning

Batch learning

Online learning

Instance-Based Versus Model-Based Learning

・・・・・・・・・・

 

CHAPTER 7

Ensenble Learning and Random Forests

Voting Classifiers

The following code creates and trainis a voting classifier in Scikit-Learn, composed of three classifiers (the training set is the moons dataset, introduced in Chapter 5):

    from sklearn.ensemble import RandomForestClassifier

    from sklearn.ensemble import VotingClassifier

    from sklearn.linear_model import LogisticRegression

    from sklearn.svm import SVC

    log_clf = LogisticRegression()

    rnd_clf = RandomForestClassifier()

    svm_clf = SVC()

    voting_clf = VotingClassifier(

        estimators=[('lr', log_clf), ('rf', rnd_clf), ('svc', svm_clf)], voting='hard')

    voting_clf.fit(X_train, y_train)

Let's look at each classifier's accuracy on the test set:

    >>> from sklearn.metrics import accuracy_score

    >>> for clf in (log_clf, rnd_clf, svm_clf, voting_clf):

    >>>      clf.fit(X_train, y_train)

    >>>      y_pred = clf.predict(X_test)

    >>>     print(clf.__class__.__name__, accuracy_score(y_test, y_pred)

    >>>

    LogisticRegression 0.864

    RandomForestClassifier 0.872

    SVC 0.888

    VotingClassifier 0.896

Ther you have it! The voting classifier slightly outperforms all the individual classifiers.

If all classifiers are able to estimate class probabilities (i.e., they have a predict_proba() method), then you can tell Scikit-Learn to predict the class with the highest class probability, averaged over all the individual classifiers.

This is called soft voting.

It often achieves higher performance than hard voting because it gives more weight to highly confident votes.

All you need to do is replace voting="hard" with voting="soft" and ensure that all classifiers can estimate class probabilities.

This is not the case of the SVC class by default, so you need to set its probability hyperparameter to True (this will make the SVC class use cross-validation to estimate class probabilities, slowing down training, and it will add a predict_proba() method).

If you modify the preceding code to use soft voting, you will find that the voting classifier achieved over 91% accuracy!

Bagging and Pasting

One way to get a diverse set of classifiers is to use very different training algorithms, as just discusses. Another approach is to use the same training algolithm for every predictor, but to train them on different random subset of the training set.

When sampling is performed with replacement, this method is called bagging.  

When sampling is performed without replacement, it is called pasting. 

Bagging and Pasting in Scikit-Learn

The followin g code trains an ensemble of 500 Decision Tree classifiers, each trained on 100 training instances randomly sampled from the training set with replacement (this is an example of bagging, but if you want to use pasting instead, just set boostrup=False).

The n_jobs parameter tells Scikit-Learn the number of CPU cores to use for training and predictions (-1 tells Scikit-Learn to use all available cores):

    from sklearn.ensemble import BaggingClassifier

    from sklearn.tree import DecisionTreeClassifier

    bag_clf = BaggingClassifier(

            DecisionTreeClassifier(), n_estimators=500,

            max_samples=100, boostrap=True, n_job=-1)

    bag_clf.fit(X_train, y_train)

    y_pred = bag_clf.predict(X_test)

The BaggingClassifier automatically performs soft voting instead of hard voting if the base classifier can estimate class probabilities (i.e., if it has a predict_proba() method), which is the case with Decision Trees classifications.

Out-of-Bag Evaluation

Random Patches and Random Subspace

Random Forests

As we have discussed, a Random forest is an ensemble of Decision Trees, generally trained via the bagging method (or sometimes pasting), typically with max_samples set to the size of the training set. 

Instead of building a BaggingClassifier and passing in a DecisionTreeClassifier, you can instead use the RandomForestClassifier class, which is more convenient and optimized for Decision Trees (similarly,there is a RandomForestRegressor class for regression tasks). 

The following code trains a Random Forest classifier with 500 trees (each limited to maximum 16 nodes), using all available CPU cores.

    from sklearn.ensemble import RandomForestClassifier

    rnd_clf = RandonForestClassifier(n_estimators=500, max_leaf_nodes=16, n_jobs=-1)

    rnd_clf.fit(X_train, y_train)

    y_pred_rf = rnd_clf.predict(X_test)

With a few exceptions, a RandomForestClassifier has all the hyperparameters of a DecisionTreeClassifier (to control how trees are grown), plus all the hyperparameters of a BaggingClassifier to control the ensemble itself.

The following BaggingClassifier is roughly equivalent to the previous RandomForestClassifier:

    bag_clf = BaggingClassifier(

          DecisionTreeClassifier(splitter="random", max_leaf_nodes=16),

          n_estimators=500, max_samples=1.0, bootsrap=true, n_jobs=-1)

Extra-Trees

It is hard to tell in advance whether a RandomForestClassifier will perform better or worser than an ExtraTreesClassifier. Generally, the only way to know is to try both and compare them using cross-validation (and tuning the hyperparameters using grid search)

Feature Importance

Yet another quality of Random Forests is that they make it easy to measure the relative importance of each feature. 

Scikit-Learn measures a feature's importance by looking at how much the tree nodes that use that feature reduce impurity on average (across all trees in the forest).

More precisely, it is a weighted average, where each node's weight is equal to the number of training samples that are associated with it (see Chapter 6).

Scikit-Learn computes this score automatically for each feature after training, that it scale the results so that the sum of all importances is equal to 1.

You can access the result using the feature_importances_ variable.

For example, the following code trains a RandomForestClassifier on the iris dataset (introduced in Chapter 4) and outputs each feature's importance.

It seems that tha most important features are the petal length (44%) and width (42%), while sepal length and width are rather unimportant in comparison (11% and 2%, respectively).

    >>> from sklearn.datasets import load_iris

    >>> iris = load_iris()

    >>> rnd_clf = RandomForestClassifier(n_estimators=500, n_jobs=-1)

    >>> rnd_clf.fit(iris["data"], iris["target"])

    >>> for name, score in zip(iris["feature_names"], rnd_clf.feature_importances_):

    >>>      print(name, score)

    >>>

    sepal length (cm) 0.112492250999

    sepal width (cm) 0.0231192882825

    petal length (cm) 0.441030464364

    petal width (cm) 0.423357996355

Similarly, if you train a Random Forest classifier on the MNIST dataset (introduced in Chapter 3) and plot each pixel's importance, you get the image represented in Figure 7-6.

Random Forests are very handy to get a quick understanding of what features actually matter, in particular if you need to perform feature selection.

 

*明日もこの続きで、Boostingまでやってしまおう。

 

つづく

 

f:id:AI_ML_DL:20200211075433p:plain

style=102 iteration=1

f:id:AI_ML_DL:20200211075526p:plain

style=102 iteration=20

f:id:AI_ML_DL:20200211075620p:plain

style=102 iteration=500

 

Quantum-chemical insights from DTNN -6

Quantum-chemical insights from DTNN -6

*KaggleのテーマPredicting Molecular Propertiesと類似した内容であるが、Kaggleとは離れて、DTNNの本質に迫る。

*プログラムコードを学び、使えるようにする。(2月9日追記)

*主要対象論文:K. T. Schütt et al., Quantum-chemical insights from deep tensor neural networks, nature communications 2017、SchNetの論文、K. T. Schüttさんの学位論文他

 

*DTNNとSchNetは、量子力学のDFT(密度汎関数法)によって計算した分子のエネルギーのデータベースによって訓練し、未知の分子のエネルギーを量子力学のDFT計算と同レベルの正確さで予測するプログラムである。

*このDTNNとSchNetの計算の仕組みとプログラムコードを学んでいるところである。

 

*分子のデータベースからは、MD(分子動力学)に関係する分子の力も、正確に予測できるということだが、論文中の、1分子の力の計算とMDの関係性が理解できず、昨日、MDのことを調べることにした。

*その結果、MDが、初期のニュートン力学をベースにしたものから、近似的な量子力学的計算を取り入れたものがあらわれ、さらには、原子分子の量子力学計算の集大成であるDFTをベースにしたab initio MDが登場したということがわかった。

*しかし、ab initio MDは、計算資源の問題から、扱える原子数が少なく時間スケールも短いために現実的な系に適用するのが困難で、限られた使い方しかできない。

*計算資源の問題の根源は、ab initio MD計算に必要な、DFTによる原子分子の力の計算に要する時間にある。

*ここで、機械学習が登場する。

*ab initio MDに必要な、DFTによる原子分子の力の計算を、DFTに変わって行えるように訓練するニューラルネットの1つが、DTNNである。

*H. Wangらは、DTNNのような機能を組み込んだ、ab initio MDとして、DeePMDを開発した。

 

*今日は、このDeePMDについて、もう少し詳しく見ていきたいと思う。

・DeePMD-kit: A deep learning package for many-body potential energy representation and molecular dynamics, H. Wang, L. Zhang, J. Han and W. E, arXiv 31 Dec 2017

ディープラーニングは、量子力学計算の領域で、正確だけど時間がかかる計算と同等の結果を、短時間で得る方法を提供し始めている。

・ここでは、ディープラーニングベースで表現されたポテンシャルエネルギーと力場(force field)を、分子動力学(molecular dynamics)に適用することができる、DeePMD-kitを紹介する。

・LAMMPSやi-PIのような、高機能な古典的MD計算から、量子力学的MD計算まで、種々のMDプログラムとのインターフェースを備えている。

・LAMMPSとi-PIは、GitHubにあることを確認した。オープンソースのコードが増えて有難いこと、この上ない。(やる気と少しのお金があれば、好きなだけ勉強/研究できるのだ)

・DeePMD-kitの全体の構成は、以下の図のようになっている。

・オレンジ色の機械学習で学んだモデルが緑色のMD計算に用いられる。

f:id:AI_ML_DL:20200210111335p:plain

 

*そもそも、古典的なMDとは、どのような計算なのかを勉強してみよう。

・Introduction to molecular dynamics simulations, K. Vollmayr-Lee, arXiv 20 Jan 2020

・代表的なソフトウエアパッケージが、LAMMPSである。

・とりあえず、図を並べておこう。

f:id:AI_ML_DL:20200210160538p:plain

f:id:AI_ML_DL:20200210161240p:plain


f:id:AI_ML_DL:20200210160638p:plain

f:id:AI_ML_DL:20200210161340p:plain

・これでは何の説明にもなっていないが、学生向けに書かれたもので、次のようなPythonで書かれたコードが載っている。

f:id:AI_ML_DL:20200210164321p:plain


*次は、ab initio MDのシミュレーションソフト、i-PIをながめてみよう。

・i-PIは、ab initioに限らず、半経験的パラメータ等を用いた計算も可能である。

・さらに、DeePMD-kitで使われていることからもわかるように、外部からエネルギーと力を入力してMDシミュレーションすることも可能である。それが、下図右上の、EXTERNAL FORCE CODESとして示されている。

 

f:id:AI_ML_DL:20200210221521p:plain

 

*さて、K. T. SchüttさんのDTNN、SchNet、学位論文等からずいぶん離れてしまったようだ。

*DeePMD-kitでは、DTNNやSchNetと同等かそれ以上の性能を持つエネルギーと力の予測性能を持つニューラルネットが使われているので、どうしたものかと悩むところではある。

*Kaggleコンペのテーマであった、スカラーカップリングコンスタントの予測に対しては、DooPMD-kitで使われているニューラルネットとDTNNやSchNetのどちらが優れているかはわからない。

 

*明日は、DTNNから、さらに離れてしまうことになるが、スカラーカップリングコンスタントの予測に用いられていた、機械学習モデル、XGBoost, LightGBM, CatBoostなどを全く知らないので、勉強してみよう。

・そもそも、Gradient Boostもよくわかっていない。

・なので、タイトルを、Machine Learning without DNNに変えて、1回か2回やってから、Quantum-chemical insightに戻ってこよう。


 つづく 

 

f:id:AI_ML_DL:20200210080208p:plain

style=101 iteration=1

f:id:AI_ML_DL:20200210080301p:plain

style=101 iteration=20

f:id:AI_ML_DL:20200210080348p:plain

style=101 iteration=500

*F. CholletさんのDeep Learning with Pythonのテキストを使って、このスペースで、プログラムコードの勉強をしよう。(写経レベル)

・毎回載せている画像の加工に使っているNeural Style transfer in Kerasを使わせていただこう。

Lat's start by defining the paths to the style-reference image and the target imge. To make sure that the processed images are a similar size (widely different sizes make style transfer more difficult), you'll later resize them all to a shared height of 400 px.

Listing 8.14  Defining initial variables

from keras.preprocessing.image import load_img, img_to_array

target_image_path = 'img/portrait.jpg' # path to the image you want to transform

style_reference_image_path = 'img/transfer_style_reference.jpg' # path to the style image

width, height = load_img(target_image_path).size

img_height = 400

img_width = int(width * img_height / height)

 

以上

Quantum-chemical insights from DTNN -5

Quantum-chemical insights from DTNN -5

*KaggleのテーマPredicting Molecular Propertiesと類似した内容であるが、Kaggleとは離れて、DTNNの本質に迫る。

*プログラムコードを学び、使えるようにする。(2月9日追記)

・主要対象論文:K. T. Schütt et al., Quantum-chemical insights from deep tensor neural networks, nature communications 2017、SchNetの論文、K. T. Schüttさんの学位論文他

 

*今日は、Molecular dynamicsのパラメータF(kcal/mol/Å)の予測、Molecular dynamic study of C20 fullereneについて学ぶ。

 

*Molecular dynamicsに関して自分のもつイメージと、1分子に対する力F(kcal/mol/Å)の予測が、どうつながっているのか理解できないので、ゼロから勉強しよう。

 

*定義(ウイキペディアより)

分子動力学(ぶんしどうりきがくほう、molecular dynamics、MD法)は、原子ならびに分子物理的な動きコンピューターシミュレーション手法である。

・原子および分子はある時間の間相互作用することが許され、これによって原子の動的発展の光景が得られる。

・最も一般的なMD法では、原子および分子のトラクジェクトリは、相互作用する粒子の系についての古典力学におけるニュートンの運動方程式数値的に解くことによって決定される。

・この系では粒子間のおよびポテンシャルエネルギー原子間ポテンシャル分子力学力場)によって定義される。

・MD法は元々は1950年代末に理論物理学分野で考え出されたが[1][2]、今日では主に化学物理学材料科学生体分子モデリングに適用されている。

・系の静的、動的安定構造や、動的過程(ダイナミクス)を解析する手法。

*ここまでは、古典力学の世界の話

 

*結合の切断、形成を扱えるMD(ウイキペディアより)

ab-initio法におけるポテンシャル

・古典的分子動力学では、単一のポテンシャルエネルギー表面(通常は基底状態)は力場によって表わされる。

・これはボルン=オッペンハイマー近似の結果である。

励起状態では、化学反応あるいはより正確な表現が必要な時は、電子の振る舞いを密度汎関数法といった量子力学的手法を用いることによって第一原理から得ることができる。

・これはab initio分子動力学(AIMD)と呼ばれる。

・電子の自由度を扱うコストから、このシミュレーションの計算コストは古典的分子動力学よりもかなり高い。

・これはAIMDがより小さな系あるいはより短い時間に制限されることを意味する。

・Ab initio量子力学法は、トラジェクトリ中の配座について必要に応じてその場で系のポテンシャルエネルギーを計算するために使うことができる。

・この計算は反応座標の近傍で大抵行われる。

・様々な近似を使うことができるが、これらは経験的当てはめではなく理論的考察に基づいている。

・Ab-initio計算は、電子状態の密度やその他の電子的性質といった、経験的手法からは得ることのできない膨大な情報を与える。

Ab-initio法を使用する大きな利点は、共有結合の切断あるいは形成を含む反応を調べる能力である。

・これらの現象は複数の電子状態に対応する。

 

ab initio分子動力学(AIMD)の課題は、計算速度だから、機械学習ニューラルネットと組み合わせれば良さそうだな。

*すなわち、AIMD = Ab-initio MD  →  Artificial Inteligence MD

 

*ありますね、Artificial Inteligence MD!

*Free energy of proton transfer at the water - TiO2 interface from ab initio deep potential molecular dynamics, M. F. Calegari Andrade, H-Y. Ko, L. Zhang, R. Car and A. Selloni, Chem. Sci., 2020

f:id:AI_ML_DL:20200209161446p:plain

 

*DeePMD(Deep Potential Molecular Dinamics)と命名された手法の開発者の論文

・Deep Potential Molecular Dynamics: a scalable model eith the accuracy of quantum mechanics, L. Zhang et al., arXiv

・概要:ab initio計算のデータを用いてDNNを学習させ、得られた多体ポテンシャルと原子間力をベースにし、MD法によって分子シミュレーションする手法である。

・ネットワーク以外は、第一原理から計算したものである。

・バルク材料や分子を含む様々な系に、効率的で正確なプロトコルを提供する。

・序文:MDは、物理、化学、生物、材料科学など、さまざまな分野で使われているが、その計算結果の正確性は、計算に用いる原子の相互作用のモデルに依存している。

・ ab initio MDは、密度汎関数法(DFT)の正確さをもつが、計算コストのために数百原子、100 ps程度の範囲に限られる。

・DFTの近似法が種々開発されているが、十分ではない。

機械学習が、この状況を変えつつある。(引用文献10件の中にK. T. SchüttさんらのDTNNが含まれている)

・原子の立体配置とポテンシャルエネルギーと力の大きなデータベースで学習させれば、機械学習は、これらの物理量を同等の正確さで再生することができる。

・これまでの10件の機械学習法は、そのままでは使えないとの判断から、新しいモデルDeep Potential Molecular Dynamics (DeePMD)を提案している。

・理解するのが難しくなったので、模式図を示しておこう。

f:id:AI_ML_DL:20200209230214p:plain

 

*MDAnalysis: A Python Package for the Rapid Analysis of Molecular Dynamics Simulations, R. G. Gowers et al., Proc. of the 15th Python in Science Conf. (SciPy 2016)

・これは、バイオインフォマティクス分野におけるMD計算を想定し、様々なフォーマットのデータベースからの入力に対応し、複数の出力方式に対応したPythonコードの紹介である。2008年1月に公開されたとのこと。

・これは、おそらく、古典的なMD計算であろう。

 

f:id:AI_ML_DL:20200209230848p:plain

 

*今日は、DTNNやSchNetでのMDに関する内容を理解する予定であったが、MDについて調べているうちに、DeePMDというab initio MDと同等の正確さでMD計算を可能にするツールが開発され、水-TiO2系に適用されていることがわかった。

・そのDeePMDは、DeePMD-kitとして、GitHubにアップロードされている。

 

機械学習関係の論文は、ほぼ全て、arXivで読めるので、とにかく、文献検索をして、日々、新しい情報を取り入れるようにしよう!

 

つづく

  

f:id:AI_ML_DL:20200209074105p:plain

style=100 iteration=1

f:id:AI_ML_DL:20200209074200p:plain

style=100 iteration=20

f:id:AI_ML_DL:20200209074247p:plain

style=100 iteration=500

 

Quantum-chemical insights from DTNN -4

+Quantum-chemical insights from DTNN -4

*KaggleのテーマPredicting Molecular Propertiesと類似した内容であるが、Kaggleとは離れて、DTNNの本質に迫る。

・対象論文:K. T. Schütt et al., Quantum-chemical insights from deep tensor neural networks, nature communications 2017

 

*今日は、K. T. Schüttさんの、学位論文:Learning Representations of Atomistic Systems with Deep Neural Networks:によって、DTNNとSchNetを理解していきたいと思う。

 

*Local chemical potential

・分子の等距離表面における、プローブ元素Zpの化学ポテンシャルの分布を示したもので、次の図の左側のネットワークの出力Xpから計算される。

f:id:AI_ML_DL:20200208122211p:plain

・次の図は、プローブ元素をH, C, N, Oと変えた時の、局所化学ポテンシャルである。

f:id:AI_ML_DL:20200208122905p:plain

・元素の種類と原子の空間座標から計算した原子間距離のみを入力し、分子のエネルギー(atomization energy)だけを目的関数としてDTNNで学習させると、分子のエネルギーを正確に予測できるだけでなく、化学結合に関する情報も得られるということが、これまでの方法との大きな違いである。

・結合の不飽和度(炭素で言えば、二重結合か三重結合かなど)や、芳香族性の程度の違いを含む情報が得られており、原著論文では、Fig.1eに示した図(下図)について、C6O3H6(図ではC6C3H6と誤記)分子はベンゼン(C6H6)やトルエン(C6H5CH3)よりも高い芳香族性を示している、と述べている。

 

f:id:AI_ML_DL:20200208140643p:plain

 

 *Chemical compound space

・QM7bとQM9のサブセットを用いたDTNNによるテストデータに対するエネルギーの予測値は、1.0 kcal mol-1と良好であったが、下図に示されるように、20 kcalから40 kcalを超の誤差を示す分子もある。

f:id:AI_ML_DL:20200208161622p:plain

・誤差が大きい分子は、変わった結合をもった分子だから、と表現しているが、納得いかないところもある。類似分子に対する学習量が少なかったということだろうか。

・エネルギーの予測値の誤差が、原子数が多いほど小さくなるという現象がみられている。

・原子数の大きい分子は原子数の小さい分子の学習結果から学ぶのだろうと推測し、実際に原子数の少ない分子を加えたデータでトレーニングすると、誤差が小さくなったとのこと。(下図右上のグラフに示されている)

f:id:AI_ML_DL:20200208161947p:plain

 

*DTNNを理解しようとして、いろいろ調べたが、非常に奥深い、幅広い領域における情報をうまく利用して新しい手法を編み出したのだと思う。

・2000年から2010年頃までのニューラルネットワークに関する研究や機械学習に関する研究成果も多く取り入れられているようだが、とらえきれない部分が殆どだった。

 

*そろそろ、次のテーマ、とも思ったが、ここは、後先考えず、量子化学の世界に、どっぷりつかってみようかな、と思いなおしたところである。

*難しくなって、先に進めなくなると、どうしても、目先を変えたくなるものだ。

 

*明日は、まずは、Molecular dynamicsについて調べてみようと思う。

・ざっと目を通したところでは、インパクトは感じなかったが、SchNetではC20フラーレンを扱っているし、MD計算自体には非常に興味がある。

・炭素原子からダイヤモンド、グラファイトナノチューブフラーレンなどが生成するプロセスを再現できないか、知り合いにMD計算を試してもらったことがあり、できれば自分でやってみたいと思っていたこともある。


つづく 

  

f:id:AI_ML_DL:20200208084717p:plain

style=099 iteration=1

f:id:AI_ML_DL:20200208084812p:plain

style=099 iteration=20

f:id:AI_ML_DL:20200208084852p:plain

style=099 iteration=500

 

Quantum-chemical insights from DTNN -3

Quantum-chemical insights from DTNN -3

*KaggleのテーマPredicting Molecular Propertiesと類似した内容であるが、Kaggleとは離れて、DTNNの本質に迫る。

・対象論文:K. T. Schütt et al., Quantum-chemical insights from deep tensor neural networks, nature communications 2017

 

*今日は、K. T. Schüttらの、ShuNetに関する2件の論文も含めて、DTNNを理解していきたいと思う。

*SchNet: A continuous-filter convolutional neurel network for modeling quantum interactions

*SchNet - a deep learning architecture for molecules and materials

 

*入力データ

・データベースCDB-7やCDB-9から、分子の情報を入力する。このときの1次情報は、構成原子の核電荷と構成元素の3次元座標

・構成元素の核電荷と3次元座標は、核電荷ベクトルZと原子間距離行列Dに変換される。

・核電荷ベクトルZは、次のようにcに変換される。

1. Assign initial atomic descriptors

f:id:AI_ML_DL:20200207083202p:plain

・原子間距離マトリックスDは次のようにdに変換される。

2. Gaussian feature expansion of the inter-atomic distance

f:id:AI_ML_DL:20200207083523p:plain

・さらに、cとdを用いて、原子間相互作用項vが導入される。
3. Perform T interaction passes

f:id:AI_ML_DL:20200207104649p:plain

・とりあえず、次のステップへ。

4. Predict energy contributions

f:id:AI_ML_DL:20200207110055p:plain

・最終ステップ
f:id:AI_ML_DL:20200207112911p:plain

f:id:AI_ML_DL:20200207110323p:plain

・5つのプロセスのうちの3番目のinteraction pass Tの意味がわからない。

 

*K. T. Schüttさんの学位論文があった。2018年5月25日付けである。

*学位論文のタイトル:Learning Representations of Atomistic Systems with Deep Neural Networks

・内容は、DTNNの論文と、2件のSchNetの論文と、2014年のHow to represent crystal structures for machine learning: towards fast prediction of electronic properties., の計4件の論文をまとめたもののようである。

・2014年の論文は、結晶のフェルミエネルギーにおけるDOS(状態密度)を予測するもので、結晶の表現方法に工夫があり、機械学習には、kernel ridge regression (KRR)を用いている。

・Chapter 1:ここでは、シュレーディンガー方程式や密度汎関数などが簡単に紹介されているので、用語に慣れることができる。

・Capter 2:Representing atomistic systems:分子の表現方法として、有機化学分子生物学では化学式(キャラクターのみ)や化学構造式(直線や多角形とキャラクターの組合せ)が用いられるが、量子力学計算による物理化学的な量や物性値との相関が低いので機械学習の入力としては適切ではない。

・Uniqueness, Invariance, Equivariance, Differentiability, Cross-element generalizationなどを考慮する必要があるとのことで、Coulomb matrix, Many-body expansion, Chemical environments, などの項目を立てて議論されているがよくわからなかった。

・Chapter 3 : Deep tensor neural networks(DTNN):いよいよ本題に入ったが、学位論文を読むことで理解が深まるかどうか。

・論文とは違って、学位論文では、Tが強調された図面が2つ掲載されている。

・この2つの図をじっと見ていれば、Tのなんたるかが、少し分かった気になる。

f:id:AI_ML_DL:20200207195525p:plain

 

f:id:AI_ML_DL:20200207193919p:plain

・学位論文は、通常の論文よりも丁寧に説明されているし、文字も大きいので読みやすい。

 

*明日は、DTNNの計算の結果として得られている、Local chemical potential、の意味や、どのようにして得られるのかを理解しようと思う。

*その後で、SchNetについても学ぼうと思う。

f:id:AI_ML_DL:20200207223401p:plain

 

つづく 

 

f:id:AI_ML_DL:20200207080819p:plain

style=098 iteration=1

f:id:AI_ML_DL:20200207080935p:plain

style=098 iteration=20

f:id:AI_ML_DL:20200207081026p:plain

style=098 iteration=500