/
PCA_Classify5_CG.py
290 lines (191 loc) · 8.73 KB
/
PCA_Classify5_CG.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
"""
=====================================
Visualization of MLP weights on MNIST
=====================================
Sometimes looking at the learned coefficients of a neural network can provide
insight into the learning behavior. For example if weights look unstructured,
maybe some were not used at all, or if very large coefficients exist, maybe
regularization was too low or the learning rate too high.
This example shows how to plot some of the first layer weights in a
MLPClassifier trained on the MNIST dataset.
The input data consists of 28x28 pixel handwritten digits, leading to 784
features in the dataset. Therefore the first layer weight matrix have the shape
(784, hidden_layer_sizes[0]). We can therefore visualize a single column of
the weight matrix as a 28x28 pixel image.
To make the example run faster, we use very few hidden units, and train only
for a very short time. Training longer would result in weights with a much
smoother spatial appearance.
"""
print(__doc__)
import matplotlib.pyplot as plt
from sklearn.datasets import fetch_mldata
from sklearn.neural_network import MLPClassifier
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import mean_squared_error
from sklearn.metrics import log_loss
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_squared_error
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.decomposition import FastICA
from sklearn.decomposition import FactorAnalysis
from sklearn.manifold import Isomap
import umap
import numpy as np
import cv2
import glob
import time
import math
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.preprocessing import MinMaxScaler
import matplotlib.cm as cm
from sklearn.model_selection import train_test_split
import xlsxwriter
import pandas as pd
plt.close("all")
#mnist = fetch_mldata("MNIST original")
#img = cv2.imread('honolulu-airport.jpg',0)
#images = [ np.reshape( np.reshape (cv2.imread(file, 0)/255 , 394*1200) ,(1200,394)) for file in glob.glob("*.jpg")]
#plt.figure(1)
#plt.imshow(images[0], cmap = 'gray', interpolation = 'bicubic')
#plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
#plt.show()
#wx , wy =25, 25
Nhid1, Nhid2=500,500
#I = plt.imread("./Input/OPCarray_InputMask/1.png")
#plt.imshow(I)
# read Input mask images
images = [ plt.imread(file) for file in sorted(glob.glob("./Input/OPCarray_InputMask/*.png") )]
#plt.imshow(images[1])
#plt.pause(1)
#images = [ cv2.resize(cv2.imread(file, 0) , (
# int(wx),int(wy) ) ) for file in glob.glob("./Input/OPCarray_InputMask/*.tif")]
EntireImageSizexi=600
EntireImageSizeyi=400
EntireImageSizexo=65
EntireImageSizeyo=38
for idx in enumerate(images):
#resizing images, mainly downsampling
images[idx[0]]= np.round (cv2.resize(images[idx[0]],(EntireImageSizexi,EntireImageSizeyi)))
#Padding input images to larger size
#images[idx[0]]=np.pad(images[idx[0]], ((50,50),(50,50)),
# 'constant', constant_values=((0,0), (0,0)) )
#images=cv2.resize(images,(50,50))
# read binarized SEM images
images2 = [ plt.imread(file) for file in sorted( glob.glob("./Output/etched/OPCArray/DRIE_shallow_SiSubs/*.png") )]
for idx in enumerate(images2):
images2[idx[0]]=np.round ( cv2.resize(images2[idx[0]],(EntireImageSizexo,EntireImageSizeyo)) )
#plt.imshow(images2[1])
#plt.pause(1)
for ii in range(len(images)):
images[ii]= np.reshape (images[ii] , EntireImageSizexi*EntireImageSizeyi )
for ii in range(len(images2)):
images2[ii]= np.reshape (images2[ii] , EntireImageSizexo*EntireImageSizeyo)
subimages=np.asarray(images)
subimages2=np.asarray(images2)
split=45
X, y = np.float64(subimages) , np.float64(subimages2)
del subimages, subimages2
#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42)
X_train, X_test = X[:split], X[split:]
y_train, y_test = y[:split], y[split:]
pca1=PCA(n_components=2,svd_solver = 'auto', random_state=1)
ica1=FastICA(n_components=20, random_state=1)
tsne1 = TSNE(n_components=2,random_state=1,method='exact' )
fa1=FactorAnalysis(n_components=5, random_state=1)
embedding = Isomap(n_components=20)
reducer = umap.UMAP(n_components=30, random_state=1)
#X_train_t =pca1.fit_transform(X_train)
#X_train_t =ica1.fit_transform(X_train)
#X_train_t = fa1.fit_transform(X_train)
#X_train_t=tsne1.fit_transform(X_train)
#X_train_t=embedding.fit_transform(X_train)
#X_train_t =reducer.fit_transform(X_train)
sc1=MinMaxScaler()
#X_train_t =sc1.fit_transform(X_train_t)
X_train_t=X_train
## convert your array into a dataframe
df = pd.DataFrame (X_train)
## save to xlsx file
filepath = 'my_excel_file.xlsx'
df.to_excel(filepath, index=False)
#X_test_t= =pca1.transform(X_test)
#X_test_t=ica1.transform(X_test)
#X_test_t= fa1.transform(X_test)
#X_test_t=embedding.transform(X_test)
#X_test_t=reducer.transform(X_test)
#X_test_t=sc1.transform(X_test_t)
X_test_t=X_test
plt.figure(1)
plt.scatter(X_train_t[:,0], X_train_t[:,1] )
plt.scatter(X_test_t[:,0], X_test_t[:,1],marker='^', c='g' )
start = time. time()
# mlp = MLPClassifier(hidden_layer_sizes=(100, 100), max_iter=400, alpha=1e-4,
# solver='sgd', verbose=10, tol=1e-4, random_state=1)
mlp = MLPClassifier(hidden_layer_sizes=(Nhid1,Nhid2 ), activation='relu', solver='adam', alpha=0.0001,
batch_size='auto', learning_rate='constant', learning_rate_init=1e-3,
power_t=0.5, max_iter=20000, shuffle=True, random_state=1, tol=1e-4,
verbose=True, warm_start=False, momentum=0.9, nesterovs_momentum=True,
early_stopping=False, validation_fraction=0.1, beta_1=0.9, beta_2=0.999,
epsilon=1e-08, n_iter_no_change=10)
#mlp= MLPRegressor(hidden_layer_sizes=(Nhid1,Nhid2), activation='relu', solver='adam', alpha=0.001,batch_size='auto',
# learning_rate='constant', learning_rate_init=1e-4, power_t=0.5, max_iter=100000, shuffle=True,
# random_state=None, tol=1e-6, verbose=True, warm_start=False, momentum=0.9,
# nesterovs_momentum=True, early_stopping=False, validation_fraction=0.1, beta_1=0.9, beta_2=0.999,
# epsilon=1e-08)
mlp.fit(X_train_t, y_train)
ytrain_pred=mlp.predict(X_train_t)
ytest_pred=mlp.predict(X_test_t)
end = time. time()
print('execuation time is %f' % (end - start))
print("Training set score: %f" % mlp.score(X_train_t, y_train))
print("Test set score: %f" % mlp.score(X_test_t, y_test))
print('log loss')
#print (log_loss(y_test, mlp.predict_proba(X_test) ) )
print('accuracy score')
#print (accuracy_score(y_test, ytest_pred ) )
print('mean squared error in training set')
print (mean_squared_error(y_train, ytrain_pred ) )
print('mean squared error in test set')
print (mean_squared_error(y_test, ytest_pred ) )
#X_train =sc1.inverse_transform(X_train_t)
#X_train=tsne1.inverse_transform(X_train_t)
#X_test =sc1.inverse_transform(X_test_t)
#X_test=tsne1.inverse_transform(X_test_t)
y_train=np.reshape(y_train , (split, EntireImageSizeyo,EntireImageSizexo))
ytrain_pred=np.reshape(ytrain_pred , (split,EntireImageSizeyo,EntireImageSizexo))
y_test=np.reshape(y_test , (len(images)-split,EntireImageSizeyo,EntireImageSizexo))
ytest_pred=np.reshape(ytest_pred , (len(images)-split,EntireImageSizeyo,EntireImageSizexo))
#save real images---in case of random train test split, no ordering is required
#since order already lost
lll=[str(kk) for kk in range(1,51)]
lll=sorted(lll)
for hh in range(0,45):
plt.imsave('./output/etched/OPCArray/Temp1_real/train/'+ lll[hh]+'.png', y_train[hh],cmap=cm.gray)
for hh in range(0,5):
plt.imsave('./output/etched/OPCArray/Temp1_real/test/'+ lll[hh+45]+'.png', y_test[hh],cmap=cm.gray)
# save preidcted images
lll=[str(kk) for kk in range(1,51)]
lll=sorted(lll)
for hh in range(0,45):
plt.imsave('./output/etched/OPCArray/Temp2/train/'+ lll[hh]+'.png', ytrain_pred[hh],cmap=cm.gray)
for hh in range(0,5):
plt.imsave('./output/etched/OPCArray/Temp2/test/'+ lll[hh+45]+'.png', ytest_pred[hh],cmap=cm.gray)
plt.figure(2)
plt.imshow(np.uint8(ytrain_pred[2]), cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
plt.figure(3)
plt.imshow(np.uint8(y_train[2]), cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
#import sys
#sys.exit("Error message")
plt.figure(4)
plt.imshow(np.uint8(ytest_pred[3]), cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
plt.figure(5)
plt.imshow(np.uint8(y_test[3]), cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()