-
Notifications
You must be signed in to change notification settings - Fork 0
/
generatesysnthetic_cnn.py
188 lines (142 loc) · 6.95 KB
/
generatesysnthetic_cnn.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
# -*- coding: utf-8 -*-
"""GenerateSysnthetic_CNN.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/12wWOBuRT0No4fUASX00aAhTXIAwCRT-E
"""
from google.colab import drive
drive.mount('/content/drive')
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras import regularizers
import random
from sklearn.metrics import r2_score, mean_squared_error
import matplotlib.pyplot as plt
from tensorflow.keras.layers import Conv1D, Dropout, Flatten, Dense, AveragePooling1D
from tensorflow.keras.initializers import GlorotUniform
np.random.seed(56)
random.seed(56)
tf.random.set_seed(56)
# Function to generate a spectrum as a sum of Gaussians
def generate_spectru_gaussians(amplitudes, centers):
widthG = 18
x_range = np.arange(2000, 2299.8, 0.2)
return np.sum([amplitudes[i] * np.exp(-(x_range - centers[i])**2 / widthG) for i in range(len(centers))], axis=0)
# Function to generate multiple spectra as a sum of Gaussians
def generate_multiple_spectra(amplitudes, centers):
widthG = 18
x_range = np.arange(2300, 2000, -0.2) # Generating inverse values
# Initialize empty lists for frequencies and intensity ratios
all_frequencies = []
all_intensity_ratios = []
all_spectra = []
for i in range(len(centers)):
if centers[i] == 2176:
intensity_ratios = [5, 2, 1]
frequencies = [2176, 2168, 2147]
elif centers[i] == 2168:
intensity_ratios = [3, 1]
frequencies = [2168, 2147]
else:
intensity_ratios = [1]
frequencies = [list(specificFrequencies.keys())[i]]
all_frequencies.append(frequencies)
all_intensity_ratios.append(intensity_ratios)
spectrum = np.sum([amplitudes[i] * np.exp(-(x_range - frequencies[j])**2 / widthG) * intensity_ratios[j] for j in range(len(frequencies))], axis=0)
all_spectra.append(spectrum)
final_spectrum = np.sum(all_spectra, axis=0)
return final_spectrum, all_frequencies, all_intensity_ratios
# Define specific frequencies and corresponding classes/labels
specificFrequencies = {
2175: 'CeO2(110)red',
2170: 'CeO2(110)ox',
2176: 'CeO2(100)ox',
2168: 'CeO2(100)red',
2162: 'CeO2(111)red',
2154: 'CeO2(111)ox'
}
# Generate amplitudes for spectra data
num_amplitudes = 6
num_spectra = 2500
# Generate spectra data with corresponding amplitude vectors
spectraDataAmplitudesList = []
for _ in range(num_spectra):
amplitudes = np.random.rand(num_amplitudes)
spectrum, _, _ = generate_multiple_spectra(amplitudes, list(specificFrequencies.keys()))
spectraDataAmplitudesList.append((spectrum, amplitudes))
spectrum = generate_spectru_gaussians(amplitudes, list(specificFrequencies.keys()))
spectraDataAmplitudesList.append((spectrum, amplitudes))
# Split the data into spectra and amplitudes
spectraData = np.array([data[0] for data in spectraDataAmplitudesList])
amplitudesData = np.array([data[1] for data in spectraDataAmplitudesList])
num_samples, points_per_spectrum = spectraData.shape
num_specific_frequencies = 6
spectraData = np.reshape(spectraData, (num_samples, points_per_spectrum // num_specific_frequencies, num_specific_frequencies))
hidden_layer_structure = (91, 96)
regularization_parameter = 0.0001
# ... [Previous code remains unchanged]
# Define the input shape based on spectraData's shape
input_shape = spectraData.shape[1:] # Use the shape of spectraData excluding the first dimension (number of samples)
model = Sequential()
# Feature Extraction Part
# Three parallel 1D convolutional layers
for kernel_size in [5, 10, 15]:
model.add(Conv1D(12, kernel_size, strides=1, activation='relu', input_shape=input_shape, kernel_regularizer=regularizers.l1(regularization_parameter)))
# model.add(Dropout(0.2))
# Concatenate the outputs of the parallel layers
# Add additional 1D convolutional layers
model.add(Conv1D(12, 15, strides=1, activation='relu', kernel_regularizer=regularizers.l1(regularization_parameter)))
# model.add(Dropout(0.2))
model.add(Conv1D(12, 15, strides=1, activation='relu', kernel_regularizer=regularizers.l1(regularization_parameter)))
# model.add(Dropout(0.2))
# Average Pooling
model.add(AveragePooling1D(pool_size=2, strides=2))
# Flatten the output
model.add(Flatten())
# Quantification Stage
# Fully Connected Layers
model.add(Dense(4000, activation='relu', kernel_regularizer=regularizers.l1(regularization_parameter)))
model.add(Dense(num_specific_frequencies, activation='relu', kernel_regularizer=regularizers.l1(regularization_parameter))) # Assuming num_specific_frequencies is the number of chemical species
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error') # Adjust the loss function as needed
# Train the model
history = model.fit(spectraData, amplitudesData, epochs=50)
# ... [Remaining code remains unchanged]
model.save('/content/drive/MyDrive/Research/Spectroscopy/IR_Spectrum_Predcition/CNN_Model2.h5')
# ... [Previous code remains unchanged]
num_new_spectra = 1000
new_spectra_data_amplitudes_list = []
for _ in range(num_new_spectra):
amplitudes = np.random.rand(num_amplitudes)
spectrum, _, _ = generate_multiple_spectra(amplitudes, list(specificFrequencies.keys()))
new_spectra_data_amplitudes_list.append((spectrum, amplitudes))
spectrum = generate_spectru_gaussians(amplitudes, list(specificFrequencies.keys()))
new_spectra_data_amplitudes_list.append((spectrum, amplitudes))
# Split the new data into spectra and amplitudes
new_spectra_data = np.array([data[0] for data in new_spectra_data_amplitudes_list])
new_amplitudes_data = np.array([data[1] for data in new_spectra_data_amplitudes_list])
num_samples_new, points_per_spectrum_new = new_spectra_data.shape
new_spectra_data = np.reshape(new_spectra_data, (num_samples_new, points_per_spectrum_new // num_specific_frequencies, num_specific_frequencies))
# Predict amplitudes for the new spectra
predicted_amplitudes_new = model.predict(new_spectra_data)
# Calculate RMSE and R2 for each facet
for i, frequency in enumerate(specificFrequencies.keys()):
actual_amplitudes = new_amplitudes_data[:, i]
predicted_amplitudes = predicted_amplitudes_new[:, i]
# Calculate RMSE
rmse = np.sqrt(mean_squared_error(actual_amplitudes, predicted_amplitudes))
# Calculate R2 score
r2 = r2_score(actual_amplitudes, predicted_amplitudes)
# Create a new plot for each facet
plt.figure(figsize=(8, 6))
plt.scatter(actual_amplitudes, predicted_amplitudes, s=10)
plt.title(f"Actual vs Predicted for Frequency {frequency}")
plt.xlabel("Actual Amplitudes")
plt.ylabel("Predicted Amplitudes")
plt.grid(True)
plt.text(0.1, 0.9, f"R2 Score: {r2:.4f}\nRMSE: {rmse:.4f}", transform=plt.gca().transAxes, fontsize=12,
verticalalignment='top', bbox=dict(boxstyle='round, pad=0.3', edgecolor='gray', facecolor='wheat'))
plt.show()