static Func<double,double> G=(x)=>-Cos(x); //anti-derivative of g static void Main(){ int n=5; //number of sets of parameters var ann=new network(n,f,df,F); //creating a new "network" using n and our activation function f double a=-PI,b=2*PI; //a: "start" value, b: "end" value int nx=30; //length of xs and ys var xs=new double[nx]; var ys=new double[nx]; for(int i=0;i<nx;i++){ xs[i]=a+(b-a)*i/(nx-1); //interval of x inbetween a and b ys[i]=g(xs[i]); //function values of function to fit Write($"{xs[i]} {ys[i]} {dg(xs[i])} {G(xs[i])}\n"); } Write("\n\n"); for(int i=0;i<ann.n;i++){ ann.p[3*i+0]=a+(b-a)*i/(ann.n-1); //a ann.p[3*i+1]=1; //b ann.p[3*i+2]=1; //w } ann.p.fprint(Console.Error,"p="); ann.train(xs,ys); //calling "train" which minimizes the deviation given our x's and y's double offset = G(xs[0])-ann.feedF(xs[0]); ann.p.fprint(Console.Error,"p="); for(double z=a;z<=b;z+=1.0/64) Write($"{z} {ann.feed(z)} {ann.feeddf(z)} {ann.feedF(z)+offset}\n"); //calling "feed" which returns the output signal }//Main
public ActionResult DeleteConfirmed(int id) { network network = db.networks.Find(id); db.networks.Remove(network); db.SaveChanges(); return(RedirectToAction("Index")); }
static void Main() { WriteLine("______ Assignment A ______\n"); WriteLine("Testing the neural network for fitting to a function:\n"); Func <double, double> F_fit = delegate(double x){ return(Cos(5 * x - 1) * Exp(-x * x)); }; int n = 5; var ann = new network(n); double a = -1, b = 1; int nx = 20; vector xs = new vector(nx); vector ys = new vector(nx); for (int i = 0; i < nx; i++) { xs[i] = a + (b - a) * i / (nx - 1); ys[i] = F_fit(xs[i]); Error.Write($"{xs[i]} {ys[i]}\n"); } Error.Write("\n\n"); for (int i = 0; i < ann.n; i++) { ann.p[3 * i + 0] = a + (b - a) * i / (ann.n - 1); ann.p[3 * i + 1] = 1; ann.p[3 * i + 2] = 1; } ann.p.print("Before training: p ="); (int nsteps, int ncalls) = ann.train(xs, ys); ann.p.print("After training: p ="); WriteLine($"Minimization steps: {nsteps}"); WriteLine($"Function calls: {ncalls}"); for (double z = a; z <= b; z += 1.0 / 64) { Error.Write($"{z} {ann.feed(z)}\n"); } Error.Write("\n\n"); WriteLine("The fitted function can be seen in the figure Fit.svg."); Write("\n\n\n"); WriteLine("______ Assignment B ______\n"); WriteLine("We now use different feeders to get the derivative and antiderivative.\nThese can be seen in the figures Derivative.svg and Antiderivative.svg"); for (double z = a; z <= b; z += 1.0 / 64) { Error.Write($"{z} {ann.feedDeriv(z)}\n"); } Error.Write("\n\n"); for (double z = a; z <= b; z += 1.0 / 64) { Error.Write($"{z} {ann.feedInt(z)}\n"); } Error.Write("\n\n"); }
public ActionResult Edit([Bind(Include = "ID,networkName,networkPb,s_rate")] network network) { if (ModelState.IsValid) { db.Entry(network).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(network)); }
public ActionResult Create([Bind(Include = "ID,networkName,networkPb,s_rate")] network network) { if (ModelState.IsValid) { db.networks.Add(network); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(network)); }
/// <summary> /// creates random neural networks as a base /// </summary> private void initCarsNetwork() { //create all of the networks for the cars neuralNetworkList = new List <network>(); for (int i = 0; i < populationSize; i++) { network network = new network(layers); network.mutate(); network.israndomStart(); neuralNetworkList.Add(network); } }
// GET: networks/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } network network = db.networks.Find(id); if (network == null) { return(HttpNotFound()); } return(View(network)); }
private void button1_Click(object sender, EventArgs e) { if (label1.Text == comboBox1.Items[comboBox1.SelectedIndex].ToString() + "已开启") { MessageBox.Show("请先关闭监控"); } else { //用选中的IP地址作为监控端口 nt = new network(comboBox1.Items[comboBox1.SelectedIndex].ToString(), 4000); tr = new Thread(new ThreadStart(nt.start)); tr.Start(); label1.Text = comboBox1.Items[comboBox1.SelectedIndex].ToString() + "已开启"; } }
// total fitness() && findRandomParent() are used in conjunction /// <summary> /// chooses a random network using the total fitness found /// </summary> /// <returns></returns> private network findRandomParent()//finds a random network to be a parent form the networks list with larger fitness values having a higher chance { float rand = Random.Range(0, totalTopFitness); network foundParent = new network(layers);//created placeholder for parent // goes through top 50% of networks and reduces total fitness equivelent until it is 0 then chooses the parent for (int i = neuralNetworkList.Count - 1; i > populationSize * 0.5f; i--) { rand -= neuralNetworkList[i].getFitness(); if (rand < 0) { foundParent = neuralNetworkList[i]; //parent has been found i = 0; // ends for loop early } } return(foundParent); //returns the parent found }
/// <summary> /// asigns a neural network to the car for use /// </summary> /// <param name="net"></param> public void Init(network net) { neuralNetwork = net; crashed = false; if (net.champ) { champion = true; } if (net.randomCar) { randomStart = true; } if (net.loaded) { wasLoaded = true; } }
public void con() { Console.Write("Network Name: "); string net_name = Console.ReadLine(); Console.Write("Network Password: "******"Is Available[yes/no]: "); string available = Console.ReadLine(); // true by default bool is_available = true; if (available == "Yes" || available == "yes") { is_available = true; } else if (available == "No" || available == "no") { is_available = false; } network net = new network(net_name, net_pass, is_available); if (is_available) { this.connection = true; while (this.connection) { Console.WriteLine("Connected due to connectivity being " + this.connection); break; } } else { this.connection = false; while (this.connection != true) { Console.WriteLine("Not connected due to connectivity being " + this.connection); break; } } }
// Update is called once per frame void Update() { if (isAtStartup) { if (Input.GetKeyDown(KeyCode.S)) { game = new GameObject(); game.name = "game"; game.AddComponent <game>(); channel s = game.AddComponent <channel>(); game.AddComponent <server>(); network n = game.GetComponent <network>(); int t = n.AddGameObjectToChannel(game, game.GetComponent <server>().GetFreeID()); s.SetNetwork(n); s.SetChannel(t); game.GetComponent <game>().Init(); game.GetComponent <game>().LoadShip("Prefabs/Ship1", "Ship"); isAtStartup = false; } if (Input.GetKeyDown(KeyCode.C)) { isClient = true; game = new GameObject(); game.name = "game"; game.AddComponent <game>(); channel s = game.AddComponent <channel>(); game.AddComponent <client>(); network n = game.GetComponent <network>(); int t = n.AddGameObjectToChannel(game, 0); s.SetNetwork(n); s.SetChannel(t); game.GetComponent <game>().Init(); game.GetComponent <client>().Connect(myserver); game.GetComponent <game>().LoadShip("Prefabs/Ship1", "Ship"); isAtStartup = false; Cursor.lockState = CursorLockMode.Locked; } } }
public void LoadShip(string prefab_name, string object_name) { GameObject Ship = Instantiate(Resources.Load(prefab_name, typeof(GameObject)), this.gameObject.transform) as GameObject; channel s = Ship.GetComponent <channel>(); Ship.GetComponent <puppet>().InitTransform(Ship.transform.localPosition, Ship.transform.localRotation);// rotation); network n = GameObject.FindObjectOfType <network>(); int unikID = 1; if (!Channel.GetNetwork().IsClient()) { unikID = GetComponent <server>().GetFreeID(); } int t = n.AddGameObjectToChannel(Ship, unikID); s.SetNetwork(n); s.SetChannel(t); Channel.RegisterEntity(Ship, s.GetChannel()); object_name += "_" + t; Ship.name = object_name; Ship.GetComponent <ship>().Init(this.gameObject); ShipList[s.GetChannel()] = Ship; }
void Awake() { string[] sys = System.Environment.GetCommandLineArgs(); myserver = "localhost"; foreach (string s in sys) { if (s == "-batchmode") { game = new GameObject(); game.name = "game"; game.AddComponent <game>(); channel ss = game.AddComponent <channel>(); game.AddComponent <server>(); network n = game.GetComponent <network>(); int t = n.AddGameObjectToChannel(game, game.GetComponent <server>().GetFreeID()); ss.SetNetwork(n); ss.SetChannel(t); game.GetComponent <game>().Init(); game.GetComponent <game>().LoadShip("Prefabs/Ship1", "Ship"); isAtStartup = false; break; } } }
//验证所有控件的合法性 private bool UI_verifyControlsLegal() { network netSup = new network(); if (netAccBase64 == null || netAccBase64.Equals("") || netAcc() == null || netAcc().Equals("")) { pubFun_setText_simpleButton_showUser("请激活软件", Color.Red); return(false); } if (netPwd == null || netPwd.Equals("")) { pubFun_setText_simpleButton_showUser("宽带密码未填写", Color.Red); return(false); } //if (gateway == null || gateway.Equals("")) //{ // pubFun_setText_simpleButton_showUser("网关未填写", Color.Red); // return false; //} //if (!netSup.ValidateIPAddress(gateway)) //{ // pubFun_setText_simpleButton_showUser("网关数值不合法", Color.Red); // return false; //} if (routerAcc == null || routerAcc.Equals("")) { pubFun_setText_simpleButton_showUser("路由管理员未填写", Color.Red); return(false); } if (routerPwd == null || routerPwd.Equals("")) { pubFun_setText_simpleButton_showUser("路由密码未填写", Color.Red); return(false); } return(true); }
void Awake() { _instance = this; DontDestroyOnLoad(this.gameObject); }
private void Awake() { instance = this; DontDestroyOnLoad(this); }
void createNetwork() { champNetwork = new network(layers); readText(); }
// Update is called once per frame void FixedUpdate() { if (!training) { if (newPopSize > populationSize) { //adds to the back of the network list populationSize = newPopSize; tenthOfPopulation = populationSize / 10; initCarsNetwork(); } else if (newPopSize < populationSize) { //removes from the front of the network for (int i = populationSize; i > newPopSize; i--) { neuralNetworkList.RemoveAt(0); // removes the first element of the array } newPopSize = populationSize; tenthOfPopulation = populationSize / 10; } if (generationNumber == 0) { initCarsNetwork(); //create the network the } else { neuralNetworkList[neuralNetworkList.Count - 1].champ = false; // turn off previous champion neuralNetworkList.Sort(); // neuralNetworkList[start] -> worst ----- neuralNetworkList[end] -> best //top 3 of the generation Debug.Log("Champion of generation " + generationNumber + " Fitness: " + neuralNetworkList[neuralNetworkList.Count - 1].getFitness()); Debug.Log("Runner up of generation " + generationNumber + " Fitness: " + neuralNetworkList[neuralNetworkList.Count - 2].getFitness()); Debug.Log("Third place of generation " + generationNumber + " Fitness: " + neuralNetworkList[neuralNetworkList.Count - 3].getFitness()); if (!topFitnessFound) { totalFitness(); } for (int i = 0; i < populationSize * 0.9f; i++) //for the bottom 90% { // top 10% was not changed //creates new networks with the bottom 90% of cars if (i < tenthOfPopulation) //makes the first 10% of cars have random values { neuralNetworkList[i] = new network(layers); neuralNetworkList[i].israndomStart(); //make red } else //for the 10% - 90% of population create children from 2 parents in the top 10% { network parent1 = new network(layers); network parent2 = new network(layers); parent1 = findRandomParent(); //finds a random parent parent2 = findRandomParent(); //finds another random parent neuralNetworkList[i] = parent1.createChild(parent2); //creates new by splicing 2 networks together //mutate the new networks neuralNetworkList[i].mutate(); // add in mutation } } //resets top 10% of cars for (int i = tenthOfPopulation * 9; i < populationSize; i++) { neuralNetworkList[i] = new network(neuralNetworkList[i]);//copies self so as to reset the network } // resets the fitness of the networks for (int i = 0; i < populationSize; i++) { neuralNetworkList[i].setFitness(0.0f); } //set last neuron after sort to be the champion (to change colours) neuralNetworkList[neuralNetworkList.Count - 1].makeChamp(); //if a previous network was loaded if (previousChampionLoaded) { readText(); neuralNetworkList[0].wasLoaded(); } previousChampionLoaded = false; topFitnessFound = false; // set to false for the next generation } //generation tracking generationNumber++; generation.text = "Generation: " + generationNumber; Debug.Log("Generation " + generationNumber + " start"); generationLengthText.text = "Generation length: " + generationLength; //resets total fitness totalTopFitness = 0; //time until next generation is started training = true; timeLeft = generationLength; //creates the cars createCars(); //waits 'generationLength' seconds then does the "timer" function Invoke("timer", generationLength); } //keeps track of the time left for the user to view timeLeft -= Time.deltaTime; timeLeftString = timeLeft.ToString("F2"); timerText.text = "Time left: " + timeLeftString; checkAllDead(); }
static void Main(string[] args) { //network settings int[] LayerSizes = { 1, 20, 1 }; //ga setings int popsize = 1000; double rate = 100; int tournamentsize = 1; //number of trials before selecting individuals double intensity = 0.1; //maximal value added or substracted when mutating wieghts and biases double quality = 0.001; network[] pop = new network[popsize]; Random rnd = new Random(); for (int i = 0; i < popsize; i++) { pop[i] = new network(LayerSizes, rnd); } double[] error = new double[popsize]; double[] input = new double[1]; double[] outputs = new double[popsize]; while (true) { double toterror = 0; input[0] = rnd.NextDouble(); for (int j = 0; j < tournamentsize; j++) //compute error for sinus function out of several essays { for (int i = 0; i < popsize; i++) { error[i] = Math.Abs(pop[i].feed(input)[0] - Math.Sin(input[0])) / Math.Sin(input[0]); toterror += error[i]; } } Console.WriteLine("gen errors sum is " + toterror); //select best networks List <network> NextGen = new List <network>(); Array.Sort(error, pop); if (error[0] <= quality) { break; } for (int i = 0; i < 10; i++) //add top ten { NextGen.Add(pop[i]); } while (NextGen.Count < popsize) //then individuals in top 0.1 { NextGen.Add(pop[rnd.Next((int)(popsize * 0.1))]); } foreach (network nn in NextGen) //mutate { nn.mutate(rate, intensity, rnd); } pop = NextGen.ToArray(); //replace pop } //test selected nn for (int i = 0; i < 100; i++) { input[0] = rnd.NextDouble(); error[0] = Math.Abs(pop[0].feed(input)[0] - Math.Sin(input[0])) / Math.Sin(input[0]); Console.WriteLine(error[0]); } Console.ReadKey(); }
public void SetNetwork(network n) { mynetwork = n; }
public static int Main() { Func <double, double> activate = delegate(double x){ return(Exp(-x * x)); }; Func <double, double> df = delegate(double x){ return(-2 * Exp(-x * x) * x); }; Func <double, double> adf = delegate(double x){ return(Sqrt(PI) * math.erf(x) / 2); }; Func <double, double> fitfun = delegate(double x){ return(x * Exp(-x * x)); // I'm not terribly imaginative with my functions }; Write("Part A:\n"); int n = 8; // Wikibooks said this was a typical amount var ann = new network(n, activate, df, adf); double a = -2; double b = 2; int nx = 50; double[] xs = new double[nx]; double[] ys = new double[nx]; for (int i = 0; i < nx; i++) { xs[i] = a + (b - a) * i / (nx - 1); ys[i] = fitfun(xs[i]); Error.Write("{0}\t{1}\n", xs[i], ys[i]); } Error.Write("\n\n"); for (int i = 0; i < n; i++) { ann.p[3 * i] = a + (b - a) * i / (n - 1); ann.p[3 * i + 1] = 1.0; ann.p[3 * i + 2] = 1.0; } ann.p.print("Initial p="); vector time = ann.train(xs, ys); // time=[minimizeriterations, functioncalls] ann.p.print("Post-training p="); Write($"The minimiztion took {time[0]} iterations, and the deviation function was called {time[1]} times\n"); double z = a; for (int i = 1; i <= 100; i++) { Error.Write($"{z}\t{ann.feed(z)}\n"); z += (b - a) / 100; } Write("\n The calculated function can be seen in A.svg\n\n"); Write("Part B:\n"); // Create derivative and anti-derivative functions Func <double, double> dfun = delegate(double x){ return(Exp(-x * x) * (1 - 2 * x * x)); }; Func <double, double> adfun = delegate(double x){ return(-Exp(-x * x) / 2.0); }; Error.Write("\n\n"); z = a; for (int i = 1; i <= 100; i++) // For the derivative { Error.Write($"{z}\t{ann.dfeed(df, z)}\t{dfun(z)}\n"); z += (b - a) / 100; } Error.Write("\n\n"); z = a; for (int i = 1; i <= 1000; i++) // For the antiderivative { Error.Write($"{z}\t{ann.adfeed(adf, z)}\t{adfun(z)}\n"); z += (b - a) / 1000; } Write("The resulting derivates and antiderivatives can be seen in B.svg\n"); return(0); }
private void dispNormalStart() { if (r.setInternetMode_AutoIP(easy_routerAcc, easy_routerPwd) != 1)//先设成自动ip以过二维码 { pubFun_setText_simpleButton_showUser("路由账号或密码错误", Color.Red); } PPPOEDiceive pppoeDic = new PPPOEDiceive(); //实例化PPPOE模块 startNK2 NK = new startNK2(); //实例化NK_Control模块 network netSup = new network(); pppoeDic.Start(); pubFun_setText_simpleButton_showUser("请在netkeeper上登录", Color.White); NK.startNk(NK.findNk()); //启动NK //Thread.Sleep(800); //等待NK客户端启动,以免客户端未启动就被检测到了NK已退出 while (true) { //if (!NK.isAlive()) //{ // pppoeDic.Close(); //结束抓包循环 // pubFun_setText_simpleButton_showUser("客户端已被关闭", Color.Red); // log.writeLog("NK客户端关闭", log.msgType.warning); // return; //} if (pppoeDic.netAcc != null) //如果pppoe模块抓取到了账号 { //NK.killNk(); //结束NK pubFun_setText_simpleButton_showUser("正在处理...", Color.White); if (pppoeDic.netAcc.IndexOf(netAcc()) != -1 && netAcc().Length >= 11) //如果pppoeDic模块抓取的账号和已授权账号一致 { int callPPPOEResult = r.setInternetMode_PPPOE(routerAcc, routerPwd, pppoeDic.netAcc, netPwd, special, 3); //路由PPPOE拨号,手动连接 if (callPPPOEResult == 1) //如果路由PPPOE拨号成功 { pubFun_setText_simpleButton_showUser("正在检测网络连接", Color.White); heartBeat hb = new heartBeat(1, 1000 * 60 * 5, netAcc(), netSup.getLocaMac()); //初始化heartbeat对象 if (netSup.PingIpOrDomainName("www.baidu.com")) //测试网络连接状态 { hb.start(); //启动心跳 pubFun_setText_simpleButton_showUser("网络已连接,心跳已启动", Color.White); return; } else //没连接的话 { if (netSup.PingIpOrDomainName("www.baidu.com")) //再试一遍是否联网 { hb.start(); //启动心跳 pubFun_setText_simpleButton_showUser("网络已连接,心跳已启动", Color.White); return; } else { pubFun_setText_simpleButton_showUser("网络未连接,请注意克隆MAC可用性和宽带密码正确性", Color.Red); } } } else { pubFun_setText_simpleButton_showUser("拨号失败,请检查路由的账号或密码", Color.Red); } } else { pubFun_setText_simpleButton_showUser("客户端输入了不合法账号", Color.Red); } break; } Thread.Sleep(200); } //end of while(true) loop }
//线程,处理easy_start按钮事件 private void dispEasyStart() { //if (r.setInternetMode_AutoIP(easy_routerAcc, easy_routerPwd)!=1)//先设成自动ip以过二维码 //{ // pubFun_setText_simpleButton_showUser("路由账号或密码错误", Color.Red); //} PPPOEDiceive pppoeDic = new PPPOEDiceive(); //实例化PPPOE模块 //NKControl NK = new NKControl(); //实例化NK_Control模块 startNK2 NK = new startNK2(); //实例化NK_Control模块 network netSup = new network(); pppoeDic.Start(); pubFun_setText_simpleButton_showUser("请在netkeeper上登录", Color.White); //NK.runNK(); //启动NK NK.startNk(NK.findNk()); //启动NK while (true) { //if (!NK.isAlive()) //{ // pppoeDic.Close(); //结束抓包循环 // pubFun_setText_simpleButton_showUser("客户端已被关闭", Color.Red); // return; //} if (pppoeDic.netAcc != null) //如果pppoe模块抓取到了账号 { //NK.closeNK(); //结束NK //NK.killNk(); //结束NK pubFun_setText_simpleButton_showUser("正在处理...", Color.White); if (pppoeDic.netAcc.IndexOf(netAcc()) != -1 && netAcc().Length >= 11) { if (r.routerType != 1) { r.setCloneMAC(easy_routerAcc, easy_routerPwd, "pc"); //先试pc的mac } int callPPPOEResult = r.setInternetMode_PPPOE(easy_routerAcc, easy_routerPwd, pppoeDic.netAcc, pppoeDic.netPwd, 0, 1); //路由PPPOE拨号 if (callPPPOEResult == 1) //如果路由PPPOE拨号成功 { pubFun_setText_simpleButton_showUser("正在检测网络连接", Color.White); heartBeat hb = new heartBeat(1, 1000 * 60 * 5, netAcc(), netSup.getLocaMac()); //初始化heartbeat对象 if (netSup.PingIpOrDomainName("www.baidu.com")) //测试网络连接状态 { hb.start(); //启动心跳 pubFun_setText_simpleButton_showUser("网络已连接,心跳已启动", Color.White); return; } else //没连接的话尝试改变mac { if (r.routerType != 1) { r.setCloneMAC(easy_routerAcc, easy_routerPwd, "router"); //如果没连好网尝试改变路由的克隆mac为路由的mac } } for (int ap = 0; ap < 3; ap++) //最后试三遍有没有联网 { if (netSup.PingIpOrDomainName("www.baidu.com")) { hb.start(); //启动心跳 pubFun_setText_simpleButton_showUser("网络已连接,心跳已启动", Color.White); return; } else { pubFun_setText_simpleButton_showUser("网络未连接,请注意克隆MAC可用性和宽带密码正确性", Color.Red); } } } else { pubFun_setText_simpleButton_showUser("拨号失败,请检查路由的账号或密码", Color.Red); } } else { pubFun_setText_simpleButton_showUser("客户端输入了不合法账号", Color.Red); } break; } Thread.Sleep(200); } //end of while(true) loop } //end of thread method
private void start() { network._instance = this; }