Guest User

Untitled

a guest
Jul 20th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.04 KB | None | 0 0
  1. import vdemsinversioncode as vdemi
  2. import numpy as np
  3. from keras.models import Sequential
  4. from keras.layers import Dense
  5. from keras.layers import Dropout
  6. from keras.layers import BatchNormalization
  7. from math import fabs
  8.  
  9.  
  10. def prepareVdem(vdm, path):
  11. vdm.load_all_pkl(path)
  12. vdm.set_deltax(deltax=27, offsetx=0)
  13. vdm.truevdemraster(iw=[0, 1, 2, 3])
  14. vdm.set_deltax(deltax=27, offsetx=0)
  15. vdm.rastersyn(iw=[0, 1, 2, 3])
  16.  
  17. vdemr1=vdemi.vdemsinversioncode()
  18. # vdemr2=vdemi.vdemsinversioncode()
  19. vdemr3=vdemi.vdemsinversioncode()
  20. vdemr4=vdemi.vdemsinversioncode()
  21.  
  22. prepareVdem(vdemr1, "data/vdem_cuda_revvel_raster_incl193_tg=4.7-7.5_0.2_vel=400_10.0_it=2_woNNature.opy")
  23. # prepareVdem(vdemr2, "data/vdeminv_seppix79.6000_incl193_1he_400_15_temp=4.7-7.5-0.2_woNViggohcv2.opy")
  24. prepareVdem(vdemr3, "data/vdeminv_seppix79.6000_incl193_1he_400_15_temp=4.7-7.5-0.2_woNViggoen024.opy")
  25. prepareVdem(vdemr4, "data/vdem_cuda_revvel_denser_raster_incl193_tg=4.7-7.5_0.2_vel=400_20.0_it=2_woN.opy")
  26.  
  27. ###-----------Edit this-------------###
  28. ###---------------------------------###
  29. test_number = 6
  30. ###---------------------------------###
  31. ###---------------------------------###
  32.  
  33. #%% Format the data
  34.  
  35. print(np.max(vdemr1.rassyn_arr[1][0, :, :]))
  36.  
  37.  
  38. #%% Format the data
  39. from sklearn import preprocessing
  40. from sklearn.decomposition import PCA
  41. from sklearn.externals import joblib
  42.  
  43.  
  44. def get_x_train(vdm):
  45. for i in range(0, vdm.rassyn_arr[0].shape[0]):
  46. if (i == 0):
  47. tmp_x_train = np.vstack((np.vstack((vdm.rassyn_arr[0][0, :, :], vdm.rassyn_arr[1][0, :, :])),
  48. vdm.rassyn_arr[3][0, :, :])) # Not the index 2 for rassyn_arr
  49. print("tmp_x_train = {}".format(tmp_x_train.shape))
  50. else:
  51. to_be_stacked = np.vstack((np.vstack((vdm.rassyn_arr[0][i, :, :], vdm.rassyn_arr[1][i, :, :])),
  52. vdm.rassyn_arr[3][i, :, :])) # Not the index 2 for rassyn_arr
  53. tmp_x_train = np.hstack((tmp_x_train, to_be_stacked))
  54. return np.swapaxes(tmp_x_train, 0, 1)
  55.  
  56. def get_y_train(vdm):
  57. factor = int(vdm.vdemraster_arr.shape[
  58. 2] / 35) # This is the number of steps taken by the raster. For example the raster can take 7 steps, then every 7th value belong together.
  59. # So we should look at every xth value where x is the factor.
  60. for i in range(0, factor):
  61. if (i == 0):
  62. tmp_y_train = reshapeYArray(vdm.vdemraster_arr[:, :, 0::factor, :]).reshape(-1, vdm.vdemraster_arr[:, :,0::factor, :].shape[-1])
  63. else:
  64. reshaped_y_train = reshapeYArray(vdm.vdemraster_arr[:, :, i::factor, :]).reshape(-1, vdm.vdemraster_arr[:, :, i::factor, :].shape[-1])
  65. tmp_y_train = np.hstack((tmp_y_train, reshaped_y_train))
  66. return np.swapaxes(tmp_y_train,0,1)
  67.  
  68. def reshapeYArray(yArr):
  69. shape = yArr.shape
  70. factor = int(shape[1]/20) # The number of bins to combine into one. For example with shape[1] = 41, factor = 2. With shape[2] = 81, factor = 4
  71. reformatedArr = np.zeros((shape[0], int(shape[1]/factor), shape[2], shape[3]))
  72. for y in range(0, int(np.shape(yArr)[1] / factor)):
  73. combinedYarrValue = yArr[:, y * factor, :, :]
  74. for l in range (1, factor):
  75. combinedYarrValue += yArr[:, y * factor + l, :, :]
  76. reformatedArr[:, y, :, :] = combinedYarrValue
  77. return reformatedArr
  78.  
  79.  
  80.  
  81. x_unfitted1 = get_x_train(vdemr1)
  82. x_unfitted3 = get_x_train(vdemr3)
  83. x_unfitted4 = get_x_train(vdemr4)
  84. x_unfitted = np.vstack((np.vstack((x_unfitted1, x_unfitted3)),x_unfitted4))
  85.  
  86. print("x_unfitted.shape = {} x_unfitted1 = {}, x_unfitted3 = {}, x_uniftted4 = {} ".format(x_unfitted.shape, x_unfitted1.shape, x_unfitted3.shape, x_unfitted4.shape))
  87. inputScaler = preprocessing.StandardScaler()
  88. x = inputScaler.fit(x_unfitted).transform(x_unfitted)
  89.  
  90. x_train = x[0:int(x.shape[0]*0.8),:]
  91. x_test = x[int(x.shape[0]*0.8):-1,:]
  92.  
  93.  
  94. y_unfitted1 = get_y_train(vdemr1)
  95. y_unfitted3 = get_y_train(vdemr3)
  96. y_unfitted4 = get_y_train(vdemr4)
  97. y_unfitted = np.vstack((np.vstack((y_unfitted1,y_unfitted3)),y_unfitted4))
  98. print("y_unfitted.shape = {} y_unfitted1 = {}, y_uniftted3 = {}, y_unfitted4 = {}".format(y_unfitted.shape, y_unfitted1.shape, y_unfitted3.shape, y_unfitted4.shape))
  99.  
  100. #Reduce the number of dimensions with PCA:
  101.  
  102. # pca = joblib.load("/Users/lars/Python/muse/tests/test6/pca.save")
  103. # pca = PCA(0.99)
  104. # pca.fit(y_unfitted)
  105. # y_dim_reduced = pca.transform(y_unfitted)
  106.  
  107. y_dim_reduced = y_unfitted
  108.  
  109. outputScaler = preprocessing.StandardScaler()
  110. y = outputScaler.fit(y_dim_reduced).transform(y_dim_reduced)
  111.  
  112. joblib.dump(outputScaler, "tests/test{}/outputScaler.save".format(test_number))
  113. # joblib.dump(pca, "tests/test{}/pca.save".format(test_number))
  114.  
  115.  
  116. y_train = y[0:int(x.shape[0]*0.8),:]
  117. y_test = y[int(y.shape[0]*0.8):-1,:]
  118.  
  119. #%% Get correct dimentions for array
  120.  
  121.  
  122. print("The shape is: {}".format(get_y_train(vdemr1).shape))
  123.  
  124. #%% Train the network
  125.  
  126. clf = Sequential()
  127. x_train_dim = x_train.shape[1]
  128. y_train_dim = y_train.shape[1]
  129.  
  130. print("xtraindim = {}, ytraindim = {}".format(x_train_dim, y_train_dim))
  131.  
  132. clf.add(Dense(x_train_dim, input_dim=x_train_dim, activation='relu'))
  133. clf.add(Dense(int((x_train_dim+y_train_dim) / 1.3 ), activation='relu'))
  134. clf.add(Dropout(0.4))
  135. clf.add(Dense(int((x_train_dim+y_train_dim) / 1.5), activation='relu'))
  136. clf.add(BatchNormalization())
  137. # clf.add(Dropout(0.2))
  138. clf.add(Dense(int((x_train_dim+y_train_dim) / 1.8), activation='tanh'))
  139. clf.add(BatchNormalization())
  140. # clf.add(Dropout(0.4))
  141. clf.add(Dense(int((x_train_dim+y_train_dim) / 2), activation='tanh'))
  142. # clf.add(BatchNormalization())
  143. # clf.add(Dropout(0.4))
  144. clf.add(Dense(y_train_dim))
  145.  
  146. # Compile model
  147. clf.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
  148.  
  149. clf.fit(x_train, y_train, epochs=300, batch_size=100, shuffle=True, validation_data=(x_test,y_test))
  150. clf.save('tests/test{}/graph.h5'.format(test_number))
  151.  
  152. #%% Predict using the model
  153. import matplotlib.pyplot as plt
  154. from matplotlib import colors
  155.  
  156.  
  157.  
  158. def mean_absolute_percentage_error(actual, predict):
  159. tmp, n = 0.0, 0
  160. for i in range(0, len(actual)):
  161. for l in range(len(actual[i])):
  162. if actual[i][l] != 0:
  163. diff = fabs(fabs(actual[i][l]-predict[i][l])/actual[i][l])
  164. tmp += diff
  165. n += 1
  166.  
  167. return (tmp/n)
  168.  
  169.  
  170. from keras.models import load_model
  171. savedModel = load_model('/Users/lars/Python/muse/tests/test5/graphWith20veltest5')
  172. predictedYs = savedModel.predict(x_test)
  173. print("PredictedYs = {}".format(predictedYs.shape))
  174. # y_test_scaled = outputScaler.inverse_transform(y_test)
  175. # scaledpredictedYs = outputScaler.inverse_transform(predictedYs)
  176. # y_test_scaled = outputScaler.inverse_transform(y_test)
  177. # y_predict_scaled = outputScaler.inverse_transform(predictedYs)
  178.  
  179. # y_test_original = pca.inverse_transform(y_test_scaled)
  180. # y_predict_original = pca.inverse_transform(y_predict_scaled)
  181.  
  182. y_test_original = y_test
  183. y_predict_original = predictedYs
  184.  
  185. y_test_scaled_real_dim = np.swapaxes(y_test_original,0,1)
  186. y_test_scaled_real_dim = y_test_scaled_real_dim.reshape((15,20,35,1705))
  187.  
  188.  
  189. y_predict_scaled_real_dim = np.swapaxes(y_predict_original,0,1)
  190. y_predict_scaled_real_dim = y_predict_scaled_real_dim.reshape((15,20,35,1705))
  191.  
  192. print("The dim = {}".format(y_predict_scaled_real_dim.shape))
  193.  
  194.  
  195. plt.title("Test {}".format(5))
  196. plt.xlabel("Real values")
  197. plt.ylabel("Predicted values")
  198.  
  199.  
  200.  
  201. plt.plot(y_test_original, y_predict_original, 'ro', markersize=1)
  202. plt.axis([np.min(y_test_original), np.max(y_test_original), np.min(y_predict_original), np.max(y_predict_original)])
  203. # print("Keras score = {}".format(savedModel.evaluate(x_test, y_test)))
  204. plt.show()
  205. #%% show 2D plot
  206.  
  207. print(y_test_scaled_real_dim[0][15][15][1700])
  208.  
  209.  
  210. #%% show 2D plot
  211. plt.axis([np.min(y_test_scaled), 1e31, np.min([y_predict_scaled]), 1e31])
  212. plt.show()
  213.  
  214. #%% show 2D plot
  215. # print(predictedYs[0].shape)
  216. plt.hist2d(y_test.ravel(),predictedYs.ravel(), bins=60,cmap='gnuplot2',
  217. range=[[y_test.min(),y_test.max()],[predictedYs.min(),predictedYs.max()]],normed=True,norm = colors.LogNorm())
  218. plt.title("Test 6")
  219. plt.xlabel('Real y')
  220. plt.ylabel('predicted y')
  221. plt.colorbar(label='Probability Density')
  222. plt.show()
  223. # babs_weighted_error = np.average(np.abs(Y_test-Y_testread_synlines_pred)*babs_test.reshape(shape_test[0]*shape_test[1]))/np.average(babs_test.reshape(shape_test[0]*shape_test[1]))
  224. # error = np.average(np.abs(Y_test-Y_test_pred))
  225. # print("Mean error (L1):", error, ". |B|-weighted mean error (L1): ",babs_weighted_error)
  226.  
  227. #%% Print the data
  228.  
  229.  
  230. print(y_predict_scaled_real_dim[:, :, 15, 15])
  231.  
  232.  
  233.  
  234. #%% Plot observations as images to compare
  235. import numpy as np
  236. import matplotlib.pyplot as plt
  237. import matplotlib.colors as colors
  238. from matplotlib.mlab import bivariate_normal
  239. import matplotlib.animation as animation
  240. from matplotlib.pyplot import savefig
  241.  
  242.  
  243. # for sample in range (0, 10):
  244.  
  245. sample = 15
  246.  
  247. # for sample in range (0, y_unfitted.shape[1]):
  248. print("Going to {}".format(y_unfitted.shape[1]))
  249. print(y_unfitted.shape)
  250. print(y_test_scaled_real_dim.shape)
  251. y_test_scaled_for_plot = np.swapaxes(y_unfitted[int(y_unfitted.shape[0]*0.8):-1,:],0,1).reshape((15,20,35,1705))
  252.  
  253. y_test_to_plot = y_test_scaled_for_plot[:, :, 15, sample]
  254. y_predict_to_plot = y_predict_scaled_real_dim[:, :, 15, sample]
  255.  
  256.  
  257. if (np.min(y_test_to_plot) < np.min(y_predict_to_plot)):
  258. plt_min = np.min(y_test_to_plot)
  259. else:
  260. plt_min = np.min(y_predict_to_plot)
  261.  
  262. if(np.max(y_test_to_plot) > np.max(y_predict_to_plot)):
  263. plt_max = np.max(y_test_to_plot)
  264. else:
  265. plt_max = np.max(y_predict_to_plot)
  266.  
  267.  
  268. fig, ax = plt.subplots(2, 1)
  269. pcm = ax[0].pcolormesh(y_test_to_plot,
  270. norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
  271. vmin=plt_min, vmax=plt_max), cmap='RdBu_r')
  272. pcm2 = ax[1].pcolormesh(y_predict_to_plot,
  273. norm=colors.SymLogNorm(linthresh=0.03, linscale=0.03,
  274. vmin=plt_min, vmax=plt_max), cmap='RdBu_r')
  275.  
  276. fig.colorbar(pcm, ax=ax[0], extend='both')
  277. fig.colorbar(pcm2, ax=ax[1], extend='both')
  278.  
  279. # savefig("tests/test{}/moviePngs/pn{}.png".format(test_number, sample))
  280.  
  281. # cax = plt.axes([0.95, 0.1, 0.075, 0.8])
  282. # plt.colorbar(cax=cax)
  283. plt.show()
  284.  
  285. # savedModel.evaluate(X_test, Y_predict)
  286. #%% Look at correlation with intensity
  287. from keras.models import load_model
  288. from matplotlib import colors
  289. import matplotlib.pyplot as plt
  290.  
  291. def doPlot(y_test, y_predict, title, xMax = None, yMax = None):
  292. plt.plot(y_test, y_predict, 'ro', markersize=1)
  293. if (xMax is None): xMax = np.max(y_test)
  294. if (yMax is None): yMax = np.max(y_predict)
  295. plt.axis([np.min(y_test), 1e33, np.min(y_predict), 1e33])
  296. plt.xlabel("Real intensity")
  297. plt.ylabel("Predicted intensity")
  298. plt.title(title)
  299. plt.show()
  300. plt.savefig('figures/'+title+".png")
  301.  
  302. def do2dPlot(y_test, y_predict, title, xMax = None, yMax = None):
  303.  
  304. plt.hist2d(y_test.ravel(), y_predict.ravel(), bins=60, cmap='gnuplot2',
  305. range=[[y_test.min(), 1e33], [y_predict.min(), 1e33]], normed=True,
  306. norm=colors.LogNorm())
  307. plt.title(title)
  308. plt.xlabel("Real intensity")
  309. plt.ylabel("Predicted intensity")
  310. plt.colorbar(label='Probability Density')
  311. plt.show()
  312. plt.savefig('figures/' + title + ".png")
  313.  
  314. print("xtest = {}, ytest = {}".format(x_test.shape, y_test.shape))
  315. vdemr1.read_synlines()
  316.  
  317. savedModel = load_model('/Users/lars/Python/muse/graphs/graphWith20veltest6')
  318. # x_test = np.swapaxes(vdemr1.rassyn_arr[0][0], 0,1)
  319. y_predict = outputScaler.inverse_transform(savedModel.predict(x_test))
  320. y_predict_scaled = np.swapaxes(y_predict,0,1)
  321. y_predict_scaled = y_predict.reshape((15,20,35,1705))
  322.  
  323. print("Evaluation = {}".format(savedModel.evaluate(x_test, y_test)))
  324.  
  325. print("y_test shape = {}".format(y_test.shape))
  326. print("y_predict shape = {}".format(y_predict.shape))
  327.  
  328. print("predict max = {}, test max = {}".format(np.max(y_predict), np.max(y_test)))
  329. scaled_y_test = np.swapaxes(outputScaler.inverse_transform(y_test),0,1).reshape(15,20,35,1705)
  330. vdemr1.calc_moments_vdemsol_arr(scaled_y_test)
  331. y_intens_test1 = vdemr1.synprofsol[0]['intens']
  332. y_intens_test2 = vdemr1.synprofsol[1]['intens']
  333. y_intens_test3 = vdemr1.synprofsol[2]['intens']
  334.  
  335. # scaled_y_predict = outputScaler.inverse_transform(y_predict_scaled)
  336. vdemr1.calc_moments_vdemsol_arr(y_predict_scaled)
  337. y_intens_predict1 = vdemr1.synprofsol[0]['intens']
  338. y_intens_predict2 = vdemr1.synprofsol[1]['intens']
  339. y_intens_predict3 = vdemr1.synprofsol[2]['intens']
  340.  
  341. print("y_intens_test1 {}".format(y_intens_test1.shape))
  342.  
  343. doPlot(y_intens_test1, y_intens_predict1, "Predicted vs real intensity (fe_19_108.355), test5")
  344. doPlot(y_intens_test2, y_intens_predict2, "Predicted vs real intensity (fe_15_284.163), test5")
  345. doPlot(y_intens_test3, y_intens_predict3, "Predicted vs real intensity (fe_9_171.073), test5")
  346.  
  347. do2dPlot(y_intens_test1, y_intens_predict1, "Predicted vs real intensity (fe_19_108.355), test5")
  348. do2dPlot(y_intens_test2, y_intens_predict2, "Predicted vs real intensity (fe_15_284.163), test5")
  349. do2dPlot(y_intens_test3, y_intens_predict3, "Predicted vs real intensity (fe_9_171.073), test5")
  350.  
  351. # synteticVdm = vdemr.vdemsol_arr[str([0, 1, 2, 3])]
  352. #
  353. # vdemr.calc_moments_vdemsol_arr(synteticVdm)
  354. # print(vdemr.synprofsol[0]['intens'].shape)
Add Comment
Please, Sign In to add comment