0
$\begingroup$

I want to convert the code written in Python into Matlab code. May I know is it possible to do that. Share the available ways or methods to do the conversion. May I know is there any Online Translators which do the same.

Here is the Data I used:

https://drive.google.com/open?id=1GLm87-5E_6YhUIPZ_CtQLV9F9wcGaTj2

Here is my code in Python:

# imports libraries
import numpy as np
import pandas as pd
import os
import tensorflow as tf
import matplotlib.pyplot as plt
import random
from scipy import signal
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.models import Sequential
from tensorflow import set_random_seed
from tensorflow.keras.initializers import glorot_uniform
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
from sklearn.metrics import accuracy_score
from importlib import reload

# useful pandas display settings
pd.options.display.float_format = '{:.3f}'.format

# useful functions
def plot_history(history, metrics_to_plot):
    """
    Function plots history of selected metrics for fitted neural net.

    """

    # plot
    for metric in metrics_to_plot:
        plt.plot(history.history[metric])

    # name X axis informatively
    plt.xlabel('epoch')

    # name Y axis informatively
    plt.ylabel('metric')

    # add informative legend
    plt.legend(metrics_to_plot)

    # plot
    plt.show()

def plot_fit(y_true, y_pred, title='title'):
    """
    Function plots true values and predicted values, sorted in increase order by true values.

    """

    # create one dataframe with true values and predicted values
    results = y_true.reset_index(drop=True).merge(pd.DataFrame(y_pred), left_index=True, right_index=True)

    # rename columns informartively
    results.columns = ['true', 'prediction']

    # sort for clarity of visualization
    results = results.sort_values(by=['true']).reset_index(drop=True)

    # plot true values vs predicted values
    results.plot()

    # adding scatter on line plots
    plt.scatter(results.index, results.true, s=5)
    plt.scatter(results.index, results.prediction, s=5)

    # name X axis informatively
    plt.xlabel('obs sorted in ascending order with respect to true values')

    # add customizable title
    plt.title(title)

    # plot
    plt.show();

def reset_all_randomness():
    """
    Function assures reproducibility of NN estimation results.

    """

    # reloads
    reload(tf)
    reload(np)
    reload(random)

    # seeds - for reproducibility
    os.environ['PYTHONHASHSEED']=str(984797)
    random.seed(984797)
    set_random_seed(984797)
    np.random.seed(984797)
    my_init = glorot_uniform(seed=984797)

    return my_init
def give_me_mse(true, prediction):
    """
    This function returns mse for 2 vectors: true and predicted values.

    """

    return np.mean((true-prediction)**2)
# Importing the dataset
X = pd.read_excel(r"C:\filelocation\Data.xlsx","Sheet1").values
y = pd.read_excel(r"C:\filelocation\Data.xlsx","Sheet2").values

# Importing the experiment data
Data = pd.read_excel(r"C:\filelocation\Data.xlsx","Sheet1")
v = pd.DataFrame(Data, columns= ['v']).values
c = pd.DataFrame(Data, columns= ['c']).values
ird = pd.DataFrame(Data, columns= ['ird']).values
tmp = pd.DataFrame(Data, columns= ['tmp']).values

#Data Prepration
ird = ird.ravel()
tmp = tmp.ravel()
ir = np.nanmax(ird)
tp = np.nanmax(tmp)
p = v*c
p = p.ravel()
peaks, _ = signal.find_peaks(p)
nop = len(peaks)
pv = p.max()

#Experimental Data for testing
E_data = np.array([[ir,tp,pv,nop]])

#importing some more libraries
from sklearn.preprocessing import LabelEncoder
from keras.utils import np_utils

# encode class values as integers
encoder = LabelEncoder()
encoder.fit(np.ravel(y))
y_encoded = encoder.transform(np.ravel(y))
# convert integers to dummy variables (i.e. one hot encoded)
y_dummy = np_utils.to_categorical(y_encoded)

# reset_all_randomness - for reproducibility
my_init = reset_all_randomness()

# Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test, y_train_dummy, y_test_dummy = train_test_split(X, y, y_dummy, test_size = 0.3, random_state = 20)

# Feature Scaling
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
E_data = sc.transform(E_data)

# Initialising the ANN
model0 = Sequential()

# Adding 1 hidden layer: the input layer and the first hidden layer
model0.add(Dense(units = 160, activation = 'tanh', input_dim = 4, kernel_initializer=my_init))

# Adding 2 hidden layer
model0.add(Dense(units = 49, activation = 'tanh', kernel_initializer=my_init))

# Adding 3 hidden layer
model0.add(Dense(units = 24, activation = 'tanh', kernel_initializer=my_init))

# Adding 4 hidden layer
model0.add(Dense(units = 15, activation = 'tanh', kernel_initializer=my_init))

# Adding output layer
model0.add(Dense(units = 6, activation = 'softmax', kernel_initializer=my_init))

# Set up Optimizer
Optimizer = tf.train.AdamOptimizer(learning_rate=0.001, beta1=0.9, beta2=0.99)

# Compiling the ANN
model0.compile(optimizer = Optimizer, loss = 'categorical_crossentropy', metrics=['accuracy','categorical_crossentropy','mse'])

# Fitting the ANN to the Train set, at the same time observing quality on Valid set
history = model0.fit(X_train, y_train_dummy, validation_data=(X_test, y_test_dummy), batch_size = 100, epochs = 1500)

# Generate prediction for all Train, Valid set and Experimental set
y_train_pred_model0 = model0.predict(X_train)
y_test_pred_model0 = model0.predict(X_test)
y_exp_pred_model0 = model0.predict(E_data)

# find final prediction by taking class with highest probability
y_train_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_train_pred_model0])
y_test_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_test_pred_model0])
y_exp_pred_model0 = np.array([[list(x).index(max(list(x))) + 1] for x in y_exp_pred_model0])

# check what metrics are in fact available in history
history.history.keys()

# Inverse scaling 
X_train_inverse = sc.inverse_transform(X_train)
X_test_inverse = sc.inverse_transform(X_test)
E_data_inverse = sc.inverse_transform(E_data)

#Plots
print('#######################################################################')

# look at model fitting history
plot_history(history, ['mean_squared_error', 'val_mean_squared_error'])
plot_history(history, ['categorical_crossentropy', 'val_categorical_crossentropy'])
plot_history(history, ['acc', 'val_acc'])

# look at model fit quality
plot_fit(pd.DataFrame(y_train), y_train_pred_model0, 'Fit on train data')
plot_fit(pd.DataFrame(y_test), y_test_pred_model0, 'Fit on test data')

#Results
print('#######################################################################')

print('=============Mean Squared Error============')

print('MSE on train data is: {}'.format(give_me_mse(y_train, y_train_pred_model0)))
print('MSE on test data is: {}'.format(give_me_mse(y_test, y_test_pred_model0)))

print('#######################################################################')

print('================Accuracy===================')

print('Accuracy of ANN is: {} Percentage'.format((accuracy_score(y_test, y_test_pred_model0))*100))

print('#######################################################################')

print('========Result of Test Data set is=========')

for i in range(len(y_test)):
    print('%s => %d (expected %s)' % (X_test_inverse[i].tolist(), y_test_pred_model0[i], y_test[i].tolist()))

print('#######################################################################')

print('====Result of Experimental Data set is=====')

print('%s => %d' % (E_data_inverse, y_exp_pred_model0))
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.