Разработка нейронной сети для реализации работы спектрометра космических излучений на алмазных детекторах

Принцип построения и описание прибора. Назначение и область применения спектрометра космических излучений на алмазных детекторах. Аппроксимация степенным многочленом. Математическая модель нейронной сети. Описание интерфейса программного комплекса.

Рубрика Программирование, компьютеры и кибернетика
Вид дипломная работа
Язык русский
Дата добавления 03.09.2017
Размер файла 591,1 K

Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже

Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.

23. Jolliffe I.T. Principal Component Analysis

24. Рао С. Р., Линейные статистические методы и их применения.

25. Анил К. Джейн, Жианчанг Мао, Моиуддин К.М. Введение в исскуственные нейронные сети.

Приложение

namespace nero

{

public partial class Form1: Form

{

NumericUpDown[] NLayers=null;

int stop = 0;

int epox = 0;

System.Windows.Forms.Label[] NLayerLabels = null;

double[][] input = null;

double[][] output = null;

double[][] input_train = null;

double[][] input_test = null;

double[][] output_train = null;

double[][] output_test = null;

double[][] intest = null;

double[][] outest = null;

double[] maxinput = null;

double[] mininput = null;

double[] maxout = null;

double[] minout = null;

double[] sredout = null;

double[] sredin = null;

double[] dispin = null;

double[] dispout = null;

public delegate void InvokeDelegate(string err_tr,double epox,double speed);

public delegate void MetodDelegate(int time);

public delegate void EnableDelegate(bool br);

public delegate void GraphDelegate(double err, double test);

PointPairList list1 = new PointPairList();

PointPairList list2 = new PointPairList();

NeuralNW netset = null;

double x = 1;

int time = 0;

double speed_teach = 1;

int vixod = 21;

Thread tt = null;

GraphPane pane = null;

int tik = 1;

int[] numer = null;

public Form1()

{

InitializeComponent();

maxinput = new double[(int)numericUpDown1. Value];

mininput = new double[(int)numericUpDown1. Value];

maxout = new double[vixod];

minout = new double[vixod];

sredout = new double[vixod];

sredin = new double[(int)numericUpDown1. Value];

dispout = new double[vixod];

dispin = new double[(int)numericUpDown1. Value];

numer = new int[800];

for (int i = 0; i < 400;i++ )

{

numer[i] = i;

}

pane = zedGraph. GraphPane;

pane. XAxis. Title. Text = "Эпохи обучения";

pane. YAxis. Title. Text = "Модуль ошибки ( Мэв )";

pane. Title. Text = "Ошибка сети и ошибка обобщения";

}

void normirov()

{

int j = 0;

int I = 0;

for (j = 0; j < input[0].Length; j++)

{

double max = -10;

double min = 100000000000000000;

double sum = 0;

for (i = 0; i < input.GetLength(0); i++)

{

sum = sum + input[i][j];

if (input[i][j] > max)

max = input[i][j];

if (input[i][j] < min)

min = input[i][j];

}

sredin[j] = sum / input.Length;

maxinput[j] = max;

mininput[j] = min;

for (i = 0; i < input.GetLength(0); i++)

{

if (max != min)

input[i][j] = (input[i][j] - min) / (max - min);

else

input[i][j] = (input[i][j] - min);

}

}

for (j = 0; j < output[0].Length; j++)

{

double max = -10;

double min = 1000000000000000000;

double sum = 0;

for (i = 0; i < output. GetLength(0); i++)

{

sum = sum + output[i][j];

if (output[i][j] > max)

max = output[i][j];

if (output[i][j] < min)

min = output[i][j];

}

sredout[j] = sum / output.Length;

maxout[j] = max;

minout[j] = min;

for (i = 0; i < output.GetLength(0); i++)

{

if (max != min)

output[i][j] = (output[i][j] - min) / (max - min);

else

output[i][j] = (output[i][j] - min);

}

}

}

void readfile()

{

int j = 0;

int razmernost = 1000;

input = new double[razmernost][];

output = new double[razmernost][];

for (int k1 = 0; k1 < razmernost; k1++)

{

input[k1] = new double[(int)numericUpDown1.Value];

output[k1] = new double[vixod];

}

StreamReader viborka = new StreamReader("input.txt");

while (true)

{

string text = viborka. ReadLine();

if ((text == null) || (text == ""))

{

viborka. Close();

break;

}

string[] ss = text. Split('\t');

for (int k2 = 0; k2 < numericUpDown1.Value; k2++)

{

input[j][k2] = Double. Parse(ss[k2]);

}

j++;

}

viborka. Close();

viborka = new StreamReader("output.txt");

j = 0;

while (true)

{

string text = viborka. ReadLine();

if ((text == null) || (text == ""))

{

viborka. Close();

break;

}

string[] ss = text. Split('\t');

for (int k2 = 0; k2 < vixod; k2++)

{

output[j][k2] = Double. Parse(ss[k2]);

}

j++;

}

viborka.Close();

}

void formervibork()

{

int i = 0;

int j = 0;

int r = 0;

int k = 0;

input_train = new double[4*input.Length / 10][];

output_train = new double[4 * input.Length / 10][];

output_test = new double[input.Length / 20][];

input_test = new double[input.Length / 20][];

outest = new double[input.Length / 20][];

intest = new double[input.Length / 20][];

for (k = 0; k < input_train.Length; k++)

{

input_train[k] = new double[(int)numericUpDown1.Value];

output_train[k] = new double[vixod];

}

for (k = 0; k < input_test.Length; k++)

{

input_test[k] = new double[(int)numericUpDown1.Value];

output_test[k] = new double[vixod];

intest[k] = new double[(int)numericUpDown1.Value];

outest[k] = new double[vixod];

}

for (k = 0; k < input. Length; k++)

{

int h;

Math. DivRem(k, 10, out h);

if (h < 4)

{

input_train[i] = input[k];

output_train[i] = output[k];

i++;

}

if ((h == 5)&&(j!=input_test. Length))

{

input_test[j] = input[k];

output_test[j] = output[k];

j++;

}

if ((h == 6) && (r != intest. Length))

{

intest[r] = input[k];

outest[r] = output[k];

r++;

}

}

}

void teach(double speed)

{

double lasterror = 100;

double err = 10;

double[] sumist_tr = new double[vixod];

double[] sumnorm_tr = new double[vixod];

double[] sumist_test = new double[vixod];

double[] sumnorm_test = new double[vixod];

// Ошибка сети

double error = 100;

double test_err = 100;

Stopwatch ss = new Stopwatch();

ss. Start();

while (err > 0.00000001)

{

epox++;

if (stop == 0)

{

break;

}

Random rand = new Random();

for (int i = numer. Length - 1; i > 0; i--)

{

int j = rand. Next(i);

int tmp = numer[i];

numer[i] = numer[j];

numer[j] = tmp;

}

for (int i = 0; i < input_train.Length; i++)

{

err=err+netset. LernNW(input_train[numer[i]], output_train[numer[i]], speed);

}

err = err / input_train.Length;

if (Math. Abs(err - lasterror) < 0.000000001)

{

// Уменьшаем коэффициент скорости обучения на 2

speed /= 2;

if (speed < 0.001)

speed = 0.001;

}

tik++;

error = 0;

for (int i = 0; i < input_train.Length; i++)

{

double[] y = new double[vixod];

double[] realout = new double[vixod];

netset. NetOUT(input_train[i], out y);

for (int j = 0; j < output_train[0].Length; j++)

{

realout[j] = output_train[i][j] * (maxout[j] - minout[j]) + minout[j];

y[j] = y[j] * (maxout[j] - minout[j]) + minout[j];

error = error + Math.Abs(realout[j] - y[j]);

}

}

error = error / input_train.Length;

test_err = 0;

for (int i = 0; i < input_test.Length; i++)

{

double[] y = new double[vixod];

double[] realout = new double[vixod];

netset. NetOUT(input_test[i], out y);

for (int j = 0; j < output_test[0].Length; j++)

{

realout[j] = output_test[i][j] * (maxout[j] - minout[j]) + minout[j];

y[j] = y[j] * (maxout[j] - minout[j]) + minout[j];

test_err = test_err + Math.Abs(realout[j] - y[j]);

}

}

test_err = test_err / input_test.Length;

lasterror = err;

grafic(error, test_err);

InvokeMethod("обучение "+error.ToString()+" \r\n тестовая " +test_err.ToString(), epox,speed);

InvokeMethod("0", epox,speed);

}

ss.Stop();

time =time+ ss.Elapsed.Seconds;

Method(time);

if (stop == 0)

{

enable(true);

}

else

{

Time = 0;

Epox = 0;

enable(false);

}

stop = 0;

}

private void сохранитьToolStripMenuItem_Click(object sender, EventArgs e)

{

if (netset==null)

{

MessageBox. Show("Сеть не создана!");

return;

}

DialogResult s=MessageBox. Show("Вы уверены ?","Внимание", MessageBoxButtons.OKCancel);

if (s == DialogResult. OK)

{

netset. SaveNW("net.txt");

MessageBox. Show("Сеть сохранена в файл net.txt в папке с программой!");

}

}

private void обучитьToolStripMenuItem_Click(object sender, EventArgs e)

{

if (netset==null)

{

MessageBox. Show("Сеть не создана! Создайте сеть для обучения!");

return;

}

readfile();

normirov();

formervibork();

stop = 1;

textBox4.Text = "0";

textBox5.Text = "0";

list1.Clear();

list2.Clear();

обучитьToolStripMenuItem. Enabled = false;

try

{

speed_teach = Double. Parse(textBox3.Text);

}

catch

{

MessageBox. Show("Параметры скорости и коэффициент активации должны быть числовые !");

return;

}

pane = zedGraph. GraphPane;

pane. CurveList. Clear();

Thread tt = new Thread(delegate() { teach(speed_teach); });

tt.Start();

}

private void создатьСетьToolStripMenuItem_Click(object sender, EventArgs e)

{

double sigmoid_a = 1;

if (NLayers == null)

{

MessageBox. Show("Настройте число скрытых слоев. Должно быть больше нуля!");

return;

}

else

if (NLayers.Length==0)

{

MessageBox. Show("Настройте число скрытых слоев. Должно быть больше нуля!");

return;

}

int[] nlayers = new int[NLayers.Length];

for (int i = 0; i < NLayers.Length; i++)

{

nlayers[i] = (int)NLayers[i].Value;

}

if (nlayers[nlayers. Length - 1] != vixod)

{

MessageBox. Show("Внимание! В данной задаче число нейронов в выходном слое должно быть 21\n У вас " + nlayers[nlayers. Length - 1] + "\n Измените число на 21, пересоздайте сеть и запустите обучение!");

return;

}

try

{

sigmoid_a = Double. Parse(textBox2.Text);

speed_teach = Double. Parse(textBox3.Text);

}

catch

{

MessageBox. Show("Параметры скорости и коэффициент активации должны быть числовые !");

return;

}

time = 0;

epox = 0;

MessageBox. Show("Сеть успешно создана, можно приступать к обучению");

}

private void тестирование_Click(object sender, EventArgs e)

{

Form2 ff = new Form2(netset);

ff. maxinput = maxinput;

ff. mininput = mininput;

ff. maxout = maxout;

ff. minout = minout;

ff. intest = intest;

ff. outest = outest;

ff. ShowDialog();

}

}

Размещено на Allbest.ru


Подобные документы

Работы в архивах красиво оформлены согласно требованиям ВУЗов и содержат рисунки, диаграммы, формулы и т.д.
PPT, PPTX и PDF-файлы представлены только в архивах.
Рекомендуем скачать работу.