text stringlengths 454 608k | url stringlengths 17 896 | dump stringclasses 91 values | source stringclasses 1 value | word_count int64 101 114k | flesch_reading_ease float64 50 104 |
|---|---|---|---|---|---|
Nathan, Yep, you've assumed correctly, that's a CVS keyword. All you need to put in your code is the "$Id$" and CVS will expand out the rest, or you can copy and paste one from anywhere into your code. CVS will replace the relevant portions the next time that you check you code into the repository.. If you're curious, the text that gets put there is the file name, it's revision number, the date/time of the last change to the file, the culprit's (:-) login name and the tag associated with the file. There's lots of info available on CVS at. The book written by Karl Fogel is just about the best around to get you up and running on it. Many folks assign the keyword to a string variable that can be parsed later on for useful information like so. // // Beware ... Java code follows :-) // public class VersionedClass { public String version="$Id$"; ... } This is particularly useful if you're debugging a product that has gone out the door (i.e. your exchanging emails with poor hapless user) and you need to verify which version of a particular class is in the binary. If you've built in a mechanism for printing out the 'version' variable, then , voila the mystery will be solved. I use this at work for distributed components such as CORBA, EJB's, servlets and cgi programs when I need to debug an installed application that might have been there for some time. BTW, I'm jealous of you being able to work in Mac OS X. Can't wait until I get the money scraped together to get am iMac for myself. What a sweet, sweet little machine, and decently priced for an Apple product. Cheers, Bobby Nathan wrote: > > I noticed that files contain something like this: > > $Id: versekey.h,v 1.24 2002/03/22 05:26:34 scribe Exp $ > > I assume CVS updates this text, so should I put something in my files > so this will happen if/when they get put into CVS. > > $Id: Exp $ > ? > > - n8 > | http://www.crosswire.org/pipermail/sword-devel/2002-April/014198.html | CC-MAIN-2016-40 | refinedweb | 348 | 77.37 |
#include <Pt/PoolAllocator.h>
Memory pool for objects of the same size. More...
Inherits NonCopyable.
If memory of uniform sizes has to be allocated, a MemoryPool can be used directly, rather than indirectly as part of the PoolAllocator. This can be faster, because the PoolAllocator has to look up the pool for the requested size of memory each time it allocates and deallocates. To construct a MemoryPool, the size of the records, i.e. the size of memory it can allocate, has to be specified.
Optionally, the maximum size of the blocks in the pool can be controlled. In the example shown above, the pool can only allocate memory of the size required for a float. Each time the pool itself requires more memory, it will allocate a new block of 4096 bytes. | http://pt-framework.net/htdocs/classPt_1_1MemoryPool.html | CC-MAIN-2018-34 | refinedweb | 133 | 63.39 |
A copy constructor is a special constructor in the C++ programming language for creating a new object as a copy of an existing object. The first argument of such a constructor is a reference to an object of the same type as is being constructed (const or non-const), which might be followed by parameters of any type (all having default values).
Example
#include <iostream> using namespace std; class Vehicle { public: int wheels; }; int main() { Vehicle Car; Car.wheels = 4; cout << "from object Car, car wheels are " << Car.wheels << endl; Vehicle smallTruck(Car); // copy constructor cout << "from copy constructor, small truck wheels are " << smallTruck.wheels << endl; getchar(); return 0; }
Output :
from object Car, car wheels are 4 from copy constructor, small truck wheels are 4 | http://www.loopandbreak.com/copy-constructor/ | CC-MAIN-2021-17 | refinedweb | 125 | 59.64 |
I'm trying to write a function which can wait for me to press anykey and then return my mouse position. I'm confused about how to get my xy value from key(event) function and return them with get_mouse_pixel().
from Tkinter import *
import win32api
def get_mouse_pixel():
x,y = 0,0
root = Tk()
def key(event):
x,y = win32api.GetCursorPos()
print "pressed", repr(event.char)
print "mouse position", x, y
root.quit()
def callback(event):
print "clicked at", event.x, event.y
frame = Frame(root, width=0, height=0)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()
frame.focus_set()
root.mainloop()
print x,y
return x,y
get_mouse_pixel()
Since you're using inner functions and you give them values, you have to tell your inner function (
key()) that the
x and
y you're setting aren't new variables, they're the ones in the outer scope. You can do that with the
nonlocal keyword in python3 (eg
nonlocal x,y
x,y = win32api.GetCursorPos()), or
global in python2. If you didn't assign to them, you could read from them in the inner scope, but you can't re-assign to them.
A different way to do it is that you can modify nonlocal variables. I.e. you can change mutable data types that aren't local- if you change
x and
y into a dictionary
d = {'x':0, 'y':0}, your
key() can change that nonlocal;
# Define x/y as dictionary d higher def key(event): d['x'],d['y'] = win32api.GetCursorPos() # Everything else you would like to do with x/y.
This will change dictionary
d to hold the new values without having to do potentially destructive things with global variables with the immensely common names
x and
y.
With the dict method, you can either return the whole dictionary or you can return each piece (ie
return d['x'], d['y']) to return nice ints if you want. | https://codedump.io/share/3uwNkNXWRnMW/1/return-value-from-a-event-binded-function | CC-MAIN-2016-44 | refinedweb | 325 | 72.87 |
I was in Toronto last week, so I dropped out of my normal routine: little email, no Advo, etc. It's nice to do that occasionally, and another blackout starts next week...
thomasvs: I've never read Written on the Body, but I've read and enjoyed several of Winterson's books. I read The Passion about once a year; I've probably given it as a gift more often than any other book (or object).
While in Toronto I talked to Ben Elliston (who I think isn't on Advo and thus, in a sense, not a <person> :-) about requirements and thoughts for a new build tool.
Some other important (though perhaps more minor) considerations that I didn't mention before:
- You need to hack the tools to record untaken dependencies (see the automake dependency-tracking paper), and also to tell the build tool about the other programs they exec. This might seem like overkill, but it is required at least for correctly building gcc.
- Targets and rules require separate namespaces. That way you can still easily write a program named install or info, both examples which have actually occurred.
- Well, there was more stuff, but I've forgotten it once again. I think I have it written down somewhere though.
Lately I've looked at ant a bit, since Eclipse uses it. I'm a bit discouraged by the use of XML. I find it hard to figure out what is going on, there is way too much text overhead. I haven't really followed the current mania for XML, in that respect I'm either lazy, stupid, or hopelessly backwards (take your pick). I haven't come to a definite conclusion regarding ant yet, given my relative lack of experience with it. I'd be interested to hear opinions. | http://www.advogato.org/person/tromey/diary.html?start=16 | CC-MAIN-2015-27 | refinedweb | 302 | 71.24 |
One that might normally require multiple tasks and data flow components.
In this article, I demonstrate how to implement a Script task into the control flow of a basic SSIS package. The purpose of the package is to retrieve data from a comma-separated values (CSV) file, insert the data into a SQL Server table (though no data is actually loaded), and then delete the file. The package includes a Script task that will first determine if the file has been updated since the last data load and, if so, whether the file currently contains data. You can download the SSIS package file, along with the two data files (one with data, and one without) from the bottom of the article. You’ll have to rename the data file that you use to PersonData.CSV.
NOTE: The Script task is different from the Script component. The Script component can be used as a source, transformation, or destination to enhance the data flow, but it cannot be used in the control flow, just like the Script task is not available to the data flow. However, many of the basic concepts I cover in this article apply to the Script component.
Setting Up Your SSIS Package
Before adding the Script task to your SSIS package, you should add and configure any components that are necessary to support the task, such as variables, connections managers, and other tasks. For the example in this article, however, I created a CSV file named PersonData.csv before adding any components to the package. To make it simpler for you to create the file, I’m including the bcp command I used to generate the file on my system:
Notice that the command retrieves Person data from the AdventureWorks2008R2 database and adds that data to the C:\DataFiles\PersonData.csv file. I also created a second bcp command to create an empty file with the same name. I did this in order to fully test the SSIS package. In the SELECT statement in the second command, I include a WHERE clause that references a nonexistent BusinessEntityID value:
Because I’m referencing a nonexistent BusinessEntityID value, the command creates an empty CSV file. You can use either file to test your SSIS package, should you decide to try the example I’m demonstrating in this article.
NOTE: I tested the SSIS package against both files. However, because the files share the same name, I had to create them one at a time, deleting the original, as necessary, after I ran the SSIS package.
The Script task that I’ll be demonstrating will reference two SSIS user-defined variables, so after I created the CSV file, I added the following two variables to my package:
- IsEmpty: A Boolean variable with a package-level scope. The variable will be used by the Script task to specify whether the source CSV file contains data. I’ve set the initial value to False, but the Script task will set the final value, so you can set the initial value to either True or False.
- LastUpdate: A DateTime variable with a package-level scope. I’ve set the value as an arbitrary date that precedes the date that I created the CSV files. In theory, the LastUpdate variable stores the timestamp of the last time the package ran and updated the database. In reality, this date would probably come from a table or some other system that logged the updates. For this article, however, it serves our purposes to set a hard-coded date.
My next step was to create a Flat File connection manager named PersonData. The connection manager connects to the C:\DataFiles\PersonData.csv file. Other than naming the connection manager and providing a description, I retained the default settings for its other options.
NOTE: This article assumes that you know how to run bcp commands as well as add and configure SSIS components, such as variables, connection managers, and tasks. If you’re not familiar how to use bcp or work with these components, you should first review the relevant topics in SQL Server Books Online or in another source.
The two variables and Flat File connection manager are the only SSIS components necessary to support the Script task that I’m going to demonstrate. So let’s look at how to add and configure that task.
Adding the Script Task to Your Package
After you add the Script task to your SSIS package, you can configure it by opening the Script Task Editor. On the editor’s General page, you should provide a name and description for the task. (I named the task Check file status.) Next, go to the editor’s Script page to configure the script-related properties, as shown in Figure 1.
Figure 1: Script page of the Script Task Editor
The first property that you need to set is ScriptLanguage. You can create your scripts in one of two languages: Visual Basic 2008 or Visual C# 2008. I used C# for the script that I created.
The next property on the Script page is EntryPoint. This is the method (specific to the selected script language) that the SSIS runtime calls as the entry point into your code. The Main method, in most cases, should work fine. However, if you choose another method, it must be in the ScriptMain class of the Visual Studio for Applications (VSTA) project.
The next two properties on the Script page are ReadOnlyVariables and ReadWriteVariables. As the names imply, you enter the name of any SSIS variables you want to use in your script. (Separate the names with commas for multiple variables of either type.) For instance, I added the LastUpdate variable to the ReadOnlyVariables property and the IsEmpty variable to the ReadWriteVariables property. As a result, my C# script will be able to retrieve the date from the LastUpdate variable and set the file status in the IsEmpty variable.
That’s all there is to configuring the Script task properties in preparation for creating the script itself, so once you’ve configured the properties, click the Edit Script button on the editor’s Script page to open the VSTA integrated development environment (IDE) window, shown in Figure 2. All script modifications are made in the VSTA development environment.
Figure 2: Default C# code in the VSTA IDE window
As Figure 2 shows, when you first open the VSTA window, you’ll see the default C# script, which includes the language necessary to work with the Main method of the ScriptMain class. Because Figure 2 shows only part of the script, I’m included the entire default code here for your convenience:
/*
Microsoft SQL Server Integration Services Script Task
Write scripts using Microsoft Visual C# 2008.
The ScriptMain is the entry point class of the script.
*/
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
namespace ST_96fb03801a81438dbb2752f91e76b1d()
{
// TODO: Add your code here
Dts.TaskResult = (int)ScriptResults.Success;
}
}
}
For the most part, you need to be concerned only with adding code to the Main method, specifically, to the section that is marked with the comment // TODO: Add your code here. (Comments are either preceded by double slashes for a single line or enclosed slashes and asterisks-/* and */-for multiple lines.) Usually, the only exception to where you enter code is at the beginning of the script, where you include the necessary using statements to define the relevant namespaces. For instance, the script includes the using System; statement so we can access classes in the System namespace, like those that reference components such as events, interfaces, and data types.
NOTE: A full explanation of how to use the C# language within a Script task is beyond the scope of this article. For specifics about the language, refer to a more complete resource, such as MSDN.
Other than the using statements and the Main method, you should, for the most part, leave the rest of the code alone, except for perhaps deleting comments. (Unless you’re a C# pro-then have add it.) Now let’s look how to modify the script to check the status of our flat file.
Writing Your C# Script
The first step I often take when working the code in the Script task is to get rid of the comments. In this case, I removed the comments before the Main method. You can also delete the opening comments, but I left them in just to provide a few reminders about the environment in which we’re working. So let’s look at how I’ve modified the script, and then I’ll explain the changes I’ve made. The following code shows how I’ve updated the original script and expanded the Main method:
Microsoft SQL Server Integration Services Script Task
Write scripts using Microsoft Visual C# 2008.
The ScriptMain is the entry point class of the script.
*/
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO; //added to support file access
namespace ST_5bd724e0deb3452e8646db6ec63913b()
{
// Define C# variable to reference SSIS user variable.
DateTime LastLoggedUpdate = (DateTime)(Dts.Variables[“LastUpdate”].Value);
// Define variable for connection string.
string PersonDataConnection = (string)(Dts.Connections[“PersonData”].AcquireConnection(null) as String);
// Create file object based on file connection.
FileInfo PersonDataFile = new FileInfo(PersonDataConnection);
// Retrieve properties from file object.
DateTime LastModified = PersonDataFile.LastWriteTime;
long PersonFileSize = PersonDataFile.Length;
// If the file was modified since the last logged update,
// set IsEmpty variable and set the task result to Success.
// Otherwise, fail the task.
if(LastModified > LastLoggedUpdate)
{
if(PersonFileSize > 0)
{
Dts.Variables[“IsEmpty”].Value = false;
}
else
{
Dts.Variables[“IsEmpty”].Value = true;
}
Dts.TaskResult = (int)ScriptResults.Success;
}
else
{
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
}
}
Let’s start with the using statements at the beginning of the script. You might have noticed that I added the using System.IO; statement. The System.IO namespace lets us access the language components we need in order to retrieve information about the flat file. I did not modify the script outside the Main method in any other way (except for deleting comments), so now let’s look at that method.
The first item I added after the Main method declaration is a DateTime variable named LastLoggedUpdate:
I’ve set the variable value to equal that of the SSIS LastUpdate variable that I defined on the package. To retrieve the value of the SSIS variable, I use the Dts object’s Variables property, which returns a Variable object. I then specify the name of the variable, enclosed in double-quotes and brackets, and tag on the Value property (available through the Variable object). This lets me retrieve the variable’s actual value. Note that I also cast the LastUpdate value to the DateTime data type by preceding the Dts variable construction by the name of the data type, just like I do when I declare the LastLoggedUpdate variable. I can now reference the LastLoggedUpdate variable within the Main method, and it will return the data currently stored the LastUpdate SSIS variable.
Next I declare a string variable named PersonDataConnection to hold the connection string I retrieve through the PersonData connection manager:
Notice that my declaration once again begins with the data type, followed by the name of the variable. I then set the variable’s value to equal the connection string. I retrieve the connection string by using the Dts object’s Connections property. This is followed by the name of the connection manager, enclosed in double-quotes and brackets, and then by the AcquireConnection method. The method takes one argument-the handle to a transaction type. In this case, we can specify NULL , which indicates that the container supports transactions but is not going to participate. In other words, you don’t need to worry about this. Just pass in NULL for this type of connection. Notice also that I’m explicitly converting the connection object to a string to pass into the PersonDataConnection variable.
The next variable I declare is PersonDataFile, which is defined with type FileInfo:
In this case, the variable’s value is based on a new instance of the FileInfo class. Because the FileInfo constructor takes the PersonDataConnection variable as an argument, you can use the methods and properties available to the FileInfo class to access information about the PersonData.csv file. That means you can access those properties and methods through the PersonDataFile variable, which is what I do in the next two variable declarations:
First, I declare a DateTime variable named LastModified and set its value to equal the value of the LastWriteTime property of the PersonDataFile variable, which is a FileInfo object. This will provide me with a timestamp of the last time the file was modified. I declare the second variable with the long data type and name the variable PersonFileSize. I then set the variable value to equal that of the file object’s Length property.
After I’ve declared the necessary variables, I’m ready to implement the logic needed to check the status of the PersonData.csv file. In the next section of code, I include two if…else statements, one embedded in the other:
Let’s start by looking at the outer if…else construction. Essentially, what this is saying is, “If the last modified date is more recent that the last time data was loaded into the database, run the script in the if section. Otherwise, skip to the end of the script and show the Script task as having failed.
The if statement begins by specifying the condition that determines whether to run the code in the if section or in the else section. If the condition evaluates to True-in this case, the LastModified date is more recent that the LastLoggedUpdate date-the code in the rest of the if section should run. If the condition does not evaluate to true, the code in the if section does not run and the code in the else section runs, which sets the Dts object’s TaskResult property to Failure. (The TaskResult property tells the runtime whether the task succeeded or failed.)
The embedded if…else construction checks whether the value in the PersonFileSize variable is greater than 0, in other words, whether the file contains any data. If the file does contain data, the code in the if section runs, otherwise the code in the else section runs. As a result, if the file contains data, the SSIS IsEmpty variable is set to false. If the file contains no data, the variable is set to true. Notice that after the embedded if…else construction, I’ve set the value of the TaskResult property to show that the task has successfully run.
That’s all there is to the script. Normally, you would also include code to handle exceptions, but what I’ve shown you here should provide you with an overview of the script’s basics elements. You can now close the VSTA window and then click OK to close the Script Task Editor. Be sure to save your changes.
Adding Other Tasks to Your Package
After I completed configuring the Script task and writing the C# script, I added a Data Flow task to the control flow. The data flow should, in theory, retrieve the data from the PersonData.csv file and insert it into a SQL Server database. However, for the purposes of this exercise, the Data Flow task serves only as a placeholder. It will still run like any other Data Flow task, but no data will actually be moved. Even so, you can still verify whether your control flow is set up correctly.
Next, I connected a precedence constraint from the Script task to the Data Flow task. I then added a File System task to the control flow and configured it to delete the PersonData.csv file. Next I connected a precedence constraint from the Script task to the File System task and one from the Data Flow task to the File System task. I then configured the two precedence constraints connecting to the File System task with the Logical OR option, which means that only one constraint must evaluate to True for the task to run. (By default, all constraints connected to a task must evaluate to True for the task to run.) Figure 3 shows what the control flow looked like after I added all the components.
Figure 3: Adding a Data Flow task and File System task to the control flow
Notice how the precedence constraints connecting to the File System task are dotted lines. This indicates that the constraints have been configured with the Logical OR option. Also notice that an expression is associated with each of the precedence constraints leading out of the Script task (as indicated by the fx label). Both constraints are configured so that the tasks down the line will run only if the Script task runs successfully and the expression evaluates to True. I defined the following expression on the precedence constraint that connects to the Data Flow task:
This means that the IsEmpty variable must be set to False in order for the expression to evaluate to True. The expression defined on the precedence constraint that leads from the Script task to the File System task is as follows:
This means, of course, that the IsEmpty variable must be set to True for the expression to evaluate to True. And that about does it for setting up the SSIS package. The only other step I took was to add a breakpoint to the Script task, which I’ll explain in the following section.
Running Your SSIS Package
Before I ran the SSIS package, I added a breakpoint on the OnPostExecute event to the Script task. As a result, when I ran the package, it stopped running as it was about to complete the Script task. Figure 4 shows what the package looks like when it stopped running.
Figure 4: Using a breakpoint to view variable values
When the package stopped running, I added a watch (shown in the bottom pane in Figure 4) on each of the two variables I created early on. The watches show the variable values at the time the package reached the breakpoint. Notice that the IsEmpty variable is set to False. Had the PersonData.csv file contained no data, the variable would have been set to True.
Next, I resumed running the package until it executing all applicable tasks. As Figure 5 shows, every control flow task ran. That’s because the IsEmpty variable evaluated to False and the Data Flow task ran and then the File System task ran.
Figure 5: Running the SSIS package when IsEmpty is false.
If the IsEmpty variable had evaluated to True, the Data Flow task would not have run, which is what happened when I added an empty file to the C:\DataFiles folder. This time around, only the Script task and File System task ran, as shown in Figure 6.
Notice that the value of the IsEmpty variable shown in the Watch window is set to True. As a result, the file would have been deleted, but no attempts would have been made to load data into the database.
And It Doesn’t End There
In the example above, the SSIS package performed in two different ways, depending on whether the file contained data. But there is a third scenario: the file was not updated since the last data load. If that happens, the Script task fails and the package stops running, which is what we’d expect given the way the script is written in the Script task. Another thing that the example doesn’t reflect is what would happen if the script threw an exception. Given that I’ve included no exception handling, I would again expect the task to fail. What this points to is that the example I’ve shown you here is only a simple script that contains relatively few elements. A script can be far more complex and take many more actions than what I’ve demonstrated here. However, you should now at least have enough information to get started creating your own scripts and using the Script task to extend your control flow so you can perform the tasks that need to be performed. | https://www.red-gate.com/simple-talk/sql/ssis/adding-the-script-task-to-your-ssis-packages/ | CC-MAIN-2018-05 | refinedweb | 3,391 | 61.36 |
Last Updated on August 21, 2019
You must be able to load your data before you can start your machine learning project.
The most common format for machine learning data is CSV files. There are a number of ways to load a CSV file in Python.
In this post you will discover the different ways that you can use to load your machine learning data in Python.
Kick-start your project with my new book Machine Learning Mastery With Python, including step-by-step tutorials and the Python source code files for all examples.
Let’s get started.
- Update March/2017: Change loading from binary (‘rb’) to ASCII (‘rt).
- Update March/2018: Added alternate link to download the dataset as the original appears to have been taken down.
- Update March/2018: Updated NumPy load from URL example to work wth Python 3.
How To Load Machine Learning Data in Python
Photo by Ann Larie Valentine, some rights reserved.
Considerations When Loading CSV Data
There are a number of considerations when loading your machine learning data from CSV files.
For reference, you can learn a lot about the expectations for CSV files by reviewing the CSV request for comment titled Common Format and MIME Type for Comma-Separated Values (CSV) Files.
CSV File Header
Does your data have a file header?
If so this can help in automatically assigning names to each column of data. If not, you may need to name your attributes manually.
Either way, you should explicitly specify whether or not your CSV file had a file header when loading your data.
Does your data have comments?
Comments in a CSV file are indicated by a hash (“#”) at the start of a line.
If you have comments in your file, depending on the method used to load your data, you may need to indicate whether or not to expect comments and the character to expect to signify a comment line.
Delimiter
The standard delimiter that separates values in fields is the comma (“,”) character.
Your file could use a different delimiter like tab (“\t”) in which case you must specify it explicitly.
Quotes
Sometimes field values can have spaces. In these CSV files the values are often quoted.
The default quote character is the double quotation marks “\””. Other characters can be used, and you must specify the quote character used in your file.
Need help with Machine Learning in Python?
Take my free 2-week email course and discover data prep, algorithms and more (with code).
Click to sign-up now and also get a free PDF Ebook version of the course.
Start Your FREE Mini-Course Now!
Machine Learning Data Loading Recipes
Each recipe is standalone.
This means that you can copy and paste it into your project and use it immediately.
If you have any questions about these recipes or suggested improvements, please leave a comment and I will do my best to answer.
Load CSV with Python Standard Library
The Python API provides the module CSV and the function reader() that can be used to load CSV files.
Once loaded, you convert the CSV data to a NumPy array and use it for machine learning.
For example, you can download the Pima Indians dataset into your local directory (download from here).
All fields are numeric and there is no header line. Running the recipe below will load the CSV file and convert it to a NumPy array.
The example loads an object that can iterate over each row of the data and can easily be converted into a NumPy array. Running the example prints the shape of the array.
For more information on the csv.reader() function, see CSV File Reading and Writing in the Python API documentation.
Load CSV File With NumPy
You can load your CSV data using NumPy and the numpy.loadtxt() function.
This function assumes no header row and all data has the same format. The example below assumes that the file pima-indians-diabetes.data.csv is in your current working directory.
Running the example will load the file as a numpy.ndarray and print the shape of the data:
This example can be modified to load the same dataset directly from a URL as follows:
Note: This example assumes you are using Python 3.
Again, running the example produces the same resulting shape of the data.
For more information on the numpy.loadtxt() function see the API documentation (version 1.10 of numpy).
Load CSV File With Pandas
You can load your CSV data using Pandas and the pandas.read_csv() function.
This function is very flexible and is perhaps my recommended approach for loading your machine learning data. The function returns a pandas.DataFrame that you can immediately start summarizing and plotting.
The example below assumes that the ‘pima-indians-diabetes.data.csv‘ file is in the current working directory.
Note that in this example we explicitly specify the names of each attribute to the DataFrame. Running the example displays the shape of the data:
We can also modify this example to load CSV data directly from a URL.
Again, running the example downloads the CSV file, parses it and displays the shape of the loaded DataFrame.
To learn more about the pandas.read_csv() function you can refer to the API documentation.
Summary
In this post you discovered how to load your machine learning data in Python.
You learned three specific techniques that you can use:
- Load CSV with Python Standard Library.
- Load CSV File With NumPy.
- Load CSV File With Pandas.
Your action step for this post is to type or copy-and-paste each recipe and get familiar with the different ways that you can load machine learning data in Python.
Do you have any questions about loading machine learning data in Python or about this post? Ask your question in the comments and I will do my best to answer it.
Hi!
What is meant here in section Load CSV with Python Standard Library. You can download the Pima Indians dataset into your local directory.
Where is my local directory?
I tried several ways, but it did not work
It means to download the CSV file to the directory where you are writing Python code. Your project’s current working directory.
Thank you, I got it now!
thanks budddy
You’re welcome.
thx
You are very welcome Anon!
hi
how can load video dataset in python?? without tensorflow, keras, …
I googled “python load video” and found this:
Is it possible to store the dataset in E drive while my python files are in C drive?
I don’t think Python cares where you store files.
Hello,
I want to keep from a CSV file only two columns and use these numbers, as x-y points, for a k-means implementation that I am doing.
What I do now to generate my points is this:
” points = np.vstack(((np.random.randn(150, 2) * 0.75 + np.array([1, 0])),
(np.random.randn(50, 2) * 0.25 + np.array([-0.5, 0.5])),
(np.random.randn(50, 2) * 0.5 + np.array([-0.5, -0.5])))) “,
but I want to apply my code on actual data.
Any help?
Sorry, I don’t have any kmeans tutorials in Python. I may not be the best person to give you advice.
I don’t want anything about k-means, I have the code -computations and all- sorted out. I just want some help with the CSV files.
Thank you for explaining how to load data in detail.
They work perfectly.
I’m glad to hear it!
I’m glad it helped Steve.
Thanks you very much…really helpful…
I’m glad to hear that Fawad.
how to load text attribute ? I got error saying could not convert string to float: b’Iris-setosa’
You will need to load the data using Pandas then convert it to numbers.
I give examples of this.
I was just wondering what the best practices are for converting something in a Relational Database model to an optimal ML format for fields that could be redundant. Ideally the export would be in CSV, but I know it won’t be as simple as an export every time. Hopefully simple example to illustrate my question: Say I have a table where I attribute things to an animal. The structure could be set up similarly to this:
ID, Animal, Color,Continent
1,Zebra,Black,Africa
2,Zebra,White,Africa
With the goal of being able to say “If the color is black and white and lives in Africa, it’s probably a zebra.” …so each line represents the animal with a single color associated with it, and other fields as well. Would this type of format be a best practice to feed into the model as is? Or, would it make more sense to concatenate the colors into one line with a delimiter? In other words, it may not always be a 1:1 relationship, and in cases where the dataset is like that, what’s the best way of formatting?
Thanks for your time.
Great question. There are no hard rules, generally, I would recommend exploring as many representations as you can think of and see what works best.
This post might help to give you some ideas:
can you tell me how to select features from a csv file
Load the file and use feature selection algorithms:
Hey,
I am trying to load a line separated data.
name:disha
gender:female
majors:computer science
name:
gender:
majors:
Any advice on this?
Ouch, looks like you might need to write some custom code to load each “line” or entity.
can you tell me how to load a csv file and apply feature selection methods?? can you post code for grey wolf optimizer algorithm??
Yes, see this post:
I have loaded the data into numpy array. What is the next thing that i should do to train my model?
Follow this process:
Hey,
I want to use KDD cup 99 dataset for the intrusion detection project. The dataset consist of String & numerical data. So should I convert entire dataset into numeric data or should I use it as it is?
Eventually all data will need to be numbers.
Hey Jason,
I have a dataset in csv which has header and all the columns have different datatype,
which one would be better to use in this scenario: loadtxt() or genfromtxt().
Also, is there any major performance difference in these 2 methods?
Use whatever you can, consider benchmarking the approaches with your data if speed is an issue.
I got a ValueError: could not convert string to float
while reading this data :
Can you please reply where I am doing wrong?
You might have some “?” values. Convert them to 0 or nan first.
filename = ‘C:\Users\user\Desktop\python.data.csv’
raw_data = open(filename, ‘rt’)
names = [‘pixle1’, ‘pixle2’, ‘pixle3’, ‘pixle4’, ‘pixle5’, ‘pixle6’, ‘pixle7’, ‘pixle8’, ‘pixle9’, ‘pixle10’, ‘pixle11’, ‘pixle12’, ‘pixle13’, ‘pixle14’, ‘pixle15’, ‘pixle16’, ‘pixle17’, ‘pixle18’, ‘pixle19’, ‘pixle20’, ‘pixle21’, ‘pixle22’, ‘pixle23’, ‘pixle24’, ‘pixle25’, ‘pixle26’, ‘pixle27’, ‘pixle28’, ‘pixle29’, ‘pixle30’, ‘class’]
data = numpy.loadtxt(raw_data, names= names)
Well done!
I have multiple csv files of varying sizes that I want to use for training my neural network. I have around 1000 files ranging from about 15000 to 65000 rows of data. After I preprocess some of this data, one csv may be around 65000 rows by 20 columns array. My computer starts running out of memory very quickly on just 1 of the 65000 by 20 arrays, so I cannot combine all the 1000 files into one large csv file. Is there a way using keras to load one of the csv files, have the model learn on that data, then load the next file, have the file learn on that, and so on? Is there a better way to learn on so much data?
I have a few ideas here:
I have multiple 200 CSV files and labels files that contains 200 rows as output. I want to train, but unable to load the dataset
You may have to write come custom code to load each CSV in turn. E.g. in a loop over the files in the directory.
I got the error:
Traceback (most recent call last):
File “sum.py”, line 8, in
data= numpy.array(x).astype(float)
ValueError: setting an array element with a sequence.
why?
It suggests that x is not an array or a list.
Hello,
I have a dataset which contains numbers like this: 3,6e+12, 2.5e-3…
when reading this dataset as a CSV file, I get the error: “Value error: cannot convert string to float”
Any solution please??
The numbers are in scientific notation and will be read correctly.
Perhaps there are other non-number fields in the file?
No, there aren’t, and the error says :” cannot covert string to float in 3.6e+12″
thank you
That is surprising, perhaps try a different approach to loading, e.g. numpy or pandas?
Perhaps try posting to stackoverflow?
I’ll try ,
thanks
Sir,
Suppose i have 3 csv files , each having a particular attribute in it. So a single row in the 3 csv file correspond to a particular feature instance. So during the loading time can i load all the csv file together and convert each row into numpy array,
thanks
I recommend loading all data into memory then perhaps concatenate the numpy arrays (e.g. hstack).
If I have a data set with .data file extention how can I deal with it in python?
please help
Perhaps use a text editor to open it and confirm it is in CVS format, then open it in Python as though it were a CSV file.
I copy your codes as follows:
# Load CSV using NumPy
# You can load your CSV data using NumPy and the numpy.loadtxt() function.
import numpy
filename = ‘pima-indians-diabetes.csv’
raw_data = open(filename, ‘rt’)
data = numpy.loadtxt(raw_data, delimiter=”,”)
print(data.shape)
===============
However, I got an error message
ValueError Traceback (most recent call last)
in
5 filename = ‘pima-indians-diabetes.csv’
6 raw_data = open(filename, ‘rt’)
—-> 7 data = numpy.loadtxt(raw_data, delimiter=”,”)
8 print(data.shape)
~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in loadtxt(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin, encoding)
1099 # converting the data
1100 X = None
-> 1101 for x in read_data(_loadtxt_chunksize):
1102 if X is None:
1103 X = np.array(x, dtype)
~\Anaconda3\lib\site-packages\numpy\lib\npyio.py in read_data(chunk_size) (.0) floatconv(x)
744 if ‘0x’ in x:
745 return float.fromhex(x)
–> 746 return float(x)
747
748 typ = dtype.type
ValueError: could not convert string to float: ‘Pregnancies’
========
I do not know what is wrong.
I’m sorry to hear that, I have some suggestions for you here:
how to load the dataset from the working directory to colab?
Sorry, I have not used colab.
When I click the “update: download from here” to download the CSV file, it takes me to a white page with number on the left side which looks to be the data. How do I get / download this data into a CSV file? Thanks!
Here is the direct link:
Thank you!
Hi Jason,
I hope you can help me with the following preprocessed dataset.txt file. How can I load this dataset in python? It contains a total of 54,256 rows and 28 columns. Can I use pandas?
[0.08148002361739815, 3.446134970078908e-05, 4.747197881944017e-05, 0.0034219001610305954, 0.047596616392169624, 0.11278174138979659, 0.0011501307441196414, 1.0, 0.09648950774661698, 0.09152382450070766, 0.0032736389720705384, 0.02231715511892242, 0.0, -1.0, 0.0, -1.0, -1.0, -1.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0, -1.0, 1.0, -1.0]
[0.0816768352686479, 2.929466010613462e-05, 1.2086789450560964e-06, 0.6246987951807229, 0.04743433880824845, 0.11350265074251698, 0.0011614423285977043, 1.0, 0.0965330892767645, 0.0914339631118999, 0.003190342698832632, 0.022268885790504313, 0.0, -1.0, 0.0, -1.0, -1.0, -1.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0, -1.0, 1.0, -1.0]
[0.08226727022239716, 2.987144231823633e-05, 2.2329338947249727e-06, 0.047448165869218496, 0.04753095407349041, 0.11459941368369171, 0.0011702815567795678, 1.0, 0.0969906953433135, 0.09170354727832318, 0.003358412434012629, 0.022329898179060795, 0.0, -1.0, 0.0, -1.0, -1.0, -1.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0, -1.0, 1.0, -1.0]
.
.
.
.
.
.
You can load it as a dataframe or a numpy array directly.
What problem are you having exactly?
When I try to load it as a numpy array it returns the list again
I am using the following code after loading the dataset.txt file into memory:
import numpy as np
dataset = load_doc(‘dataset.txt’)
x= np.asarray(dataset)
print (x)
Try:
print(type(x))
Thank you so much!
So my last question (hopefully) is that I have the dataset, the labels and a list of 28 titles for the columns. I am trying to load them in python so I can split them and create my training and testing datasets. I am not sure what to do with the titles. Do I need to load them as well?
You can use the column heading as the first line in the CSV file and load them automatically with pandas.
Alternately, you can specify them as the columns in python, if needed.
Or discard them completely.
hi
i am new .
please help me to convert image dataset to csv.
You don’t, instead you load images as arrays:
how can i load data from parser
from parser import load_data #dataloading
I don’t understand, sorry. Perhaps try posting to stackoverflow?
Hi, Jason, the dataset has been removed from the above link and I want to check that because the whole of your book is based on that dataset only, so please provide us the dataset as it would become easy for us to understand concepts from your book, please provide the dataset.
Thank You
I provided an updated link directly in the post, here it is again:
sir, pls help me
i just want ,
how to classify categorical image by SVM and KNN alogrithm using python
Perhaps start here:
Hello,
Thank you so much for all the great Tutorials. I would like to use a multivariate time series dataset and at first I need to make a similar format as of load_basic_motion data in Python. I have several text files each representing one feature and each file has time series data for each observation. Do you have any suggestions for preparing the data in the required format?
Thanks!
Perhaps this tutorial will provide a useful starting point and adapted to your needs:
Hello,
i successfully loaded my csv file dataset. Its basically a letter dataset and now i want to train my python with this loaded dataset so that i can use this to recognise words later can you help me with is ?
thank you
Yes, you can get started with text data in Python here:
Hi Jason,
One question here, may I know how can I load my non-csv data (a normal file instead) on spyder pyhton without converting to csv file dataset?
Yes, you can customize the call to read_csv() function for your dataset.
X = list(map(lambda x: np.array(x), X))
X = list(map(lambda x: x.reshape(1, x.shape[0], x.shape[1]), X))
y = np.expand_dims(y, axis=-1)
I used Tcn model .when i run i got this error .Index out of Range please please help me how to solve this error ..i also search from stackoverflow but not found
This is a common question that I answer here:
Thanks for this nice article.I want to know if we have a digit classification problem and the last column contain the class.Then how to load and print the digits ignoring the last column.
I tried it and it is showing .
ValueError: cannot reshape array of size 257 into shape (16,16)
This tutorial will show you how to load and show image data:
Thanks .But the pixels of the image are in csv format and the last column of the dataset contains the label which I want to ignore.The dataset I am using is usps.csv to classify digits.Thanks in advance.
That is very strange. Typically pixels are stored in an image format.
I’m not sure I have a tutorial that can help directly, you may have to write some custom code to load the CSV and convert it to an appropriate 3d numpy array.
Hi.I got my work done by keeping the data in the csv in numpy arrays and then slicing the array.However your tutorials are very nice and helpful.Thanks.
Well done!
Thanks 🙂
You’re welcome.
Dear Jason,
How I can load .rek dataset in python? please comment if possible. Thanks
I am not familiar with that file type, sorry.
Thanks Jason
You’re welcome.
how to load image dataset in python code
Perhaps start here:
And here:
hi jason, i am a fresher with no experience. how can i learn data science. can you suggest me a roadmap? that will be helpful for me.
Right here:
hey jason,
i actually wanted to use some specific columns in a csv file for loading the data into a machine learning model. can you help me out.
Yes, load the data as normal, then select the columns you want to use, or delete the columns you do not want to use.
If you are new to numpy arrays, this will help:
And this:
Actually the data set i am using has data of two types of signals. i dont want to delete the columns. i want to use “the columns of one type of signal” in one model the other in the second one.
please do tell me if you can help me out
thank you tho
You can use the ColumnTransformer, for an example see this tutorial:
Hi!! is it possible to cluster the similar rows of a csv file ( 2 columns) together using nlp. If yes could you please guide me with a post to help with the code.
Yes, sorry, I don’t have an example of clustering for text data. | https://machinelearningmastery.com/load-machine-learning-data-python/ | CC-MAIN-2022-27 | refinedweb | 3,732 | 73.98 |
On 22/02/2012 21:02, Nicolas Cannasse wrote:
> Well, I think most of them comes down to design choices. Instead of
> focusing on what AS3 have and haXe does not, maybe focusing on what
> haXe has and AS3 haven't would also be useful ? Unless it's a clear
> showstopper feature of course.
From the AS3 developers (my) point of view the list of things that haXe
is not capable of is more important as it will interrupt our current
concepts. That is why I focused on it. I think its important to know
about it in this list.
>> *) Standalone variables/constants/function files outside of a class
>> context. I found them very liberating and as far as I can tell: haXe
>> only allows class/ENum/ alike.
>
> We have plans for Java-like "import statics" for haXe 3.0 : this will
> enable you to import all statics of a given class into the global
> namespace.
The point of the functions-files is that you don't create huge code
dependencies: Say you create a dependency to StringTools.endsWith() then
the compiler better compiles all functions of StringTools into the swf
so it can be loaded properly. In AS3: If i just create a dependency to
one function file (without a prefixing class) then it will just include
this one function, once. Allows a slimmer swf, doesn't it? Having import
statics will not solve that problem, right?
> We have haxe.xml.Fast API which is maybe not as much powerful as E4X
> but still very convenient for quick XML parsing. It should be possible
> to write a quite complete E4X equivalent with haXe macros.
>
>
> Keep in mind also that XML is being replaced in lot of cases by JSON.
Specially due to the lack of proper documentation and validation of JSON
(namespace...) - xml will stay a standard that is used in enterprise
environments still for a while. Specially with namespaces e4x is a
blessing. However: This just means that we would need to help with e4x
macros for haXe.
Aside from that, I read a little into the Macro language and I wonder
that is really implementable, I think specially about things like:
var b: String = "foo";
var a: XML = <{b}></{b}>;
// <foo></foo>
or
var a: XML = <b/>;
a = a + <c/>;
// <b/><c/>
Can that be implemented with Macros?
> Is this really a showstopper feature ? :)
Initializers are not a show-stopper but incredibly handsome on the daily
job :)
> We have "real this" support in local functions : it means it's the
> "this" of the class in which the local function is declared, not the
> one of the "current this" in which context this function which be
> called. This gives real strict typing since we don't know the latter.
The AS3 compiler creates automatic method closures. I am not entirely
sure how they are treated by the Flash Player. It seems I lack the
vocabulary to describe the difference properly so I attached a zip. The
haxe version will display "b" where the as3 version displays "a". I hope
with this I can make myself clear.
This "logic" is very important through all AS3 code I have ever seen.
The "JavaScript" approach of handling "this" requires a lot of
rethinking within the AS3 community as many concepts won't work anymore
as expected - or just with hacks.
>
>> *) Namespaces: While I don't "like" namespaces particularly, porting
>> Flex to haXe might be difficult without it.
>
> Indeed. But Javascript does not have namespaces either, so if you want
> to compile to JS you'll have to deal with it somehow.
Theoretically namespaces are hackable using prefixes. Even though they
would consume quite some javascript size I guess.
> We have a pending draft for access control customization. It's not yet
> implemented but could be done in matter of days, please check it there :
>
That is a very nice draft. Looks awesome!
>
>> *) Compiling the "asdoc" to different locales
>
> Not really an issue there, the documentation format is flexible and
> you can get your raw /** ... **/ comments as XML output and deal with
> it as you wish.
But it doesn't do it out of the box? I mean: translation? asdoc allowed
using additional xml files to inject translation based on property flags.
>> *) Documentation on Meta-tags
>
> Like ?
I am talking about a way to document the meta data (like [Style]) use.
that can be represented in the asdocs. In UIComponent for example all
documentation of Styles [1] can be found inline in the code [2] and is
automatically created.
>
>> *) Binding
>
> I'm not familiar with Binding, but it needs to either be translated to
> property access or another corresponding low level feature. I guess
> this can be achieved with compiletime code generation thanks to
> macros, and again using such not-native scheme will enable it to work
> on all platforms supported by haXe as well.
Binding essentially modifies the code to send events on change. So if
you write
[Bindable]
public var foo: String;
then it makes something like
public function get foo():String {
return _barMD5;
}
public function set foo(bar:String):void {
if( _barRandomKey != bar ) {
dispatchEvent( new PropertyChangeEvent("propertyChange",
_barRandomKey, _barRandomKey = bar) );
}
}
and if the class wasn't extending EventDispatcher before than it will be
"modifed" to do it now. Horrible mechanism..... but comfortable to use.
> We have support for bitmaps so far, by using :
>
> @:bitmap("myfile.png") class Bmp extends flash.display.BitmapData {}
That is a big feature that was essential to many parts of the code.
Embed fonts are very important. I have read of hxswfml but I am not sure
how far that would go.
yours
Martin.
[1]
[2]
(see [Style...] ) | http://mail-archives.apache.org/mod_mbox/incubator-flex-dev/201202.mbox/%3C4F44FC03.7050202@leichtgewicht.at%3E | CC-MAIN-2014-10 | refinedweb | 943 | 73.37 |
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Flask-WTF Forms9:39 with Kenneth Love
Using code-based forms to create HTML forms and also provide data validation gives us two powerful tools for building our web application.
In Flask and in Django, people often get the wrong idea about forms. 0:00
They hear the word form, and immediately think about HTML forms. 0:04
They think that forms are all about display. 0:07
And really that makes forms very limited. 0:10
Forms are about validation. 0:12
Making sure that your data matches a certain pattern. 0:14
The de facto form library for Flask is Flask-WTF, 0:17
and it builds on top of an older package named WTForms, and 0:20
we'll actually end up with both of them installed. 0:24
You'll install this with pip install flask-wtf. 0:27
This package also provides us with CSRF, or cross-site request forgery, protection. 0:31
What's cross-site request forgery? 0:37
Well, imagine you've logged in to your bank site and 0:39
it keeps you logged in through a cookie. 0:41
Now, imagine that some horrible person out there sends you an image in an HTML page. 0:43
But instead of an image URL, the URL goes to some send me $1,000 page on your bank. 0:46
Without CSRF your bank trusts that you actually made that request, and 0:52
goes ahead and sends them the 1,000 bucks. 0:55
CSRF includes a custom one time code with each submission. 0:58
And, if the form doesn't have that code, or 1:02
doesn't have the right one, the request is ignored. 1:04
Okay, let's make our registration form. 1:07
All right, so if we're gonna forms, 1:10
our app.py, I can already tell it's gonna get pretty crowded. 1:11
So, we probably don't wanna put them in there. 1:15
And our models.py should really just be models. 1:17
So let's add another new file. 1:19
That we will call forms.py. 1:21
Very creative, I know. 1:25
This is where we're gonna build the forms. 1:26
Now, our form that we're gonna build, I wanna warn you. 1:27
There's a lot here. 1:31
So we're gonna do a lot of stuff. 1:32
So here we go. 1:34
Okay. 1:35
From flask_wtf import Form. 1:36
And what's kinda weird is that flask_wtf doesn't use the flask.ext thing. 1:41
I really wish it did, but it doesn't. 1:45
And then we're gonna say from models import User. 1:47
And let's start building our class. 1:51
So we'll make a RegisterForm. 1:56
You can call it registration form if you wanted. 1:57
And it's going to be of the class form. 2:00
Form is the parent class. 2:02
So Username equals StringField. 2:04
And then this first argument that we give here is the label. 2:09
So if you think about forms as they show up on HTML, there's a label, right? 2:13
So we're gonna put the label of Username. 2:20
If we think about our Username field, there's some things that have to be valid. 2:23
For it to be a real username, right? 2:27
So, there has to be data. 2:29
We probably want it to match a certain pattern. 2:31
And we should probably make sure that it's not already in the database. 2:33
Though, these requirements here, we call these validators. 2:37
So we actually have an argument here, called validators. 2:41
And we can put in validators. 2:45
So, I guess that we want there to be data, right? 2:47
So DataRequired is one of the validators. 2:51
And then, the others we kinda have to create our self. 2:55
Well, the regular expression we don't. 2:58
So, we want to match our patterns, so we're gonna use Regexp, 2:59
which is a regular expression, regular expression pattern. 3:03
So, what are we gonna give it. 3:07
Well, we have to give it a pattern. 3:09
What would our pattern be? 3:10
Well, we want it to start, and we only want a through z lower case, 3:13
A through Z upper case, 0 through 9, and then underscore. 3:18
And we want that to be as many of those as, as they want, at least one, and 3:23
then we want that to end. 3:27
Why didn't I just use /w with a plus sign? 3:29
Since we're gonna be showing this in the URL, 3:33
sometimes unit code doesn't play nicely with the URL. 3:36
So I figure it's safer just to restrict them to using ASCII than it is to 3:39
worry about something looking weird, or not actually loading, or, or whatever. 3:43
If you wanna go with Unicode or 3:47
you wanna do some other requirement, then that's fine, go for it. 3:49
But this is the one that I wanna do. 3:53
Okay. So that's our pattern. 3:55
And I'm gonna pass in a message. 3:57
So, my message is going to be, 3:59
Username should be one word, letters, 4:02
numbers, and underscores only. 4:07
And look at that, I'm way out on column 95, so let's do. 4:11
I'm gonna make sure I can break this. 4:16
I'm gonna put a parenthesis here. 4:18
And I'll close the quote here. 4:20
Open a new quote. 4:22
Close that parenthesis. 4:24
This is a really handy way of not having the light invalidate a line break. 4:25
Just a little, quick little tip here. 4:29
Okay, and then that closes our Regexp thing. 4:32
Before we forget, let's go up here and actually import those. 4:37
So, from wtforms import StringField, 4:40
because it's StringField that we're using. 4:43
And then from wtforms.validators 4:48
import DataRequired, and Regexp. 4:54
So far those are the only two we need. 4:59
All right. 5:01
As I said, we also wanted to make sure that name did not already exist. 5:02
Right? 5:06
So we're gonna write our own validator that we're gonna use here. 5:06
And we're gonna call this name_exists. 5:10
Then we close our list. 5:14
And we close our StringField. 5:16
So let's go right name_exists. 5:17
So here we go def name_exists, and this takes two arguments, 5:20
it takes the form, that it's running on, so in this case, register form, 5:24
and it takes the field that it's running on, in this case username. 5:29
And we wanna do if User.select .where User.name, 5:33
oops sorry we called it username, is equal to field.data.exists. 5:39
So that just returns a Boolean of either true or false. 5:47
This record's here or this record's not. 5:49
So, if that comes back as true, then we want to raise ValidationError 5:51
of User with that name already exists. 5:57
But look, we imported something else and we need to, or we're using something else, 6:03
we need to import that. 6:07
And we need to import ValidationError. 6:08
We've done a lot and we've only created one field. 6:12
We need another blank line here too. 6:15
There we go. 6:17
Okay, so there's our username field. 6:18
Well, what comes next? 6:21
Well, in the register, we ask for a username, we ask for an email address, and 6:22
we ask for a password twice. 6:26
So let's figure out how to do the email. 6:28
And we're gonna say Email, right? 6:36
Now what validators does email have? 6:40
It's got a few. 6:44
So the first one that it has, is that data is required. 6:45
Something has to be there. 6:50
Second one is email. 6:52
It has to be email. 6:54
And then lastly, we're gonna make another function named email_exists. 6:56
So let's go do those two. 7:01
So, first of all we need to import email. 7:03
And you know what? 7:08
That's 76 characters, I bet we're gonna have to import something else, so 7:09
let's put a parenthesis there and 7:14
then that way we can import some stuff on the next line too. 7:16
So name exists is already there, so let's add def email_exists and 7:19
again, form, field, you know what? 7:25
Let's take this whole thing. 7:29
And paste it, because these two are gonna be almost identical, except for 7:32
you want this to be email. 7:36
And you want this to be email. 7:37
So, same idea on these two, name exists, email exists, except for 7:42
what they point to. 7:46
All right, so there's that one. 7:48
And let's add in password. 7:51
This is gonna be a password field. 7:52
Oh, new import. 7:55
And we'll say Password. 7:56
And it's gonna have some validators too. 7:58
Validators are gonna be DataRequired. 8:02
Cuz they have to give us a password. 8:05
Link and we'll say it has to be at least two characters long for the password. 8:08
I would really say you make this like seven or eight or something, but 8:12
it has to be at least two. 8:16
And then, we're gonna do a new one here. 8:17
EqualTo. And 8:20
we're gonna say it's gonna be EqualTo password2, whatever that is. 8:21
And then the message if it doesn't match is gonna be, Passwords must match. 8:25
Okay. 8:32
Close our validators, close our password field. 8:33
And let's actually go ahead and write password2 before we go add our import. 8:35
So password2, hey there it is, is also a PasswordField. 8:39
And it will say Confirm Password. 8:45
And really we could leave this one completely alone, but 8:50
I do wanna add one validator to this of DataRequired. 8:54
Just to make sure that they fill in some data on that. 9:00
So we need to import PasswordField from wtforms. 9:05
And we need to import Length and EqualTo from our validator. 9:09
So StringField PasswordField. 9:15
And then here, we're gonna say Length and EqualTo. 9:18
And that is our form. 9:23
That is a long, long form. 9:26
Wow! 9:29
There's a lot to building a form, 9:29
at least one that does all the stuff that we want it to do. 9:31
Knowing how to customize validation will go a long way when you start building your 9:34
own forms, though. 9:38 | https://teamtreehouse.com/library/flaskwtf-forms | CC-MAIN-2021-39 | refinedweb | 2,004 | 93.74 |
Copyright © 2014 W3C® (MIT, ERCIM, Keio, Beihang), 11 February participating in discussions that resulted in changes to the document: David Dailey,.
A bounding bounding box is the tightest fitting rectangle aligned with the axes of that element's user coordinate system that entirely encloses it and its descendants. There are three kinds of bounding boxes that can be computed for an element: the object bounding box, the stroke bounding box and the decorated bounding box. See Bounding boxes for a more detailed description of these bounding boxes and how they are computed.
Should gradient elements also be context elements?.
This chapter is a bit waffley. How much of this do we really need to say?.
We should reference the SVG Integration specification here, once that has been published. an SVG document fragment have an implicit drawing order, with the first elements in the SVG document fragment getting "painted" first. Subsequent elements are painted on top of previously painted elements.
Grouping elements, such as the ‘g’ element (see container elements) create a compositing group. The compositing group will composite and blend with the group backdrop with behaviour depending on the values of the compositing and blending properties, such as knock-out, and isolation. See Compositing and Blending Specification..
The basic type <anything> is a sequence of zero or more characters. Specifically:
anything ::= Char*
where Char is the production for a character, as defined in XML 1.0 ([XML10], section 2.2).).
A gradient as defined by CSS Level 3 Image
Values [CSS3IMAGES] and can be used
as paint server for the properties ‘
fill’ and ‘
stroke’. Percentage values get resolved
against the bounding box of the element to which the gradient is applied.
An <icccolor> is an ICC color specification. In SVG 1.1, an ICC color specification is given by a name, which references an @color-profile rule, and one or more color component values. The grammar is as follows:
icccolor ::= "icc-color(" author-ident (comma-wsp number)+ ")".
We should disentangle lengths and percentages. xmlbase; readonly attribute SVGAnimatedString className; readonly attribute CSSStyleDeclaration style; attribute DOMString xmllang; attribute DOMString xmlspace; readonly attribute SVGSVGElement? ownerSVGElement; readonly attribute SVGElement? viewportElement; readonly attribute long tabIndex; void focus(); void blur(); }; SVGElement implements GlobalEventHandlers; should add accessors for the
ch,
rem,
vw,
vh,
vmin
and
vmax units once we support css3-values more fully.
Since SVGAnimatedLength objects can represent percentage values too, what should we name the accessor for that unit?
Should we add a string accessor, perhaps named
asString or
value, to avoid having to write for example
rect.x.baseVal.valueAsString?
This interface defines a list of SVGLength objects.
SVGLengthList has the same attributes and methods as other SVGxxxList interfaces. Implementers may consider using a single base class to implement the various; };
If any changes to the unit accessors are made to SVGAnimatedLength they should be made here too..
[Constructor, Constructor(float x, float y, float width, float height)] interface SVGRect { attribute float x; attribute float y; attribute float width; attribute float height; };
Used for attributes of type SVGRect which can be animated.; readonly attribute SVGElement? nearestViewportElement; readonly attribute SVGElement? farthestViewportElement; SVGRect getBBox(optional SVGBoundingBoxOptions options); SVGMatrix? getCTM(); SVGMatrix? getScreenCTM(); SVGMatViewportElement. Note that null is returned if this element is not hooked into the document tree.GeometryElement represents SVG elements whose rendering is defined by geometry and which can be filled and stroked. This includes paths, text and the basic shapes.
interface SVGGeometryElement : SVGGraphicsElement { bool isPointInFill(SVGPoint point); bool isPointInStroke(SVG the ‘rendering-intent’ descriptor on an @color-profile rule.
:
Indicates the SVG language version to which this document fragment conforms.
In SVG 1.0 [SVG10], this attribute was fixed to the value '1.0'. For SVG 1.1, the attribute should have the value '1.1'.
What are we doing with the ‘version’ attribute? It's not clear whether it is useful to keep.
Describes the minimum SVG language profile that the author believes is necessary to correctly render the content. The attribute does not specify any processing restrictions; It can be considered metadata. For example, the value of the attribute could be used by an authoring tool to warn the user when they are modifying the document beyond the scope of the specified base profile. Each SVG profile should define the text that is appropriate for this attribute.
It's unlikely SVG 2 will have profiles as 1.0 and 1.1 did. Do we keep the attribute in case others wish to profile SVG? (Or should we be discouraging that?)
The ‘x’ and ‘y’ attributes specify the top-left corner of the rectangular region into which an embedded ‘svg’ element is placed. On an outermost svg element, these attributes have no effect.
For outermost svg elements, the ‘width’ and ‘height’ attributes specify the intrinsice:
This attribute may be harmonized and/or replaced with the work done as part of the Web Animation specification..
Attribute values have the following meanings:
loadevent for the rootmost ‘svg’ element is triggered.
What about when the SVG document fragment is within
an XHTML document? Is there a single timeline for the whole document, and if so,
does it start at the parse time for the first
<svg> start tag?
What about when using the HTML parser? above paragraphs feel out of place just after the list of attributes specific to ‘svg’..
That generously structured content with ‘title’ and ‘desc’ is more accessible isn't necessarily true. It also seems like a stretch to claim that documents "rich in structure" can be rendered as speech or braille, without specific references to how that can be achieved. More fundamental uses of grouping that should be mentioned are (a) for specifying common styling of inherited properties, and (b) for selecting elements to apply a group effect like filters and group opacity.>
This is not a particularly useful example.
Any element that is not contained within a ‘g’ is treated (at least conceptually) as if it were in its own group.
It is unclear what this sentence actually means. Does it mean that all operations that apply to groups (such as group opacity, filter effects, etc.) can apply to single elements too? If so, then it should say that..
Again this claim about accessibility is dubious.
We should have a term for definition elements (since we now have a corresponding IDL interface) and reference it here.:
Is this really about efficiency of implementations? If anything, it looks like it is ensuring progressively rendered documents don't make forward references that would otherwise cause an incorrect rendering before the referenced element is loaded.
<.
Would this element be better as part of the Animation chapter? It also needs to be a member of the element categories that other animation elements are, and an IDL interface needs to be written for it.
Need to define SVGDiscardElement DOM interface for ‘discard’ element..
I don't think it is easy to use a style sheet to cause an element's ‘title’ to be rendered in place of its graphics..
'lang' should be defined here (rather than pointing to the glyph definition).>
We should say what purpose including other-namespaced markup in ‘title’ and ‘desc’ has. If it is just that these are basically metadata extension points for other profiles or uses of SVG, then we should say that..
Again this mention of accessibility through the use of structure (this time with ‘symbol’ elements). We should include an example here or in the Accessibility appendix that shows how this is the case and what the actual effects of structuring content with ‘symbol’ are..
Should reference Shadow DOM for the event handling. Note that events will be retargeted to maintain the encapsulation, ie. not to leak the original target inside a shadow tree..
Animations on a referenced element will cause the instances to also be animated.
A ‘use’ element has the same visual effect as if the ‘use’ element were replaced by the following generated content:
Except that the replaced content shouldn't affect how styles are matched. IRI processing of ‘script’.
The value is a list of IRI:
Need a grammar for name.
Standard XML attribute for assigning a unique name to an element. Refer to the Extensible Markup Language (XML) 1.0 Recommendation [XML10].
Specifies a base IRI other than the base IRI.
Elements that might contain character data content have attributes ‘xml:lang’ and ‘xml:space’.
Should we be moving ‘lang’ instead of ‘xlink:lang’?
Need a grammar for languageID. 'default' and 'preserve'. Refer to the Extensible Markup Language (XML) 1.0 Recommendation [XML10] and to the discussion white space handling in SVG.
New content should use the ‘
white-space’ property instead. role value is a set of white-space separated machine-extractable semantic information used to define the purpose of the element.
The "Value" entry in the attribute definition box above should be a grammar, not a sentence. Maybe we can define a symbol <role> by reference to the ARIA specification, and then define the attribute as taking "role+".
The lacuna value for the ‘role’ attribute langauges ARIA User Agent Implementation Guide specifications. [ARIA] [ARIAIM below are already defined in HTML, and in implementations that support SVG and HTML we they cannot be duplicated.
The title, referrer, domain and activeElement IDL attributes must behave the same as the corresponding IDL attributes defined in HTML.
Issues have been filed on HTML so that title and activeElement work on SVG documents (by looking at ‘title’ elements in the SVG namespace, and by defaulting to the root ‘svg’ element rather than the body element, respectively)..
Should this and the next three IDL attributes be removed? Are they implemented?
The definition of the initial view (i.e., before magnification and panning) of the current innermost SVGPoint at the coordinates (0, 0).
Should this method be neutered as suspendRedraw and friends have been? Do implementations actually support painting in the middle of a running script by calling this method?
pointer-events’ processing.
pointer-events’ processing.
pointer-events’ processing.
pointer-events’ processing.
What is a type-in bar? Do we need
deselectAll given
we have DOM Selection?
Creates an SVGTransform object outside of any document trees. The object is initialized to the given matrix transform (i.e., SVG_TRANSFORM_MATRIX). The values from the parameter matrix are copied, the matrix parameter is not adopted as SVGTransform::matrix.
Do we need this? If so, can we define it in terms of calling Document.getElementById and checking whether the returned element is within the subtree?
interface SVGGElement : SVGGraphicsElement { };
interface SVGDefsElement : SVGGraphicsElement { };
interface SVGDescElement :width’ or ‘height’. Note alsowidth’ and ‘height’.
This returns a bounding box even if fill is false. Is this what we want?.
Do we need this section? Should we instead have a guide on how other specifications should re-use specific attributes or elements?.
[Constructor, Constructor(float x, float y)](); SVGPoint initialize(SVGPoint newItem); getter); setter void (unsigned long index,]
[Constructor, Constructor(float a, float b, float c, float d, float e, float.
[Constructor, Constructor(SVGMatrix CSS Transforms specification does not have a grammar for <transform-function> yet. Value in the table above should be a link to a datatype for path data.).
These three groups of commands draw curves:.
What should we do about the SVGPathSeg objects for these new path bearing: ( "B" | "b") wsp* bearing-argument-sequence bearing-argument-sequence: number | number comma-wsp? bearing; }; | http://www.w3.org/TR/2014/WD-SVG2-20140211/single-page.html | CC-MAIN-2018-39 | refinedweb | 1,886 | 57.67 |
Question:
I am writing a LINQ provider to a hierarchal data source. I find it easiest to design my API by writing examples showing how I want to use it, and then coding to support those use cases.
One thing I am having trouble with is an easy/reusable/elegant way to express "deep query" or recursion in a LINQ statement. In other words, what is the best way to distinguish between:
from item in immediate-descendants-of-current-node where ... select item
versus:
from item in all-descendants-of-current-node where ... select item
(Edit: please note neither of those examples above necessarily reflect the structure of the query I want. I am interested in any good way to express recursion/depth)
Please note I am not asking how to implement such a provider, or how to write my IQueryable or IEnumerable in such a way that allows recursion. I am asking from the standpoint of a person writing the LINQ query and utilizing my provider - what is an intuitive way for them to express whether they want to recurse or not?
The data structure resembles a typical file system: a folder can contain a collection of subfolders, and a folder can also contain a collection of items. So myFolder.Folders represents all the folders who are immediate children of myFolder, and myFolder.Items contains all the items immediately within myFolder. Here's a basic example of a site hierachy, much like a filesystem with folders and pages:
(F)Products (F)Light Trucks (F)Z150 (I)Pictures (I)Specs (I)Reviews (F)Z250 (I)Pictures (I)Specs (I)Reviews (F)Z350 (I)Pictures (I)Specs (I)Reviews (I)Splash Page (F)Heavy Trucks (F)Consumer Vehicles (I)Overview
If I write:
from item in lightTrucks.Items where item.Title == "Pictures" select item
What is the most intuitive way to express an intent that the query get all items underneath Light Trucks, or only the immediate ones? The least-intrusive, lowest-friction way to distinguish between the two intents?
My #1 goal is to be able to turn this LINQ provider over to other developers who have an average understanding of LINQ and allow them to write both recursive and list queries without giving them a tutorial on writing recursive lambdas. Given a usage that looks good, I can code the provider against that.
Additional clarification: (I am really sucking at communicating this!) - This LINQ provider is to an external system, it is not simply walking an object graph, nor in this specific case does a recursive expression actually translate into any kind of true recursive activity under the hood. Just need a way to distinguish between a "deep" query and a "shallow" one.
So, what do you think is the best way to express it? Or is there a standard way of expressing it that I've missed out on?
Solution:1
Linq-toXml handles this fine, there is an XElement.Elements()/.Nodes() operation to get immediate children, and a XElement.Descendents()/DescendentNodes() operations to get all descendents. Would you consider that as an example?
To summarize Linq-to-Xml's behavior... The navigation functions each correspond to an axis type in XPath (). If the navigation function selects Elements, the axis name is used. If the navigation function selects Nodes, the axis name is used with Node appended.
For instance, there are functions Descendants() and DescendantsNode() correspond to XPath's descendants axis, returning either an XElement or an XNode.
The exception case is not surprisingly the most used case, the children axis. In XPath, this is the axis used if no axis is specified. For this, the linq-to-xml navigation functions are not Children() and ChildrenNodes() but rather Elements() and Nodes().
XElement is a subtype of XNode. XNode's include things like HTML tags, but also HTML comments, cdata or text. XElements are a type of XNode, but refer specifically to HTML tags. XElements therefore have a tag name, and support the navigation functions.
Now its not as easy to chain navigations in Linq-to-XML as it is XPath. The problem is that navigation functions return collection objects, while the navigation functions are applied to non-collections. Consider the XPath expression which selects a table tag as an immediate child then any descendant table data tag. I think this would look like "./children::table/descendants::td" or "./table/descendants::td"
Using IEnumerable<>::SelectMany() allows one to call the navigation functions on a collection. The equivalent to the above looks something like .Elements("table").SelectMany(T => T.Descendants("td"))
Solution:2
Well, the first thing to note is that actually, lambda expressions can be recursive. No, honestly! It isn't easy to do, and certainly isn't easy to read - heck, most LINQ providers (except LINQ-to-Objects, which is much simpler) will have a coughing fit just looking at it... but it is possible. See here for the full, gory details (warning - brain-ache is likely).
However!! That probably won't help much... for a practical approach, I'd look at the way
XElement etc does it... note you can remove some of the recursion using a
Queue<T> or
Stack<T>:
using System; using System.Collections.Generic; static class Program { static void Main() { Node a = new Node("a"), b = new Node("b") { Children = {a}}, c = new Node("c") { Children = {b}}; foreach (Node node in c.Descendents()) { Console.WriteLine(node.Name); } } } class Node { // very simplified; no sanity checking etc public string Name { get; private set; } public List<Node> Children { get; private set; } public Node(string name) { Name = name; Children = new List<Node>(); } } static class NodeExtensions { public static IEnumerable<Node> Descendents(this Node node) { if (node == null) throw new ArgumentNullException("node"); if(node.Children.Count > 0) { foreach (Node child in node.Children) { yield return child; foreach (Node desc in Descendents(child)) { yield return desc; } } } } }
An alternative would be to write something like
SelectDeep (to mimic
SelectMany for single levels):
public static class EnumerableExtensions { public static IEnumerable<T> SelectDeep<T>( this IEnumerable<T> source, Func<T, IEnumerable<T>> selector) { foreach (T item in source) { yield return item; foreach (T subItem in SelectDeep(selector(item),selector)) { yield return subItem; } } } } public static class NodeExtensions { public static IEnumerable<Node> Descendents(this Node node) { if (node == null) throw new ArgumentNullException("node"); return node.Children.SelectDeep(n => n.Children); } }
Again, I haven't optimised this to avoid recursion, but it could be done easily enough.
Solution:3
I'd go with implementing it in such a way as to have control over how deeply I want to query as well.
Something like Descendants() would retrieve Descendants through all levels while Descendants(0) would retrieve immediate children, Descendants(1) would get children and grandchildren and so on...
Solution:4
I would just implement two functions to clearly differentiate between the two options (Children vs. FullDecendants), or an overload GetChildren(bool returnDecendants). Each can implement IEnumerable, so it would just be a matter of which function they pass into their LINQ statement.
Solution:5
You might want to implement a (extension) Method like FlattenRecusively for your type.
from item in list.FlattenRecusively() where ... select item
Solution:6
Rex, you've certainly opened an interesting discussion, but you seem to have eliminated all possibilities - that is, you seem to reject both (1) having the consumer write recursive logic, and (2) having your node class expose relationships of greater than one degree.
Or, perhaps you haven't entirely ruled out (2). I can think of one more approach which is nearly as expressive as the GetDescendents method (or property), but might not be quite so 'ponderous' (depending on the shape of your tree)...
from item in AllItems where item.Parent == currentNode select item
and
from item in AllItems where item.Ancestors.Contains(currentNode) select item
Solution:7
I'd have to agree with Frank. have a look at how LINQ-to-XML handles these scenarios.
In fact, I'd emulate the LINQ-to-XML implementation entirely, but change it for any Data type. Why reinvent the wheel right?
Solution:8
Are you okay with doing the heavy lifting in your object? (it's not even that heavy)
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace LinqRecursion { class Program { static void Main(string[] args) { Person mom = new Person() { Name = "Karen" }; Person me = new Person(mom) { Name = "Matt" }; Person youngerBrother = new Person(mom) { Name = "Robbie" }; Person olderBrother = new Person(mom) { Name = "Kevin" }; Person nephew1 = new Person(olderBrother) { Name = "Seth" }; Person nephew2 = new Person(olderBrother) { Name = "Bradon" }; Person olderSister = new Person(mom) { Name = "Michelle" }; Console.WriteLine("\tAll"); // All //Karen 0 //Matt 1 //Robbie 2 //Kevin 3 //Seth 4 //Bradon 5 //Michelle 6 foreach (var item in mom) Console.WriteLine(item); Console.WriteLine("\r\n\tOdds"); // Odds //Matt 1 //Kevin 3 //Bradon 5 var odds = mom.Where(p => p.ID % 2 == 1); foreach (var item in odds) Console.WriteLine(item); Console.WriteLine("\r\n\tEvens"); // Evens //Karen 0 //Robbie 2 //Seth 4 //Michelle 6 var evens = mom.Where(p => p.ID % 2 == 0); foreach (var item in evens) Console.WriteLine(item); Console.ReadLine(); } } public class Person : IEnumerable<Person> { private static int _idRoot; public Person() { _id = _idRoot++; } public Person(Person parent) : this() { Parent = parent; parent.Children.Add(this); } private int _id; public int ID { get { return _id; } } public string Name { get; set; } public Person Parent { get; private set; } private List<Person> _children; public List<Person> Children { get { if (_children == null) _children = new List<Person>(); return _children; } } public override string ToString() { return Name + " " + _id.ToString(); } #region IEnumerable<Person> Members public IEnumerator<Person> GetEnumerator() { yield return this; foreach (var child in this.Children) foreach (var item in child) yield return item; }
« Prev Post
Next Post »
EmoticonEmoticon | http://www.toontricks.com/2018/05/tutorial-expressing-recursion-in-linq.html | CC-MAIN-2018-34 | refinedweb | 1,616 | 54.52 |
idk i cant read it
Type: Posts; User: Java Sucks
idk i cant read it
Turn on your speakers
To get resources you need to go and get a shovel. You can dig down and collect the rocks and stuff. Thats what i do in minecraft. Thank me if i helped :D
oh sorry. I just thought that everything would be easier if you do C++ first
i have no idea what your saying. Can you noob it down please?
You need to learn C++ before you can even do any of this
i want to make a game and i am stuck. It is not working so i need help fixing it. Will thanks anyone who can help
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public... | http://www.javaprogrammingforums.com/search.php?s=f57f4624c4a2fbcd23d61a4fe2965192&searchid=1371068 | CC-MAIN-2015-06 | refinedweb | 130 | 91.11 |
Blocking Transitions
Let's explore how to block transitions. We are going to make it so that if we change any user information when adding or editing a user, the application will block any transitions away until we confirm that we want to transition away. For example, imagine we change some info and then want to cancel. It's just a way to make sure a user doesn't accidentally lose their work.
We get this functionality by using the
Prompt component that ships with
react-router-dom. Let's first add the prompt to the
UserForm component. Place this at the top of the
Form component returned from the
render method.
<Prompt message="Are you sure you wanna do that?" />
We have created a
Prompt and given it a prop of
message. This will be the message the user sees when the prompt shows.
Also make sure to import the
Prompt component into this file.
import { Prompt } from 'react-router-dom';
Now if you go to an edit page and then press the cancel button, the prompt will show up! However, we only want it to show up if we change some information in the form. Luckily, we can pass the
Prompt component a
when prop. When this is
true, it will then show the prompt when a transition is attempted. If it's false, it won't show it. This means we need a variable in state that tracks whether information has been updated. This is easy since we have a single method that runs whenever an input is updated.
Inside
UserForm, update the creation of state in the
constructor method.
this.state = { user, formChanged: false };
Next, inside
handleChange, make sure state is updated so we know the form data has been changed.
handleChange(e, { name, value }) { const { user } = this.state; this.setState({ user: { ...user, [name]: value }, formChanged: true, }); }
Pull this
formChanged piece of state out of state in the
render method.
const { user: { name, email, phone, address, city, zip }, formChanged } = this.state;
Lastly, pass the value of
formChanged as the
when prop to the
Prompt component we just created.
<Prompt when={formChanged}
Now, try changing some data in an edit form and see what happens. The prompt shows up like before. Now reload that page and just click on the "Cancel" button. It doesn't show the prompt! Awesome! That wasn't too bad.
In the next video, we will discuss how we can show multiple routes that both match in separate areas. | https://scotch.io/courses/using-react-router-4/blocking-transitions | CC-MAIN-2018-05 | refinedweb | 416 | 75 |
How to dynamically define the name and version of a package¶
The
name and
version fields are used to define constant values. The
set_name() and
set_version()
methods can be used to dynamically define those values, for example if we want to extract the version from a text
file or from the git repository.
The version of a recipe is stored in the package metadata when it is exported (or created) and always taken from
the metadata later on. This means that the
set_name() and
set_version() methods will not be executed once
the recipe is in the cache, or when it is installed from a server. Both methods will use the current folder as
the current working directory to resolve relative paths. To define paths relative to the location of the conanfile.py
use the
self.recipe_folder attribute.
How to capture package version from SCM: git¶
The
Git() helper from tools can be used to capture data from the Git repo in which
the conanfile.py recipe resides, and use it to define the version of the Conan package.
from conans import ConanFile, tools class HelloConan(ConanFile): name = "hello" def set_version(self): git = tools.Git(folder=self.recipe_folder) self.version = "%s_%s" % (git.get_branch(), git.get_revision()) def build(self): ...
In this example, the package created with conan create will be called
hello/branch_commit@user/channel.
How to capture package version from SCM: svn¶
The
SVN() helper from tools can be used to capture data from the subversion repo in which
the conanfile.py recipe resides, and use it to define the version of the Conan package.
from conans import ConanFile, tools class HelloLibrary(ConanFile): name = "hello" def set_version(self): scm = tools.SVN(folder=self.recipe_folder) revision = scm.get_revision() branch = scm.get_branch() # Delivers e.g trunk, tags/v1.0.0, branches/my_branch branch = branch.replace("/","_") if scm.is_pristine(): dirty = "" else: dirty = ".dirty" self.version = "%s-%s+%s%s" % (version, revision, branch, dirty) # e.g. 1.2.0-1234+trunk.dirty def build(self): ...
In this example, the package created with conan create will be called
hello/generated_version@user/channel. Note: this function should never raise, see the section
about when the version is computed and saved above.
How to capture package version from text or build files¶
It is common that a library version number would be already encoded in a text file, build scripts, etc. As an example, let’s assume we have the following library layout, and that we want to create a package from it:
conanfile.py CMakeLists.txt src hello.cpp ...
The CMakeLists.txt will have some variables to define the library version number. For simplicity, let’s also assume that it includes a line such as the following:
cmake_minimum_required(VERSION 2.8) set(MY_LIBRARY_VERSION 1.2.3) # This is the version we want add_library(hello src/hello.cpp)
You can extract the version dynamically using:
from conans import ConanFile from conans.tools import load import re, os class HelloConan(ConanFile): name = "hello" def set_version(self): content = load(os.path.join(self.recipe_folder, "CMakeLists.txt")) version = re.search(b"set\(MY_LIBRARY_VERSION (.*)\)", content).group(1) self.version = version.strip() | https://docs.conan.io/en/1.26/howtos/capture_version.html | CC-MAIN-2020-40 | refinedweb | 521 | 50.94 |
So I finally got the main part of my code working... have to simulate a robot taking random steps but now i cant figure out how to get the average of steps he took throughout the whole code
any ideas? i need to add the amount of steps taken per simulation, and im really not sure how.any ideas? i need to add the amount of steps taken per simulation, and im really not sure how.Code Java:
public class Robot { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int n=20; int steps=simulation(n); simulation(n); //Calls the simulation method } public static int steps(int n){ //Start of method steps int total = 0; //initalizing total for (int i=0;i<=n;i++){ //incremental for loop int steps = (int) (5 * Math.random()) - 1;//determines the random number of steps total = total+steps; //adds the steps per try }return total; //returns the total number of steps } public static int simulation(int n){//Star of metod simulation int steps=0; for(int i=1;i<=n;i++){ //incremental for loop System.out.println("on simulation "+i+" the robot walked " //prints out the sim number total steps and in how many tries +steps(n)+" in "+n+" tries"); steps= steps(n); }return steps; } } | http://www.javaprogrammingforums.com/%20whats-wrong-my-code/5451-stuck-help-please-printingthethread.html | CC-MAIN-2015-48 | refinedweb | 215 | 52.94 |
Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+. This tutorial was first published in February, 2010.
Twice a month, we revisit some of our readers’ favorite posts from throughout the history of Activetuts+. This tutorial was first published in February, 2010.
In this tutorial I will demonstrate a technique I use to protect code and assets from theft.
Decompilers are a real worry for people who create Flash content. You can put a lot of effort into creating the best game out there, then someone can steal it, replace the logo and put it on their site without asking you. How? Using a Flash Decompiler. Unless you put some protection over your SWF it can be decompiled with a push of a button and the decompiler will output readable source code.
Before We Begin
I used a small project of mine to demonstrate how vulnerable SWFs are to decompilation. You can download it and test yourself via the source link above. I used Sothink SWF Decompiler 5 to decompile the SWF and look under its hood. The code is quite readable and you can understand and reuse it fairly easily.
What Can We do About it?
I came up with a technique for protecting SWFs from decompilers and I'm going to demonstrate it in this tutorial. We should be able to produce this:
The code that is decompiled is actually the code for decrypting the content and has nothing to do with your main code. Additionally, the names are illegal so it won't compile back. Try to decompile it yourself.
Before we get going, I want to point out that this tutorial is not suitable for beginners and you should have solid knowledge of AS3 if you want to follow along. This tutorial is also about low level programming that involves bytes, ByteArrays and manipulating SWF files with a hex editor.
Here's what we need:
- A SWF to protect. Feel free to download the SWF I'll be working on.
- Flex SDK. We will be using it to embed content using the Embed tag. You can download it from opensource.adobe.com.
- A hex editor. I'll be using a free editor called Hex-Ed. You can download it from nielshorn.net or you can use an editor of your choice.
- A decompiler. Whilst not necessary, it would be nice to check if our protection actually works. You can grab a trial of Sothink SWF Decompiler from sothink.com
Step 1: Load SWF at Runtime
Open a new ActionScript 3.0 project, and set it to compile with Flex SDK (I use FlashDevelop to write code). Choose a SWF you want to protect and embed it as binary data using the Embed tag:
[Embed (source = "VerletCloth.swf", mimeType = "application/octet-stream")] // source = path to the swf you want to protect private var content:Class;
Now the SWF is embedded as a ByteArray into the loader SWF and it can be loaded through Loader.loadBytes().
var loader:Loader = new Loader(); addChild(loader); loader.loadBytes(new content(), new LoaderContext(false, new ApplicationDomain()));
In the end we should have this code:
package { import flash.display.Loader; import flash.display.Sprite; import flash.system.ApplicationDomain; import flash.system.LoaderContext; [SWF (width = 640, height = 423)] //the dimensions should be same as the loaded swf's public class Main extends Sprite { [Embed (source = "VerletCloth.swf", mimeType = "application/octet-stream")] // source = path to the swf you want to protect private var content:Class; public function Main():void { var loader:Loader = new Loader(); addChild(loader); loader.loadBytes(new content(), new LoaderContext(false, new ApplicationDomain())); } } }
Compile and see if it works (it should). From now on I will call the embedded SWF the "protected SWF", and the SWF we just compiled the "loading SWF".
Step 2: Analyze the Result
Let's try to decompile and see if it works.
Yey! The assets and the original code are gone! What's shown now is the code that loads the protected SWF and not its content. This would probably stop most of the first-time attackers who are not too familiar with Flash but it's still not good enough to protect your work from skilled attackers because the protected SWF is waiting for them untouched inside the loading SWF.
Step 3: Decompressing the SWF
Let's open the loading SWF with a hex editor:
It should look like random binary data because it's compressed and it should begin with ASCII "CWS". We need to decompress it! (If your SWF begins with "FWS" and you see meaningful strings in the SWF it's likely that it didn't get compressed. You have to enable compression to follow along).
At first it might sound difficult but it's not. The SWF format is an open format and there is a document that describes it. Download it from adobe.com and scroll down to page 25 in the document. There is a description of the header and how the SWF is compressed, so we can uncompress it easily.
What is written there is that the first 3 bytes are a signature (CWS or FWS), the next byte is the Flash version, the next 4 bytes are the size of the SWF. The remaining is compressed if the signature is CWS or uncompressed if the signature is FWS. Let's write a simple function to decompress a SWF:; }
The function does a few things:
- It reads the uncompressed header (the first 8 bytes) without the signature and remembers it.
- It reads the rest of the data and uncompresses it.
- It writes back the header (with the "FWS" signature) and the uncompressed data, creating a new, uncompressed SWF.
Step 4: Creating a Utility
Next we'll create a handy utility in Flash for compressing and decompressing SWF files. In a new AS3 project, compile the following class as a document class:
package { import flash.display.Sprite; import flash.events.Event; import flash.net.FileFilter; import flash.net.FileReference; import flash.utils.ByteArray; public class Compressor extends Sprite { private var ref:FileReference; public function Compressor() { ref = new FileReference(); ref.addEventListener(Event.SELECT, load); ref.browse([new FileFilter("SWF Files", "*.swf")]); } private function load(e:Event):void { ref.addEventListener(Event.COMPLETE, processSWF); ref.load(); } private function processSWF(e:Event):void { var swf:ByteArray; switch(ref.data.readMultiByte(3, "us-ascii")) { case "CWS": swf = decompress(ref.data); break; case "FWS": swf = compress(ref.data); break; default: throw Error("Not SWF..."); break; } new FileReference().save(swf); } private function compress(data:ByteArray):ByteArray { var header:ByteArray = new ByteArray(); var decompressed:ByteArray = new ByteArray(); var compressed:ByteArray = new ByteArray(); header.writeBytes(data, 3, 5); //read the header, excluding the signature decompressed.writeBytes(data, 8); //read the rest decompressed.compress(); compressed.writeMultiByte("CWS", "us-ascii"); //mark as compressed compressed.writeBytes(header); compressed.writeBytes(decompressed); return compressed; }; } } }
As you probably noticed I've added 2 things: File loading and the compress function.
The compress function is identical to the decompress function, but in reverse. The file loading is done using FileReference (FP10 required) and the loaded file is either compressed or uncompressed. Note that you have to run the SWF locally from a standalone player, as FileReference.browse() must be invoked by user interaction (but the local standalone player allows to run it without).
Step 5: Uncompressing the Loading SWF
To test the tool, fire it up, select the loading SWF and choose where to save it. Then open it up with a hex editor and scrub through. You should see ascii strings inside like this:
Step 6: Analyze Again
Let's return back to step 2. While the decompiler didn't show any useful info about the protected SWF, it's quite easy to get the SWF from the now uncompressed loader; just search for the signature "CWS" (if the protected SWF is uncompressed search for "FWS") and see the results:
What we found is a DefineBinaryData tag that contains the protected SWF, and extracting it from there is a piece of cake. We are about to add another layer of protection over the loading SWF : Encryption.
Step 7: Encryption
To make the protected SWF less "accessible" we will add some kind of encryption. I chose to use as3crypto and you can download it from code.google.com. You can use any library you want instead (or your own implementation, even better), the only requirement is that it should be able to encrypt and decrypt binary data using a key.
Step 8: Encrypting Data
The first thing we want to do is write a utility to encrypt the protected SWF before we embed it. It requires very basic knowledge of the as3crypto library and it's pretty straightforward. Add the library into your library path and let's begin by writing the following:
var aes:AESKey = new AESKey(binKey); var bytesToEncrypt:int = (data.length & ~15); //make sure that it can be devided by 16, zero the last 4 bytes for (var i:int = 0; i < bytesToEncrypt; i += 16) aes.encrypt(data, i);
What's going on here? We use a class from as3crypto called AESKey to encrypt the content. The class encrypts 16 bytes in a time (128-bit), and we have to for-loop over the data to encrypt it all. Note the second line : data.length & ~15. It makes sure that the number of bytes encrypted can be divided by 16 and we don't run out of data when calling aes.encrypt().
Note: It's important to understand the point of encryption in this case. It's not really encryption, but rather obfuscation since we include the key inside the SWF. The purpose is to turn the data into binary rubbish, and the code above does it's job, although it can leave up to 15 unencrypted bytes (which doesn't matter in our case). I'm not a cryptographer, and I'm quite sure that the above code could look lame and weak from a cryptographer's perspective, but as I said it's quite irrelevant as we include the key inside the SWF.
Step 9: Encryption Utility
Time to create another utility that will help us encrypt SWF files. It's almost the same as the compressor we created earlier, so I won't talk much about it. Compile it in a new project as a document class:
package { import com.hurlant.crypto.symmetric.AESKey; import flash.display.Sprite; import flash.events.Event; import flash.net.FileReference; import flash.utils.ByteArray; public class Encryptor extends Sprite { private var key:String = "activetuts"; //I hardcoded the key private var ref:FileReference; public function Encryptor() { ref = new FileReference(); ref.addEventListener(Event.SELECT, load); ref.browse(); } private function load(e:Event):void { ref.addEventListener(Event.COMPLETE, encrypt); ref.load(); } private function encrypt(e:Event):void { var data:ByteArray = ref.data; var binKey:ByteArray = new ByteArray(); binKey.writeUTF(key); //AESKey requires binary key var aes:AESKey = new AESKey(binKey); var bytesToEncrypt:int = (data.length & ~15); //make sure that it can be divided by 16, zero the last 4 bytes for (var i:int = 0; i < bytesToEncrypt; i += 16) aes.encrypt(data, i); new FileReference().save(data); } } }
Now run it, and make an encrypted copy of the protected SWF by selecting it first and then saving it under a different name.
Step 10: Modifying the Loader
Return back to the loading SWF project. Because the content is now encrypted we need to modify the loading SWF and add decryption code into it. Don't forget to change the src in the Embed tag to point to the encrypted SWF.
package { import com.hurlant.crypto.symmetric.AESKey; import flash.display.Loader; import flash.display.Sprite; import flash.system.ApplicationDomain; import flash.system.LoaderContext; import flash.utils.ByteArray; [SWF (width = 640, height = 423)] //the dimensions should be same as the loaded swf's public class Main extends Sprite { [Embed (source = "VerletClothEn.swf", mimeType = "application/octet-stream")] // source = path to the swf you want to protect private var content:Class; private var key:String = "activetuts"; public function Main():void { var data:ByteArray = new content(); var binKey:ByteArray = new ByteArray(); binKey.writeUTF(key); //AESKey requires binary key var aes:AESKey = new AESKey(binKey); var bytesToDecrypt:int = (data.length & ~15); //make sure that it can be divided by 16, zero the last 4 bytes for (var i:int = 0; i < bytesToDecrypt; i += 16) aes.decrypt(data, i); var loader:Loader = new Loader(); addChild(loader); loader.loadBytes(data, new LoaderContext(false, new ApplicationDomain())); } } }
This is the same as before except with the decryption code stuck in the middle. Now compile the loading SWF and test if it works. If you followed carefully up to now, the protected SWF should load and display without errors.
Step 11: Look Inside Using a Decompiler
Open the new loading SWF with a decompiler and have a look.
It contains over a thousand lines of tough looking encryption code, and it's probably harder to get the protected SWF out of it. We've added a few more steps the attacker must undertake:
- He (or she) has to find the DefineBinaryData that holds the encrypted content and extract it.
- He must create a utility to decrypt it.
The problem is that creating a utility is as simple as copy-pasting from the decompiler into the code editor and tweaking the code a little bit. I tried to break my protection myself, and it was quite easy - I managed to do it in about 5 minutes. So we're going to have to take some measurements against it.
Step 12: String Obfuscation
First we'd put the protected SWF into the loading SWF, then encrypted it, and now we'll put the final touches to the loading SWF. We'll rename classes, functions and variables to illegal names.
By saying illegal names I mean names such as ,;!@@,^#^ and (^_^). The cool thing is that this matters to the compiler but not to the Flash Player. When the compiler encounters illegal characters inside identifiers, it fails to parse them and thus the project fails to compile. On the other hand, the Player doesn't have any problems with those illegal names. We can compile the SWF with legal identifiers, decompress it and rename them to a bunch of meaningless illegal symbols. The decompiler will output illegal code and the attacker will have to go over the hundreds of lines of code manually, removing illegal identifiers before he can compile it. He deserves it!
This is how it looks before any string obfuscation:
Let's start! Decompress the loading SWF using the utility we created before and fire up a hex editor.
Step 13: Your First Obfuscation
Let's try to rename the document class. Assuming you've left the original name (Main), let's search for it in the uncompressed loader SWF with a hex editor:
Rename "Main" to ;;;;. Now search for other "Main"s and rename them to ;;;; too.
When renaming make sure that you don't rename unnecessary strings or the SWF will not run.
Save and run the SWF. It works! And look what the decompiler says:
Victory!! :)
Step 14: Renaming the Rest of the Classes
Keep renaming the rest of your classes. Choose a class name and search for it, replacing it with illegal symbols until you reach the end of the file. As I said, the most important thing here is to use your common sense, make sure you don't mess your SWF up. After renaming the classes you can start renaming the packages. Note that when renaming a package, you can erase the periods too and make it one long illegal package name. Look what I made:
After you finish renaming the classes and the packages, you can start renaming functions and variables. They are even easier to rename as they usually appear only once, in one large cloud. Again, make sure you rename only "your" methods and not the built-in Flash methods. Make sure you don't wipe out the key ("activetuts" in our case).
Step 15: Compress the SWF
After you finish renaming you would probably want to compress the SWF so it will be smaller in size. No problem, we can use the compressing utility we created before and it will do the job. Run the utility, select the SWF and save it under another name.
Conclusion: Have a Final Look
Open it one last time and have a look. The classes, the variables and the method names are obfuscated and the protected SWF is somewhere inside, encrypted. This technique could be slow to apply at first, but after a few times it takes only a few minutes.
A while ago I created an automatic utility to inject the protected SWF for me into the loading SWF, and it worked fine. The only problem is that if it can be injected using an automatic utility, it can be decrypted using another utility, so if the attacker makes a utility for that he will get all your SWF easily. Because of this I prefer to protect the SWFs manually each time, adding a slight modification so it would be harder to automate.
Another nice application of the technique is Domain locking. Instead of decrypting the SWF with a constant string you can decrypt it with the domain the SWF is currently running on. So instead of having an if statement to check the domain, you can introduce a more powerful way to protect the SWF from placement on other sites.
Last thing, you may want to replace the encryption code with your own implementation. Why? We invested efforts in making the crypto code illegal, but the code we use is from a popular open source library and the attacker could recognize it as such. He will download a clean copy, and all the obfuscation work is rendered unnecessary. On the other hand, using your own implementation will require him to fix all the illegal names before he can continue.
Other Protection Methods
Because SWF theft is a big problem in the Flash world, there are other options for protecting SWFs. There are numerous programs out there to obfuscate AS on the bytecode level (like Kindisoft's secureSWF). They mess up the compiled bytecode and when the decompiler attempts to output code it will fail, and even crash sometimes. Of course this protection is better in terms of security but it costs $$$, so before choosing how to protect your SWF consider the amount of security needed. If it's about protecting a proprietary algorithm your 50-employee Flash studio has been developing for the past two years, you may consider something better then renaming the variables. On the other hand if you want to prevent the kiddies from submitting false high scores you may consider using this technique.
What I like about this technique is the fact that your protected SWF is left untouched when run. AS obfuscation tampers with the byte code and it could possibly damage the SWF and cause bugs (although I haven't encountered any myself).
That's all for today, hope you enjoyed the tutorial and learned something new! If you have any questions feel free to drop a comment.
| http://code.tutsplus.com/tutorials/protect-your-flash-files-from-decompilers-by-using-encryption--active-3115 | CC-MAIN-2014-52 | refinedweb | 3,211 | 64.91 |
Hi all, Is there a way to do conditionals in a makefile, based on the version of the compiler? (GNU make v3.79.1) I've been trying to use 'ifeq' with combinations of "$(CC) --version", $(__GNUC_MAJOR__), etc, but without much luck... :-( Basically, what I want to do is something like this: SOMEMACRO = whatever ifeq ( {compiler version equals some version} ) <- What goes here? SOMEMACRO += more endif (Actually, what I'd really like in this case, would be a 'greater or equal' operator, but if I can 'or' a bunch of version checks together, that'd do!) Thanks for any help! Ian (Please CC me if possible - I'm not subscribed) | http://lists.gnu.org/archive/html/help-make/2002-09/msg00032.html | CC-MAIN-2016-30 | refinedweb | 110 | 73.27 |
TCF/Meetings/Dec 4 2007 TCF-ECF Sync-up and Integration
Contents
Attendees
- Composent - Scott Lewis
- Wind River - Martin Oberhuber, Felix Burton
This is an Open call, so anyone is invited to join. Please add yourself on the attendee list and add any agenda meetings you would like to discuss
Agenda
Scope of TCF compared to scope of ECF
- TCF is an incubating extendable protocol for communication with embedded devices, which allows value-add services to be added transparently into the communication link. Bindings may exist to a variety of languages and environments (plain C, plain Java, Eclipse). Currently, the plain Java binding is usable from Eclipse, but an ECF-based Eclipse specific binding can be added.
- ECF provides generic APIs and mechanisms for communication from the Eclipse / Java environment, even if actual providers are written in other languages (e.g. Skype / C++).
- Is the description on DSDP/TM/TCF FAQ sufficient to clarify the scope of TCF, especially compared to ECF? Will users/extenders understand the differences?
- Is the DSDP/TM/TCF_FAQ#How does TCF compare to ECF? section sufficient and accurate?
- What do we think about the "vertical" versus "horizontal" description of TCF compared to ECF?
- When TCF focuses on the wire protocol, its vertical; when it focuses on transport agnosticism, it's horizontal; from today's statements we don't focus on transport agnosticism at all - we really want to standardize on TCP/IP, with proper enveloping through a protocol for transport conversion by a value-adding server (just a pass-through)
- What do we think about the name (TCF), is the term "framework" in it too confusing? Are there alternatives?
- TCF is not a framework for plugging in client components - it's more a basic protocol specification that can be extended (a "protocol framework") - what about "Target Protocol Framework"?
- Want to avoid confusion: especially people seeing that both TCF and ECF have a Channel abstraction
- TCF would be another component on TM, not a separate project
- Want to further work on the TCF FAQ to finally come up with a correct, concise definition of what TCF really is - Scott: there's a constant struggle about defining APIs that access protocols
- Discussion:
- Scott: Part of TCF is an asynchronous extensible API ("transport agnostic channel abstraction"). That particular part is overlapping highly with ECF. Also the auto-discovery of targets and services. We should work together on the overlapping things, to allow TCF work on the non-overlapping parts.
- The whole purpose of ECF is to create transport agnostic abstractions for communications. One of those is the Channel abstraction, another one the Discovery abstraction and the file transfer abstraction.
- The added value of cooperating is: all the code that's been written against the ECF channel abstraction can potentially be re-used on TCF.
- Felix: would that be beneficial to anybody? - TCF Channel is commands, replies and events. Registering a Service is a group of commands, events with semantics.
- The only kinds of clients that make sense to plug in to this framework is TCF services - the channel is only useful to TCF services.
- We would never have Eclipse talk to Serial target directly - we'd rather plug a value-adding server in between that would translate TCP/IP into Serial target communications. Therefore, we'd never have "special conversions" in Eclipse - all value-adding servers would have to know about that. Instead, use TCP/IP as long as we can (standardize on TCP/IP), and use a value-adding transport converter as near to the target as possible.
- Scott: any provider would need to do that. For example, XMPP - datashare uses XMPP beneath it. In order to do the addressing (refer to an XMPP endpoint), ECF ID interface is used.
- Why is TCF an Eclipse Project?
- Martin - 2 reasons: (a) TCF and a lightweight agent have been requested and are a "missing links" for the embedded tools we have Eclipse-based already. (b) We like the EPL and the legal safety
- What's the benefit of having an ECF provider for TCF?
- People can use an already-known programming model (from ECF) for sending messages and subscribing to events
- Ability to exchange underlying protocols is not so much helpful since we're trying to standardize on ONE protocol rather than exchanging protocols
How to move forward
- One Eclipse binding for TCF should be via ECF, but a plain Java binding should be retained for plain Java environments to use TCF. The ECF binding would allow any ECF/Equinox client to use TCF for datashare (channels) and fileshare.
- Moving forward, according to bug 210751 comment 22, a bridge should be written to turn TCF into an ECF provider for datashare (channels) and fileshare. Adding an adapter for directory retrieval to the ECF fileshare APIs could be considered.
- TCF will live under the DSDP-TM project, including the TCF-ECF bridge (which will have a dependency to ECF obviously). Through the work on TCF, it may be possible that enhancements to ECF are contributed via patches (e.g. ECF fileshare directory retrieval).
Clarify overlaps between TCF and ECF
- Some core functionality exists in both TCF and ECF. Is there something (implementation, concepts) in ECF that we should bring into TCF? What would be the benefits?
- How much of this exists in TCF already? Is there any point in keeping separate implementations such that a TCF Java binding can also run stand-alone?
- channels (associating message with response)
- name spaces / addressing
- filetransfer
- discovery
- Channels: What is the Threading Model of ECF?
- Might as well pre-answer this question. The threading model for most ECF APIs is asynchronous. What is meant by this? In the context of datashare this is exposed via non-blocking IChannel API calls, with a listener attached to the channel upon construction. The IChannelListener interface is asynchronously called when messages to the channel are received. The provider implementation of the IChannel and IChannelListener is responsible for implementing the underlying asynchrony via appropriate mechanisms (e.g. jobs or threads, etc). The IChannelListener is documented to allow the provider to call the listener with an arbitrary thread.
- Any thread call into ECF APIs; it's up to the provider whether they maintain state and thus need to take care of multi-threaded access.
- TCF: Like DSF - can call in on any thread but it's being translated into a single Executor thread
- Addressing: How does ECF handle addressing for transports other than TCP/IP?
- One big part of transport agnosticism is addressing.
- All addressing in ECF is via ECF IDs. ECF IDs are defined to be unique object instances within an associated Namespace. In many respects they resemble URIs, but do not require the entire URI syntax. Also, ECF's identity bundle exposes a Namespace extension point that allows other plugins to define their own Namespaces, and also define ID construction within that Namespace. With this, plugins that need to address entities (other processes, etc) using something other than tcp/ip...as well as protocols built on tcp/ip...may freely do so.
- Packaging: P2 currently using 4 bundles - identity, filetransfer API, filetransfer impl - currently picking binaries from ECF update site; in Eclipse 3.4, they will be part of the Platform.
- Addressing in TCF: not yet implemented in TCF; in future, would first connect to value-add, then read from value-add what it can connect to and ask it to forward packets to the next server and so on. Each value-add brings in their own API/UI for addressing and routing. There is no single notion of "address" or "endpoint". User configures the communication link through the APIs / UIs brought in by the value-adders.
- TCF "Context" is not an address -- it's on a higher level, for identifying a thread, process, CPU, address space or breakpoint.
- Allows queries - hierarchical namespace, e.g.
- Filetransfer: ECF has an ECF API Refactoring#Create filetransfer plugin, remove fileshare plugin action item. How does this relate to directory retrievals?
- This particular refactoring has been completed some time ago (ECF fileshare is deprecated). RE: directory retrievals...in order to reduce the overall size and complexity of filetransfer as much as possible, directory information/browsing/navigation was initially left out of the file transfer API. This provided some benefits, in terms of size and complexity for the Equinox P2 project. However, using adapters, the file transfer API can (and eventually will) be expanded to include directory navigation. A new directory navigation adapter API contribution would be most welcome, and not technically difficult. Further, for applications that can accept the dependencies involved, EFS already provides directory navigation (and I think TM is already using EFS). Further, an ECF provider implementation *based upon EFS and the Jobs API* has already been created, and can be used in combination with the EFS directory/filestore browsing code. Obviously, such applications have to deal with the blocking I/O aspect of EFS directly.
- How would an application leverage EFS directory browsing with ECF fileshare? What would the benefit of using ECF be in that case?
- Filetransfer: See API Docs for IRetrieveFileTransferContainerAdapter in ECF. Also see here
- Discovery:
- How does discovery work in TCF? How much is implemented already?
- Here is Bug 209774 for API changes in ECF Discovery 2.0
- This summary bug and all associated bugs have now been committed to HEAD. See here for new API.
- Does DSDP-TM Discovery relate to this in any way?
Clarify rules/guidelines for when ECF interfaces should be created
- JDT is opening their own sockets today for debugging; why not use ECF?
- Scott: ECF is not set out to replace all existing protocols; its rather for those who want interoperability (e.g. filetransfer - P2 not interested in implementing protocols) Current known deficiency
- Another example is Discovery - ECF defined a discovery API (Zeroconf; SLP implementations) - easy creation of interoperable clients
- Felix: Rather than integrating on Channel level, better integrate on the Filesystem and Discovery levels. TM should have an ECF based fileshare service.
- ECF Channel abstraction is very low-level - only byte[] arrays, no data presentation layer
- What are the benefits of integrating ECF/TCF?
- Discovery makes sense
- Fileshare makes sense (but directory browsing is missing)
- Datashare: Does it make sense to have an ECF provider for Channel as well, or not?
- ECF Datashare API is extendable via Adapters
- Felix: Chicken-and-egg problem... when RSE has an ECF fileshare service, it makes sense to implement it in TCF but probably not before
Links
Action Items
- All: Re-read the FAQ and point out misunderstandings
- Martin: file a bug for updating the FAQ (Done: bug 211901)
Next Meeting
- Should talk again once a few agenda items are identified - will schedule on-demand via E-Mail | http://wiki.eclipse.org/TCF/Meetings/Dec_4_2007_TCF-ECF_Sync-up_and_Integration | CC-MAIN-2017-04 | refinedweb | 1,786 | 54.12 |
So, now we have the Class designer, GREAT! Its a really nice feature, and i really love it.
Now the thing is, im to create a small framework. And i really needed something like the distributed system solution, where you could design what kinds of solutions you need, add yellow stickers(For instance ideas, as well as notes).
The class designer is fine, but to really complete the family, we need a solution designer, which basicly zooms 200% out from the class designer, and looks at solutions!
For instance, i need this solution, it takes this, this, this, x and y class. Fine.
It should work like the class designer, but if you zoom in at a class in the solution designer, you should get the class designer!
So, now we have the Class designer, GREAT! Its a really nice feature, and i really love it.
I thought Team System (I only have Pro so not sure) had a diagramming tool for systems like you describe, without the zooming effect though.
Yeah there's the Application Designer which takes a much higher conceptial view of a system.
- Sampy wrote:Yeah there's the Application Designer which takes a much higher conceptial view of a system.
I have been searching and searching, and googled it.
The application designer, as far as i can see, is really the Distributed Application designer? Or am i looking at the wrong place?
I cant find anything else, that comes anywhere near it.
But since the Distributed Application Designer handles things like webservice, and ASP.net sites, i cant use it, as i want to be able to create different solutions, that is class libraries, so i can see how it looks from another perspective, but the one the class designer gives me, which is "Now i have this namespace, with class x,y,z, and another namespace over here, containing class 1,2,3, which have NOTHING To do with each other, as far as i can see".
- Ion Todirel wrote:
Yes, i need something like the distributed system designer, but not for distributed systems, which in this realese is aimed towards web services, etc., but i need something for designing my framework(Painting a set of classes, inside a specific namespace, and eventually connect it to other namespaces, make nodes, and general design of the solution i make.
Class Designer is extensible, you should check out the Class Designer Power Toys for some ideas, but there's no reason you can't create this yourself:D
Thread Closed
This thread is kinda stale and has been closed but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know. | http://channel9.msdn.com/Forums/Coffeehouse/223073-Class-designer-needs-an-extension | crawl-003 | refinedweb | 457 | 66.98 |
Date::Calc::Iterator - Iterate over a range of dates
use Date::Calc::Iterator; # This puts all the dates from Dec 1, 2003 to Dec 10, 2003 in @dates1 # @dates1 will contain ([2003,12,1],[2003,12,2] ... [2003,12,10]) ; my $i1 = Date::Calc::Iterator->new(from => [2003,12,1], to => [2003,12,10]) ; my @dates1 ; push @dates1,$_ while $_ = $i1->next ; # Adding an integer step will iterate with the specified step # @dates2 will contain ([2003,12,1],[2003,12,3] ... ) ; my $i2 = Date::Calc::Iterator->new(from => [2003,12,1], to => [2003,12,10], step => 2) ; my @dates2 ; push @dates2,$_ while $_ = $i2->next ;
Date::Calc::Iterator objects are used to iterate over a range of dates, day by day or with a specified step. The method next() will return each time an array reference containing ($year,$month,$date) for the next date, or undef when finished.
This module is little and simple. It solves a little problem in a simple way. It doesn't attempt to be the smarter module on CPAN, nor the more complete one. If your problem is more complicated than this module can solve, you should go and check DateTime::Event::Recurrence, which solves a so broad range of problems that yours can't fall out of it.
Probabily this module won't evolve a lot. Expect bug fixes, minor improvements in the interface, and nothing more. If you need to solve bigger problems, you have two choices: vivifying a 2.x version of the module (after contacting me, of course) or using DateTime::Event::Recurrence and its brothers.
Anyway, I left the name Iterator, and not Iterator::Day or DayIterator, for example, so that the module can evolve if the need be. Who knows? Maybe one day I could need to make it iterate over weekdays, or over moon phases... let's leave the way open, time will tell.
Creates a new object. You must pass it the end points of a date interval as array references:
$i = Date::Calc::Iterator->new( from => [2003,12,1], to => [2003,12,10] )
from and
to are, obviously, required.
Optionally, you can specify a custom step with the
step key, for example:
$i = Date::Calc::Iterator->new( from => [2003,12,1], to => [2003,12,31], step => 7 ) ;
will iterate on December 2003, week by week, starting from December 1st.
Returns the next date; in list context it returns an array containing year, month and day in this order, or
undef if iteration is over; in scalar context, it returns a reference to that array, or
undef if iteration is over.
Original version; created by h2xs 1.22 with options
-CAX -b 5.6.0 --use-new-tests --skip-exporter -O -v 0.01 Date::Calc::Iterator
The wonderful Date::Calc module, on top of which this module is made.
DateTime::Event::Recurrence and all the DateTime family from.
Marco Marongiu, <bronto@cpan.org>
Thanks to Steffen Beyer, for writing his Date::Calc and for allowing me to use his namespace.
Blame on me, for being so lazy (or spare-time-missing) that I didn't make this module compatible with the Date::Calc::Object interface.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. | http://search.cpan.org/~bronto/Date-Calc-Iterator-1.00/Iterator.pm | CC-MAIN-2014-35 | refinedweb | 551 | 63.09 |
Delete unused c++ files from the project
Hello Everyone,
I want to write a script which will delete the unused c++ file from the project. Can anyone help me in writing the script. Thank you very much.
- aha_1980 Qt Champions 2018 last edited by
@rockon209 said in Delete unused c++ files from the project:
the unused c++ file
Please elaborate what you mean with "the unused c++ file".
Regards
- Kent-Dorfman last edited by
if you just mean the intermediate MOC files then make clean does that
@Kent-Dorfman
@Qt-Champions-2018
No not MOC files, normal C++ files(.cpp and .h) that are not used now in the project at all. In my project i have lot of these files which are in import but not used at all.
There are also some cases that one files is used in another file but this another file is not used anywehere. So doing this manually will take a lot of time. So a script can be used. That why i need a script to do this.
- Kent-Dorfman last edited by
The .pro file should contain a list of all the needed project files. parse it and delete whatever is not referenced therein...
@Kent-Dorfman
I am not using qmake in my project i have cmake files. Thats why i dont have .pro file
- kshegunov Qt Champions 2017 last edited by
@rockon209 said in Delete unused c++ files from the project:
Don't do that. People don't appreciate being summoned. If they have something to say, they're going to post their thoughts on their own.
@rockon209 You can parse cmake files as well.
but my Cmake file dont have the c++ files included in it. It just give the path of the folder where the files are and this folder I have all the files which are not in used also.
- aha_1980 Qt Champions 2018 last edited by
@rockon209 So how do you know a file is "unused"? If you don't have a way to know that, that will be a very hard task to write such a script.
My logic was to take each class name form each file cpp and search for it and if it us used in any other file then its used. Same as search function. But i dont know if its a right approach to do it. Just an intial idea i can think of.
@rockon209 Shouldn't you as developer know which files are used and which not?
And why do you actually have unused files in your project?
What you can do: build your project and analyse the build log to see which files were compiled, remove all files which were not compiled.
Well I am not the only developer, there are many other developer doing the develpment for there specific part assign to them.
ya but in build i am not sure if all the files are build. I mean let say in a Phone we have lot of application which are used and those application are not build everytime. I am not sure just guessing
@rockon209 Well, then you will need to collect build logs for all supported platforms and analyse all of them.
- J.Hilk Moderators last edited by
@rockon209
if you're using QtCreator,
you can right click on a class definition, and select
open include-hierachy, should help you.
But I don't think that it will show stuff that is OS-Dependend - if the includes are wrapped inside #if defined(Q_OS_WIN) #endif blocks
open include hierachy its a fucntion in Qt, i want to write a python script which will find it.
Its like to find the dead code in the project which is not been used.
- SGaist Lifetime Qt Champion last edited by
Hi,
Then in your script you'll have to parse all your sources, build a list of the include statements contained in all headers and implementation files, build a list of all the header/implementation files and then compare both and delete the files that do not appear in the list of include statements. | https://forum.qt.io/topic/103622/delete-unused-c-files-from-the-project | CC-MAIN-2019-43 | refinedweb | 685 | 79.5 |
24 January 2011 11:51 [Source: ICIS news]
LONDON (ICIS)--Specialists from BASF will examine the cargo of sulphuric acid that was being transported by the boat that capsized on the river ?xml:namespace>
The specialists need to test if water has been in contact with the ship's cargo of sulphuric acid and if there is a risk that highly explosive hydrogen has developed in the vessel, said Uwe Rindsfuesser, a spokesman for the Landkreis Rhein-Lahn, a local administrative authority.
Work to stabilise the ship, the Waldhof, was currently taking place before specialists can begin conducting tests on 26 January or 27 January.
The ship was carrying some 2,400 tonnes of sulphuric acid from BASF’s petrochemicals hub in
The capsizing led authorities to close a 70km stretch of the
Florian Krekel, a spokesman for shipping authority Wasser- und Schifffahrtsamt Bingen, said two cranes began salvage work on 22 January on the capsized tanker.
A third crane was currently in the harbour and being prepared to help secure the Waldhof with cables, he said.
Once the sulphuric acid was checked and deemed safe, the ship's contents would be transferred to a tanker currently on site.
Officials will have a better idea later this week about how long the removal of the vessel would take, Krekel said.
Ships travelling upstream have been allowed to pass the salvage site since 21 January.
“On Friday, 20 ships passed the bend of the capsized ship. On Saturday, 93 passed. And yesterday (Sunday), 111 went through. The congestion of boats travelling upstream has now disappeared,” Krekel said.
However, downstream shipping remained closed and vessels were facing congestion on the waterway near the city of | http://www.icis.com/Articles/2011/01/24/9428525/basf-to-conduct-safety-tests-of-capsized-boat-on-river-rhine.html | CC-MAIN-2014-41 | refinedweb | 283 | 58.42 |
I have to write a program that takes temperature in celsius (if in farenheit, it converts it to celsius) along with the windspeed and calculates the windchill. I have the program written but I can't figure out what I'm doing wrong in lines 63 and 75. Any help would be appreciated!
#include <iostream> using namespace std; void FtoC(); //Gets input in farenheit, makes conversion to Celsius, displays results. void TEMPinC (); //Asks user for the temperature in Celsius. void WINDSPEED (double SPEED); //Asks user for the wind speed in m/sec. void WINDCHILL(double WINDSPEED, double TEMPERATURE, double WINDCHILL_INDEX); //Calculates the windchill from the input information. void WINDCHILL_OUT(); //Outputs the results of the conversion. int main() { char repeat; cout << "This program will take the wind speed\n" << "and the temperature and find the windchill index.\n\n" << "wind speed is in m/sec, while\n" << "temperature is in degrees Celsius or Farenheit.\n\n"; do{ WINDCHILL_OUT(); cout << "Would you like to make another conversion?\nPlease enter y or n. "; cin >> repeat; }while(repeat=='y'); cout << "\nThank you and goodbye.\n"; system("PAUSE"); return 0; } void FtoC(double FARENHEIT, double& TEMPERATURE) { int which; cout << "\nPlease enter 1 to convert celsius and\nenter 2 to convert farenheit. "; cin >> which; while(which !=1 && which !=2) { cout << "Please enter 1 or 2. "; cin >> which; } if(which==1) { cout << "Please enter the temperature in farenheit followed by enter\n"; cin >> FARENHEIT; TEMPERATURE = (FARENHEIT-32)*(5/9); } else TEMPinC(); } void TEMPinC() { cout << "Please enter the temperature in farenheit followed by enter\n"; cin >> TEMPERATURE; } void WINDSPEED (double SPEED) { cout << "\nPlease enter the windspeed in m/sec.\n"; cin >> SPEED; } void WINDCHILL(double WINDSPEED, double TEMPERATURE, double WINDCHILL_INDEX) { WINDCHILL_INDEX = 13.12 + (0.6215*TEMPERATURE) - (11.37 * (pow(WINDSPEED,0.16)) + (0.3965 * TEMPERATURE * (pow(WINDSPEED,0.016)); } void WINDCHILL_OUT(double WINDSPEED, double TEMPERATURE, double WINDCHILL_INDEX) { cout << "\nWith a temperature of " << TEMPERATURE << " and a windspeed of\n" << WINDSPEED << " the windchill index is " << WINDCHILL_INDEX << " degrees celsius\n\n"; } | https://www.daniweb.com/programming/software-development/threads/11557/new-2-c-help-with-finding-erros | CC-MAIN-2017-34 | refinedweb | 330 | 56.96 |
This site uses strictly necessary cookies. More Information
I am just wondering what the best approach is to handling world items that all other players on a server can interact with. A good example would be switches and doors, that exist as part of the scene, but would need to handled by each players client as they interact with it. I've tried to wrap my head around it, but I am coming up blank. I have seen people say that the prefabs should be spawned in on launch, but that doesn't seem like it would help if the objects are static parts of the environment. Whenever I do attempt something, I get the old "Trying to send command for object without authority."
Any help would be greatly appreciated.
Answer by Graithen
·
Jun 16, 2019 at 04:03 PM
Ok! After much trial and error, I figured out a system that works fine for me that solves my initial problem. Part of my solution is handled inside the character controller, and part inside the object itself.
if (Input.GetKeyDown(KeyCode.E))
{
CmdActivateObject();
}
//A trigger volume in front of the player looks for objects with an 'interactable' tag, and when it finds them it will pass it into AssignInteractables!
private void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "Interactable")
{
AssignInteractables(other.gameObject);
Debug.Log(other.gameObject.name);
}
}
private void OnTriggerExit(Collider other)
{
AssignInteractables(null);
}
//I use this to assign the object that will be interacted with
public void AssignInteractables(GameObject interactable)
{
ObjectToAssign = interactable;
if (ObjectToAssign != null) {
Debug.Log(ObjectToAssign.name + " ready to assign!");
}
}
//This next part handles the interaction and the replication of the interaction on the server and across all other clients. It will reach into the interactable object and look for the Network Interaction script and then change its 'active' state.
[Command]
void CmdActivateObject()
{
bool activStat = ObjectToAssign.GetComponent<NetworkInteraction>().PlayerActivated;
activStat = !activStat;
if(isServer)
{
RpcActivateObject(activStat);
}
}
[ClientRpc]
void RpcActivateObject(bool state)
{
ObjectToAssign.GetComponent<NetworkInteraction>().PlayerActivated = state;
}
On each object that I want the player to be able to interact with, I just assign my 'Network Interaction' script:
public class NetworkInteraction : MonoBehaviour
{
[Header ("Activation State")]
public bool PlayerActivated;
}
Because it is the same across all systems, I can then write any script I want, and reference this PlayerActivated boolean using a locally running script to do all the complex things I need an object to do...
It might not be the most elegant way to handle this problem, but like I said it deffo works for me!
Answer by Bunny83
·
May 30, 2019 at 07:19 PM
I guess you use UNet!?
Any object that is not owned by a single player is owned by the server and therefore only the server can control it. If you want to change the state of such an object from a client, the client has to send a command through his own player object and on the serverside the server can verify the request and forward it to the object in question.
Any communication from the client goes through his player object. In most multiplayer games you only have a few physical inputs / keys that a player can actually use. (like pressing "e" to "use" something, mouse0 to fire, ... ). There are generally two approaches:
Either you just send the actual input events to the server and do everything else on the serverside. On the server you can do everything you want.
Another option is to do some pre determining on the client and send more explicit commands to the server (again, everything through the player object). For example you can do the raycasting which determines which object a player is looking at on the client and just pass a gameobject reference as parameter to the command you send to the server. However the more you do already on the client, the more difficult it is for the server to verify the validity of the command. A similar issue you see in some games that work this way. For example minecraft. The client essentially tells the server that he interacted with a certain block. However a cheater could simply tell the server he ineracted with a block that isn't reachable by the player.
So the best security is reached by only sending input events and do the rest on the server. Best precision and user feedback is reached when you do some preprocessing on the client.
So either you just send an interact() message to the server and let the server do the rest, or you send commands like interact(GameObject) where you pass along the object you want to interact with.
interact()
interact(GameObject)
Thanks for the reply! I am indeed using UNet. I am just wondering how would I go about sending the input events to the server? When I try and run a [Command] on a client locally, it says there is an issue with the client not having authority. I completely understand having things running on the server to prevent cheating, I am just unsure how to handle getting a door script run locally with authority for all players. I had presumed I would have to change the objects authority to the client intending to use it, but now I am not so.
Multiplayer Lobby & Gamemode selection Coding
0
Answers
Multiple Cars not working
1
Answer
1
Answer
Distribute terrain in zones
3
Answers
How to synchronize disable and enabling game objects over the network?
0
Answers
EnterpriseSocial Q&A | https://answers.unity.com/questions/1636426/creating-interactable-items-that-are-usable-by-all.html | CC-MAIN-2021-31 | refinedweb | 912 | 52.49 |
38305/what-the-equivalent-django-create-sqlalchemy-using-python
Hi all. My requirement was that I needed to get my hands on an object from a database (if it exists) or if not, to create it on my own.
Django has a method called get_or_create and it does exactly this. But, my question is that, is there an alternative or an equivalent to use the same thing to obtain same functionality in SWLAlchemy?
This is what I am doing now:
def get_or_create_instrument(session, serial_number):
instrument = session.query(Instrument).filter_by(serial_number=serial_number).first()
if instrument:
return instrument
else:
instrument = Instrument(serial_number)
session.add(instrument)
return instrument
All help appreciated!
As far as I know, there is no literal shortcut to go about doing this. And whatever you're doing is the right way to go about doing it.
You can also generalize it and go about it this way, check it out:
def get_or_create(session, model, defaults=None, **kwargs):
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance, False
else:
params = dict((k, v) for k, v in kwargs.iteritems() if not isinstance(v, ClauseElement))
params.update(defaults or {})
instance = model(**params)
session.add(instance)
return instance, True
Hope this helped!
The main purpose of anonymous functions come ...READ MORE
The SimpleHTTPServer module has been merged into http.server in Python 3.0. ...READ MORE
Polymorphism is the ability to present the ...READ MORE
python is general purpose programming language.it very ...READ MORE
You can also use the random library's ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
can you give an example using a ...READ MORE
You can simply the built-in function in ...READ MORE
Hi, good question!
One simple answer to your ...READ MORE
Hi. Nice question.
Here is the simplified answer ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/38305/what-the-equivalent-django-create-sqlalchemy-using-python?show=38308 | CC-MAIN-2021-21 | refinedweb | 311 | 62.04 |
"Timm, Sean" <STimm@mailgo.com> wrote:
> I don't see any reason that you *can't* specify xsl:version, but it's
> not required.
Review the XSLT recommendation quote again:
"An element from the XSLT namespace may have any attribute not from the
XSLT namespace, provided that the expanded-name of the attribute has a
non-null namespace URI."
Over the past year I've tried to read James Clark-speak. Since
xslt:version *is* in the XSLT namespace, then the above would seem to imply
that it is not legal. If you invert the first part: "An element from the
XSLT namespace may *not* have any attribute *in* the XSLT namespace", then
you get how I am reading it. This may be a misinterpretation somehow, or
an over application of legalism. Hell if I know. I just want a stylesheet
that Xalan let's you produce be interoperable with other processors. So
clearly this has to be disambiguated by the WG. Because we all want to
live in a world where users have choices about what software to run, these
legalisms are very important when it comes to standards.
-scott | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200003.mbox/%3COF09C972FA.A473B583-ON85256898.00017453@lotus.com%3E | CC-MAIN-2016-44 | refinedweb | 191 | 71.85 |
0
Hi everybody,
I wrote a game in which you have to guess a number generated randomly,but when i try to assign a random number to the variable, it just doesn't work but it compiles fine.
The code :
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main () { string replay; do { srand(time(0)); char level; int number; cout << endl << endl <<"Welcome to the guess game" << endl; cout << "Choose your level :" << endl << "1 : very easy (1-50)" << endl; cout << "2 : Easy (1-100)" <<endl; cout << "3 : Moderate (1-250)" <<endl; cout << "4 : Hard (1-500)" <<endl; cout << "5 : Very hard (1-1000)" <<endl; cout << "6 : Extreme (1-2500)" <<endl; cout << "7 : IMPOSSIBLE (1-10000)" <<endl; cin >> level; switch (level) { case 1: number = 1+(rand()%50); break; case 2: number = 1+(rand()%100); break; case 3: number = 1+(rand()%250); break; case 4: number = 1+(rand()%500); break; case 5: number = 1+(rand()%1000); break; case 6: number = 1+(rand()%2500); break; case 7: number = 1+(rand()%10000); break; } int ans = 0; int chances = 20; while(ans!=number && chances!=0) { cout << "Enter your number" << endl << endl; cin >> ans; if (ans < number) { cout << "Bigger" << endl; --chances; cout << chances << " chances left." << endl; } else if (ans > number) { cout << "Smaller" << endl; --chances; cout << chances << " chances left." << endl; } else { cout << "You guessed it !! Congratulations !! with " << chances << " chances left !!" << endl; cout << "Replay ? (y/n)" << endl; cin >> replay; } } cout << "You lost !" << endl; cout << "Replay ? (y/n)" << endl << endl; cin >> replay; } while(replay == "y"); }
i will appreciate any help, thanks
Edited by Karlwakim: n/a | https://www.daniweb.com/programming/software-development/threads/405464/problem-with-basic-code | CC-MAIN-2017-26 | refinedweb | 259 | 73.81 |
Java Date Class Example
The class Date is nothing but the representation of the specific instant in Time. It is given in the millisecond precision. For calculation purpose, all the operating system assumes that 1 day= 24*60*60=86400 seconds. However, in Coordinated Universal Time (UTC), there is an extra second called “leap second” about once every year or two year which is added either on December 31 or June 30.
also read:
In Class Date two additional functions were included prior to the JDK 1.1. First, the interpretations of dates were done as year, month, day, hour, minute, and second values. Second, formatting and parsing of the date strings. But, these functions are now taken out of Class Date and are included in the Class Calendar which is a part of JDK 1.1.Date standard for some computer is defined in terms of Greenwich Mean Time (GMT), which is equivalent to the Universal Time (UT).
Date Class Declaration
public class date extends Object implements Serializable, Cloneable, Comparable<Date>
The above declaration defines an object of class date which allows the serialization and colonizing of the objects. Serialization is an object can be converted to the series of bytes, which contains the information of the object’s data like its type of data stored in that object. Once serialized data is been written to the file it can be deserialized to the object whenever is required. Colonizing allows making the duplicate copy of the object.
Date Class Constructors
Date Class Methods
Date Class Example
import java.util.*; public class Example_date { public static void main(String[] args) { Date date1 = new Date (90, 8, 3); Date date2 = new Date (90, 11, 18); boolean before = date2.before(date1); System.out.println("Date2 is before date1: " + before); boolean after = date2.after(date1); System.out.println("Date2 is after date1 : " + after); int compare1 = date1.compareTo(date2); int compare2 = date2.compareTo(date1); int compare3 = date1.compareTo(date1); System.out.println("campare date1 to date2:" + compare1); System.out.println("campare date2 to date1:" + compare2); System.out.println("campare date1 to date1:" + compare3); boolean c1 = date1.equals(date2); System.out.println(" Are Dates equal??? :" + c1); long d1 = date1.getTime(); System.out.println("If date is 3-8-1990, " + d1 + " this much time have passed."); } }
- Above example demonstrate the usage of methods like before (), after (), compare of Class Date (), equals () and get time ().
- Date date1 = new Date (90, 8, 3); line creates the Date Object, date1 which accepts the date format as year, month, and date and similarly next line does the same thing.
- boolean before = date2.before(date1); line checks whether the date2 is before the date1 or not, and returns boolean true or false.
- boolean after = date2.after(date1); line checks whether the date2 is after the date1 or not, and returns boolean true or false.
- Below three lines makes the comparison of date 1 and date 2 in three different ways i.e.
- int compare1 = date1.compareTo(date2);
- int compare2 = date2.compareTo(date1);
- int compare3 = date1.compareTo(date1);
- Comparison output
- -1, when date1 is greater than date2.
- 1, when date1 is less than date2.
- 0, when date1 is equal to date 1.
- boolean c1 = date1.equals(date2); this methods checks for the equality of two specified dates, date 1 and date 2. It returns the boolean true if dates are equal else returns boolean false.
- long d1 = date1.getTime(); statement returns the time in terms of number of seconds elapsed since Jan 1, 1970, 00:00:00 GMT.2
When you run the above example, you would get the following output:
| http://www.javabeat.net/java-util-date/ | CC-MAIN-2015-40 | refinedweb | 598 | 59.09 |
As an example, this blog post will present the ubiquitous Word Count example, where a text file (The Tell-Tale Heart by Edgar Allan Poe) is read in, split on non-alphanumeric characters, then each word's frequency in the corpus is calculated. The incoming flow file's contents are replaced with lines of "word: frequency" for each unique word/term in the corpus.
The previous post included a discussion on how to ensure your script will get a valid flow file (namely, returning if session.get() does not return a flow file object). It also illustrated how to use session.putAttribute() to add/update an attribute, and the importance of keeping the latest reference to the flow file object. This post will focus on Groovy code to replace the content of an incoming flow file.
A very concise way to replace flow file content (at least in Groovy) is to leverage ProcessSession's write() method that takes a StreamCallback object. The StreamCallback will get an InputStream (from the incoming flow file) and an OutputStream (where the new content should go). The best part is that the StreamCallback interface has a single method, so with Groovy we can just use closure coercion instead of creating an explicit implementation of the interface. Here's what such a skeleton looks like:
flowFile = session.write(flowFile, {inputStream, outputStream -> // Read incoming flow file content with inputStream // ... other stuff... // Write outgoing flow file content with OutputStream } as StreamCallback)
If you need to read the entire flow file into a String (which you should avoid in case you get very large files), you can import org.apache.commons.io.IOUtils and use IOUtils.toString(InputStream, Charset). See the full example below.
My example reads the entire text in, to keep the code simple, but for a real script you might want to look at StreamTokenizer or something else to pull words out one at a time. Once the corpus is read in, the words are split on whitespace and other non-alphanumeric characters, then turned to lowercase to get a more accurate word count (versus capitalization differences, e.g.). The word count map is then updated, then a string output is generated with inject(). This is another place where the code can be more efficient (using map.each() or something), but I was trying to keep the body of the session.write() closure concise. The string output is written to the OutputStream, then after the write() has completed, the filename attribute is set and the file is sent to "success".
The example code for the ExecuteScript processor is as follows:
import org.apache.commons.io.IOUtils import java.nio.charset.* def flowFile = session.get() if(!flowFile) return flowFile = session.write(flowFile, {inputStream, outputStream -> def wordCount = [:] def tellTaleHeart = IOUtils.toString(inputStream, StandardCharsets.UTF_8) def words = tellTaleHeart.split(/(!|\?|-|\.|\"|:|;|,|\s)+/)*.toLowerCase() words.each { word -> def currentWordCount = wordCount.get(word) if(!currentWordCount) { wordCount.put(word, 1) } else { wordCount.put(word, currentWordCount + 1) } } def outputMapString = wordCount.inject("", {k,v -> k += "${v.key}: ${v.value}\n"}) outputStream.write(outputMapString.getBytes(StandardCharsets.UTF_8)) } as StreamCallback) flowFile = session.putAttribute(flowFile, 'filename', 'telltale_heart_wordcount') session.transfer(flowFile, REL_SUCCESS)
The self-contained template is a Gist (here), it includes the full text and a PutFile to write out the word count file in a directory relative to the NiFi instance.
Hi Matt,
I am new to NiFi and trying to change and excel file to CSV and having trouble writing the file back.
I am using Python, any idea how to write a file back to the flowfile?
Thanks | http://funnifi.blogspot.com/2016/02/executescript-processor-replacing-flow.html | CC-MAIN-2018-39 | refinedweb | 592 | 56.86 |
Hadoop Distributed File System (HDFS)
Hadoop Distributed File System (HDFS) is a distributed file system which is designed to run on commodity hardware. Commodity hardware is cheaper in cost. Since Hadoop requires processing power of multiple machines and since it is expensive to deploy costly hardware, we use commodity hardware. When commodity hardware is used, failures are more common rather than an exception. HDFS is highly fault-tolerant and is designed to run on commodity hardware.
HDFS provides high throughput access to the data stored. So it is extremely useful when you want to build applications which require large data sets.
HDFS was originally built as infrastructure layer for Apache Nutch. It is now pretty much part of Apache Hadoop project.
HDFS has master/slave architecture. In this architecture, one of the machines will be designated as a master node (or name node). Every other machine would be acting as slave (or data node). NameNode/DataNode are java processes that run on the machines when Hadoop software is installed.
NameNode is responsible for managing the metadata about the HDFS Files. This metadata includes various information about the HDFS File such as Name of the file, File Permissions, FileSize, Blocks etc. It is also responsible for performing various namespace operations like opening, closing, renaming the files or directories.
Whenever a file is to be stored in HDFS, it is divided into blocks. By default, blocksize is 64MB (Configurable). These blocks are replicated (default is 3) and stored across various datanodes to take care of hardware failures and for faster data transfers. NameNode maintains a mapping of blocks to DataNodes.
DataNodes serves the read and write requests from HDFS file system clients. They are also responsible for creation of block replicas and for checking if blocks are corrupted or not. It sends the ping messages to the NameNode in the form of block mappings.
How communication happens?
1. HDFS exposes Java/C API using which user can write an application to interact with HDFS. Application using this API Interacts with Client Library (present on the same client machine).
2. Client (Library) connects to the NameNode using RPC. The communication between them happens using ClientProtocol. Major functionality in ClientProtocol includes Create (creates a file in name space), Append (add to the end of already existing file), Complete (client has finished writing to file), Read etc.
3. Client (Library) interacts with DataNode directly using DataTransferProtocol. The DataTransferProtocol defines operations to read a block, write to block, get checksum of block, copy the block etc.
4. Interaction between NameNode and DataNode. It’s always DataNode which initiates the communication first and NameNode just responds to the requests intiated. The communication usually involves DataNode Registration, DataNode sending heart beat messages, DataNode sending blockreport, DataNode notifying the receipt of Block from a client or another DataNode during replication of blocks.
In this post, we have discussed the high level architecture of HDFS and then we understood various daemons that are running behind the scenes for HDFS. We also saw how communication happens between client vs HDFS and also among various daemons of HDFS.
In next few posts, let’s dig deeper and understand how HDFS achieves its robustness, data availability and high data transfers.
Happy Learning!
Related links For Excel: | https://www.edupristine.com/blog/introduction-to-hadoop-distributed-file-system | CC-MAIN-2021-39 | refinedweb | 543 | 57.16 |
Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: st: mat list
I would look at -help estimates- and use -estimates store- and
-estimates restore-. If your problem is too complicated for that than
it will certainly be so complicated that the probability of a hard to
find bug is (near) 100% when referring to coefficients by column
number.
If you decide to use scalars, than don't forget to use -tempname-s for
them (variables and scalars share the same namespace, and this can
cause problems), see the manual entry for -scalar-.
-- Maarten
On Tue, Apr 10, 2012 at 2:50 PM, Chiara Mussida <cmussida@gmail.com> wrote:
> for the calculations i have to use coef from different models, that's
> why i need to store them in separate matrices and not only store and
> work on the last model estimates. For each of my reg k will create a
> different mat with obviously a diff name and thereafter i will play
> with coef. Do you think it is more deficient to save them as scalars
> with more simple name than b[row, col ]?
>
> On 10/04/2012, Maarten Buis <maartenlbuis@gmail.com> wrote:
>> On Tue, Apr 10, 2012 at 12:33 PM, Chiara Mussida wrote:
>>> i run a reg and i need to use the coefficients for calculations purposes.
>>> After my reg i gen a matrix with my betas:
>>> mat beta=e(b)
>>> this is a 1*k vector of coef.
>>> To use them for my manipulation is it enough to refer to them- such:
>>> beta[1,col] or it is better to gen a scalar for each matrix element?
>>
>> I have programmed quite a bit of post-estimation commands and I have
>> never been in a situation where I had to refer to coefficients by
>> column number. That seems to me an extremely bug-prone method.
>>
>> I find it often convenient to refer to specific coefficients as
>> -_b[varname]-. This is mainly because it is easier to see in your code
>> what coefficient you refer to, so the code becomes easier to read and
>> debug. This trick does not require that you store your coefficients in
>> a separate matrix, but it does refer to the currently active model
>> (which you can manipulate using -est store- and -est restore-).
>>
>> Hope this helps,
>> Maarten
>>
>> --------------------------
>> Maarten L. Buis
>> Institut fuer Soziologie
>> Universitaet Tuebingen
>> Wilhelmstrasse 36
>> 72074 Tuebingen
>> Germany
>>
>>
>>
>> --------------------------
>> *
>> * For searches and help try:
>> *
>> *
>> *
>>
>
>
> --
> Chiara Mussida
> PhD candidate
> Doctoral school of Economic Policy
> Catholic University, Piacenza (Italy)
> *
> * For searches and help try:
> *
> *
> *
--
--------------------------
Maarten L. Buis
Institut fuer Soziologie
Universitaet Tuebingen
Wilhelmstrasse 36
72074 Tuebingen
Germany
--------------------------
*
* For searches and help try:
*
*
* | https://www.stata.com/statalist/archive/2012-04/msg00412.html | CC-MAIN-2020-40 | refinedweb | 461 | 57.81 |
Editor’s note: The following post was written by Visual C# MVP Ming Man Chan
Creating Unit Test for the projects using Microsoft’s Entity Framework
This article consist of three subsection:
When you are creating unit test method then you might have hit the following error:
Test method UnitTestProject1.UnitTest1.TestMethod1 threw exception: System.InvalidOperationException: No connection string named 'NorthwindEntities' could be found in the application config file.
The error with NorthwindEntities is because I am using the sample database so for you it may be any xxxxxxEntities.
Let us simulate the problem by using a Console Application, this can apply to other type of projects such as Web and Windows client. We will be using Visual Studio 2013 for this article. The Entity Framework that this article is using is version 6.0.
3. Right the console project.
4. Select Add -> New Item…
5. Select Data then ADO.NET Entity Data Model.
6. Type in the Name for example, NWModel.edmx.
7. Click on Add button.
8. Click on Next > button.
9. Click on Which data connection should your application use to connect to the database? (combo box) in Entity Data Model Wizard.
10. Click on New Connection... button in Entity Data Model Wizard.
11. Type on Server name: in "Connection Properties" for example, .\SQLEXPRESS
12. Click on Open button in "Connection Properties".
13. In this sample you can click on northwind in list item.
14. Click on OK button in "Connection Properties".
15. Click on Next > button in Entity Data Model Wizard.
16. Click on "Tables (tree item)" in Entity Data Model Wizard.
17. Click on dbo (tree item) in Entity Data Model Wizard.
18. Select the Products table.
19. Click on Finish button in Entity Data Model Wizard.
The ADO.NET Entity Model is now created.
20. Click on Build menu item to build your project.
Replace the following code to the Program.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class Program
{
public static void AddProduct()
{
NORTHWNDEntities ctx = new NORTHWNDEntities();
Product product = new Product();
product.CategoryID = 1;
product.ProductName = "toy";
ctx.Products.Add(product);
ctx.SaveChanges();
}
static void Main(string[] args)
{
AddProduct();
}
}
}
The AddProduct is hardcoded for testing proposes. In real life then you might pass the ID and ProductName as arguments.
3. Left click on New Project...
4. Left click on OK (button) in Add New Project.
5. Right click Reference in UnitTestProject1 project.
6. Left click on Add Reference...
7. Click on ConsoleApplication1 (dataitem) in Reference Manager under Solution -> Project.
8. click on OK (button) in Reference Manager.
Now the ConsoleApplication1 added as the reference for UnitTestProject1.
Replace the UnitTest1.cs file with the following code.
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject1
[TestClass]
public class UnitTest1
[TestMethod]
public void TestMethod1()
{
ConsoleApplication1.Program.AddProduct();
}
Right click inside the TestMothod1 then select Run Test.
Now you will get the error.
“Test method UnitTestProject1.UnitTest1.TestMethod1 threw exception:
System.InvalidOperationException: No connection string named 'NORTHWNDEntities' could be found in the application config file.”
Fix the error with adding the Entity Framework assembly and connection string into the Unit Test Project.
Well, we can manual create an app.config file but that is not going to be easy. The easy way is add the Entity Data Model follow the step 4 through step 20 in section Create an ADO.NET Entity Data Model in a Console Application.
You must then delete the edmx and other files that were created by the wizard except the App.config file.
You can now run the unit test again. You should see it green this time..
That isn't a unit test. Unit tests should be done entirely in memory and not talk to anything outside the code. What's being shown is an integration test. | http://blogs.msdn.com/b/mvpawardprogram/archive/2014/05/05/creating-unit-test-for-the-projects-using-microsoft-s-entity-framework.aspx | CC-MAIN-2014-35 | refinedweb | 639 | 53.58 |
Blog about technology, media and other interesting tidbits
For those, who don't like Python or IronPython, here is a pure C# version of Method Visualizer. The following screenshot shows it in action.
Here is a brief description about MethodViz:
MethodViz is a simple method hierarchy visualizer. It lets you see the method tree from a particular method. Let's see this with an example.
This is a simple diagram for a case where PublicMethod( ) is calling Help( ) which is then calling HelpMeToo( ). You can see that the root methods and the other methods are from different classes.
For more detailed description, see the following blog posts:
Currently MethodViz supports the following type of method calls.
Normal Calls:
Described above.
Interface Calls:
Similarly, it will detect the correct instance even if you are calling from an interface or an abstract. I'll leave the "How" section to another blog post.
public void CheckDraw(){ IShape d = new RectangleShape(); IShape d2 = new CircleShape(); d2.Draw(); d.Draw();}
Here IShape is an interface which is used to called the concrete implementations. The following is the generated graph for the above method.
Although not shown above, but the Draw( ) methods for each concrete implementation are calling another method as clear by the diagram.
Abstract Classes:
Similar to the interfaces, the abstract classes are also mapped clearly.
public void CheckAbstractImplementation( ){ AbsClass ab = new AbsClassImpl(); ab.MethodImpl(); ab.MethodNotImpl();}
In the above method, AbsClass is an abstract class where AbsClassImpl is the concrete implementation. Note that MethodImpl( ) is implemented by AbsClass whereas MethodNotImpl( ) is implemented by AbsClassImpl. Let's see how the diagram looks like.
Note the Class names highlighted by the red marker.
Cross Assembly Calls:
Another thing that it does it to automatically resolve assembly references ( * ) and connect those methods.
public void CrossAssemblyCall( ){ CecilSecondCase.CSCTypeA newObject = new CecilSecondCase.CSCTypeA(); newObject.HelloWorld();}
The above method creates an instance of CSCTypeA class which is in CecilSecondCase.dll assembly. (Shown below)
public class CSCTypeA{ public void HelloWorld( ) { this.SayHello("CecilSecondCase::HelloWorld"); }
private void SayHello(string msg) { CTCTypeA thirdCase = new CTCTypeA(); thirdCase.HelloWorld(); }}
This class in turn create an instance of CTCTypeA which resides in the CecilThirdCase.dll assembly (Not showing here as it is similar to CSCTypeA). Hence the flow looks like this:
Main Assembly -> CecilSecondCase -> CecilThirdCase
The final diagram for the above method tree looks like this:
(Marker is only used to clear the point)
( * ) There are some restrictions as it only tries in the current directory for the assembly with the dll extension only.
Issues:
The current release is like an alpha version of MethodViz. You may get incomplete graphs for some methods. In that case, you can check the log file generated in the exe directory.
The only known issue is no support for Generic method calls. So if your method contains a call to a generic method then this will definitely fail. You can just Continue there instead of Quit to check the other methods. It fails due to the IL representation of Generic method call.
newobj instance void CecilCase.Stack`1<int32>::.ctor()
This is a call to create a new object of a generic Stack. It blows up when the name is converted to XML and passed to XMLVisualizer to render because of invalid characters in XML.
update: FIX the above issue with generics. The same download link will get the updated source and binaries.
Download And Usage:
Download HereThe download contains the source and the binaries.
To try this, just extract is anywhere you like. You can start by running the "FrontEnd.exe" file in the bin\Debug folder. Once you see the window, you can open an assembly by click File -> Open Assembly. For playing with this, you can select "CecilCase.dll" which you'll find in the same directory and try out different methods.
Feedback:
I would really appreciate if you try this and see what works and what not. And also give your suggestions to include anything you like to see.
Nice control...
It seems that your examples about resolving virtual methods (i.e. interfaces and abstract classes) are too trivial.
Instanciating a concrete class, assigning it to a local and calling that interface rarely happens in the same metod body. It usually gets split between differnt methods: one store an interface instance, one makes the call. In that case, things become non trivial: any type that implements that interface could be passed, and there's no guarantee to resolve precisely the concrete type.
Great!
in AssemblyData.cs, the method "AddType" of FrontEnd.CecilAssemblyData class may throw a exception that is "a key has exited in a dictionary" when the program is loading an assembly dll(.net 1.1) file.
internal void AddType(TypeDefinition tDef)
{
if (Rules.IsValidType(tDef.FullName))
{
this.typeDic.Add(tDef.FullName, tDef);
}
}
Promising tool.
The main problem for me right now is zooming. I don't know if the graph library supports it, but zooming in/out with the mouse will be a great bonus.
Also, integration with Reflector to view the code for the methods will be great.
Greetings from Spain
Yes yes, please make this a Reflector plug-in
Pingback from links for 2008-07-25» ?????????? ???? ?????? | http://weblogs.asp.net/nleghari/archive/2007/04/08/methodviz-see-what-your-methods-are-doing.aspx | crawl-002 | refinedweb | 865 | 58.48 |
Hi guys,
This is not related to syntax or runtime problem. What I am going ask is more about how Linux and Windows handle writing data from buffer to a file. I have this code here, wrapped around a timing block, to write a buffer to a file.
Code:StartCounter(); if(rows != fwrite(image, cols, rows, fp)){ fprintf(stderr, "Error writing the image data in write_pgm_image().\n"); if(fp != stdout) fclose(fp); return(0); } test = GetCounter();Code:#include <shrUtils.h> #ifdef _WIN32 double PCFreq = 0.0; __int64 CounterStart = 0; #endif #ifdef __linux__ struct timeval ts_start,ts_end; #endif void StartCounter() { #ifdef _WIN32 LARGE_INTEGER li; if(QueryPerformanceFrequency(&li) == 0) printf("QueryPerformanceFrequency failed!\n"); PCFreq = (float)((li.QuadPart)/1000.0); QueryPerformanceCounter(&li); CounterStart = li.QuadPart; #endif #ifdef __linux__ gettimeofday(&ts_start, NULL); #endif } double GetCounter() { #ifdef _WIN32 LARGE_INTEGER li; QueryPerformanceCounter(&li); return (float)((li.QuadPart-CounterStart)/PCFreq); #endif #ifdef __linux__ gettimeofday(&ts_end, NULL); //time = timespec_sub(ts_end, ts_start); return (float)((ts_end.tv_sec - ts_start.tv_sec + 1e-6 * (ts_end.tv_usec - ts_start.tv_usec))*1000.0); #endif }
When I measure time to write data, I found out that:
1 - in Linux, the time to write data is linearly proportional to the data size.
2 - in Windows, the time to write data is quadratically proportional to the data size.
I think the fwrite function writes the data line by line to the file, therefore the linear relationship in Linux. But seems like Windows behaves differently. Do you think of any explanation for this?
Any help is greatly appreciate | http://forums.devshed.com/programming-42/linux-windows-write-timing-difference-934579.html | CC-MAIN-2016-36 | refinedweb | 248 | 51.24 |
"static" prefix - to parallel "this" prefix
Discussion in 'Java' started by Tim Tyler, Dec 5, 2004.
Page 1 of 2
Page 1 of 2
- Similar Threads
Static vs. non-static connectionNatan, May 24, 2004, in forum: ASP .Net
- Replies:
- 8
- Views:
- 7,646
- Sami Vaaraniemi
- May 26, 2004
Static classes with static membersBen, Jun 1, 2004, in forum: ASP .Net
- Replies:
- 3
- Views:
- 583
- Ben
- Jun 1, 2004
Static is REALLY Static!Paul W, May 3, 2005, in forum: ASP .Net
- Replies:
- 2
- Views:
- 512
Why do static and non-static method names collide?=?ISO-8859-1?Q?Thomas_Gagn=E9?=, Jul 2, 2003, in forum: Java
- Replies:
- 12
- Views:
- 6,435
- cgbusch
- Jul 5, 2003
- Replies:
- 1
- Views:
- 4,564
- Ryan Stewart
- Jan 16, 2004
removing a namespace prefix and removing all attributes not in that same prefixChris Chiasson, Nov 12, 2006, in forum: XML
- Replies:
- 6
- Views:
- 835
- Richard Tobin
- Nov 14, 2006 | http://www.thecodingforums.com/threads/static-prefix-to-parallel-this-prefix.138964/ | CC-MAIN-2016-36 | refinedweb | 154 | 70.33 |
Anyone know how to get the session storage to work when the user input is a date picker?
Current code:
import { session } from 'wix-storage';
$w.onReady(function () {
$w('#input3').value = session.getItem("date");
});
export function input3_change(event) { var date = $w('#input3').value session.setItem("date", date); }
Wix code SDK error: The value parameter that is passed to the value method cannot be set to the value Thu Jul 04 2019 00:00:00 GMT+0200 (sentraleuropeisk sommertid). It must be of type date. Thanks
The session storage contains a string - which is not a date. However, you can use the string to create a date object, which you can then use as the value of the date picker. Something like this:
Fantastic, thanks a lot!
When I copied and pasted the code you gave me, I got an error, but this piece of code worked: $w('#input3').value = new Date(session.getItem("date")); Is there a reason why you wrote '#input3' twice?
Anyways, its working now, thank you
@Mari Hmmm, I think it's a forum issue. I wrote #input3 only once.
@Yisrael (Wix) Ok I see, thanks for clarifying. Yisrael, could you please help me with another issue? I posted a new thread here: If you have time, I would appreciate it a lot, been dealing with this issue for weeks.. | https://www.wix.com/corvid/forum/community-discussion/session-storage-date-picker | CC-MAIN-2020-05 | refinedweb | 223 | 75.61 |
Python - Cinema 4D R20.057 - Export to Alembic without Dialog
Hi all,
i know the example on github. I tried to export to alembic. But the alembic-file is not written and I don't get any error. If I set the parameter to "c4d.FORMAT_ABCEXPORT" nothing changes. Only when I use "c4d.FORMAT_C4DEXPORT" it writes a file. But thats not what I want. When I use the script on Github and change the "filePath" to an actual path it works only with c4d Export. But not with Alembic.
I wonder what I do wrong. Heres the code:
""" Export Settings Example This example shows how to change an exporter settings. This works also for importers/scene loaders. """ import c4d from c4d import documents, plugins, storage def main(): # Get Alembic export plugin, 1028082 is its ID plug = plugins.FindPlugin(1028082, c4d.PLUGINTYPE_SCENESAVER) if plug is None: return # Get a path to save the exported file filePath = "D:\\a.abc" if filePath is None: return op = {} # Send MSG_RETRIEVEPRIVATEDATA to Alembic export plugin if plug.Message(c4d.MSG_RETRIEVEPRIVATEDATA, op): if "imexporter" not in op: return # BaseList2D object stored in "imexporter" key hold the settings abcExport = op["imexporter"] if abcExport is None: return # Change Alembic export settings abcExport[c4d.ABCEXPORT_SELECTION_ONLY] = True abcExport[c4d.ABCEXPORT_PARTICLES] = True abcExport[c4d.ABCEXPORT_PARTICLE_GEOMETRY] = True # Finally export the document if documents.SaveDocument(doc, filePath, c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST, c4d.FORMAT_ABCEXPORT): print "Document successfully exported to:" print filePath else: print "Export failed!" if __name__=='__main__': main()
Btw: I don't get any error. And if I change the parameter "c4d.FORMAT_ABCEXPORT" back to "1028082" doesnt change anything. And I dont want to get a dialog either.
It's the same with the simple code below:
import c4d from c4d import documents, plugins, storage def main(): # Get a path to save the exported file filePath = "D:\\hallo.abc" c4d.documents.SaveDocument(doc, filePath, c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST, c4d.FORMAT_ABCEXPORT) c4d.EventAdd() if __name__=='__main__': main()
Thx in advance!
Hi @PdZ, are you sure you get the permission(Cinema 4D) to write directly into a drive folder? Could you try on your desktop or any other one that you are sure is writable?
Cheers,
Maxime.
Dear m_adam,
thx for your response. Iam pretty sure C4D has permission to write but weirdly enough it only happens with exports other than .c4d.
Fortunately I was able to use R20 new feature to write alembics out by using the build in function "save as alembic and delete".
Hi @PdZ I'm not able to reproduce it, in a folder I do have the right to write, both success, in a folder I do not have the right to write both fails.
Could you try for a folder where you are sure your user is allowed to write such as a temp folder?
Cheers,
Maxime.
Yes it is! Thank you very much! | https://plugincafe.maxon.net/topic/11452/python-cinema-4d-r20-057-export-to-alembic-without-dialog | CC-MAIN-2020-10 | refinedweb | 471 | 60.21 |
No, I'm suggesting that we pull it in as a binary prereq, and that we
use the backport stuff instead of Doug's old stuff.
-Patrick
On 6/6/07, Kevin Sutter <kwsutter@gmail.com> wrote:
> Let me see if I understand the proposal...
>
> We want to get an updated version of Doug Lea's concurrency libraries into
> OpenJPA. Not as a binary prereq like Serp or Commons Collections. But,
> rather we will bring the source into the OpenJPA svn repository and build it
> like it was ours, but we don't want to change the package names?
>
> I think this is asking for problems down the road. At least with binary
> prereqs, we can identify the specific version that we require and deal with
> any incompatibilities between releases. But, if we just bring the source
> into our tree without re-packaging, then we have no idea whether we are
> running with the version that we ship or some other version that happens to
> be available via the application's classpath. As OpenJPA continues to be
> incorporated into larger and larger environments, we have to be concerned
> about our prereqs (source or binary) and how they will interact with the
> rest of the environment.
>
> I would vote to stick with our current practice of bringing in Doug Lea's
> libraries and putting them into our own packaging scheme to avoid any
> possible conflicts with other instances of these libraries.
>
> Thanks,
> Kevin
>
> On 6/4/07, Brian McCallister <brianm@skife.org> wrote:
> >
> >
> > On Jun 4, 2007, at 6:58 PM, Patrick Linskey wrote:
> >
> > > In fact, I think that not repackaging the
> > > backport classes is a good thing, as it lets people easily plug in the
> > > faster Java 5 version without having to then re-repackage those
> > > classes and recompile them.
> >
> > This is a really good reason to not renamespace, actually, as it is
> > reasonable for people to want to change between distributed options.
> >
> > -Brian
> >
>
--
Patrick Linskey
202 669 5907 | http://mail-archives.apache.org/mod_mbox/openjpa-dev/200706.mbox/%3C7262f25e0706060953p5c25b67bw9dd4b1c5c9ca4edb@mail.gmail.com%3E | CC-MAIN-2017-34 | refinedweb | 329 | 58.82 |
# Quick Sort Algorithm in JavaSript (pivot as the first element + pivot as the random element)
Introduction
------------
**Quick Sort** is one of the most famous and effective **Sorting Algorithms**. The comprehension of how it works will undoubtedly help you in your **JavaScript** learning. Also, questions on algorithms are popular in job interviews, so there is a big chance you will be asked to describe how **Quick Sort** works.
I’m sure that I convinced you that Quick Sort is important. Let’s start!

Basic knowledge for Quick Sort Implementation
---------------------------------------------
At first, this lesson assumes that you know how to work with arrays, loops and know the array’s methods in JavaScript. If not, you can read about some information in the appropriate links. And after reading you can return to this article.
**Arrays in JS**: <https://javascript.info/array>
**Loops in JS**: <https://javascript.info/while-for>
Array’s methods which are used for the Quick Sort Implementation:
* **push()**: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push>
* **concat()**: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat>
Implementation
--------------
Firstly, we need to write a function quickSort which will sort our array.
```
function quickSort(arr) {
//code
}
```
Okay, let’s start to fill out the body of our function.
Quick Sort is an algorithm which implements recursively. And thus we need to add a base case for quickSort function.
```
function quickSort(arr) {
if (arr.length < 2) return arr;
}
```
This string means that if the length is less than 2 we just return an array. We write it because we don’t need to sort an empty array or array with a single element.
The next step is to write the main variables which we need for our algorithm. There are pivot, left and right.
* **pivot** — the element of the array (in our case is the first element) which is compared with other elements in the same array.
* **left** — is an array that stores elements of the passed array which are less than the pivot.
* **right** — the same as left, but stores elements greater or equal to the pivot.
Let’s add all of them to our function.
```
function quickSort(arr) {
if (arr.length < 2) return arr;
let pivot = arr[0];
const left = [];
const right = [];
}
```
Now we need to sort elements of the passed array in **left** and **right** arrays. This requires a **for** loop.
```
function quickSort(arr) {
if (arr.length < 2) return arr;
let pivot = arr[0];
const left = [];
const right = [];
for (let i = 1; i < arr.length; i++) {
if (pivot > arr[i]) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
}
```
Here we just check each element of the passed array and compare it with the pivot. When a for loop iterates through all elements our left array fills with elements less than the pivot and right — greater than the pivot. The method **push** here adds elements at the end of the left and right arrays.
Let’s look at the simple example with the following array:
[5, 2, 6, 1, 30, -10].
Pivot is the first element. It is 5. The algorithm compares each element after the pivot. It compares 5 and 2. 2 is less and 5 (2 < 5) and hence 2 is added to the left array. Then it compares 5 and 6. 6 is greater than 5 (6 > 5) and the algorithm adds 6 to the right array. And it does the same with the other elements.
Final left and right arrays will look as follows:
* left: [2, 1, -10]
* right: [6, 30]
But now you likely have a question: “**And how does it help to sort the array?**” The answer is simple. We need to call our **quickSort** function recursively on our left and right arrays and insert between them the pivot. Why? Because pivot is greater than elements of the left array and less than elements of the right array. And thus it must be between them in our final sorted array.
Okay, let’s return to our code. In order to **return** the final sorted array, we need to write the return and the something which we want to return. In our case it is:
```
return quickSort(left).concat(pivot, quickSort(right));
```
In order to fully understand the Quick Sort Algorithm let’s continue with our example of [5, 2, 6, 1, 30, -10].
After one iteration we got the following result:
* left: [2, 1, -10]
* right: [6, 30]
Then the QuickSort algorithm does the operation of sorting with left [2, 1, -10] and right [6, 30] arrays. It means that our function will take 2 as the pivot of the left array and compare 1 and -10 with this pivot. And after it, we will get the following:
For left: [2, 1, -10]:
* left: [1, -10]
* right: []
For right: [6, 30]:
* left: []
* right: [30]
And it will be doing the same operation while will not achieve the true condition for already written string:
```
if (arr.length < 2) return arr;
```
In our example, there is only one array that doesn’t match this condition. It is left: [1, -10]. And now it will be iterated. Here is a result after the iteration:
For left: [1, -10] (pivot is 1):
* left: [-10]
* right: []
Yes, it’s cool! Now all our arrays match the appropriate condition. And after it, our **quickSort** function will return all these arrays with the help of the call stack. And in the final, our function will just return the sorted left array which will merge pivot and the sorted right array. The following line of code can tell us about this ( The **concat()** method is used to merge two or more arrays):
```
return quickSort(left).concat(pivot, quickSort(right));
```
Let’s look at the recursive stack of the left array. After it, your comprehension of the **Quick Sort Algorithm** will be advanced!
> [5, 2, 6, 1, 30, -10]
>
> ↓
> -
>
> left [2, 1, -10] & right [6, 30] (not touched in this example)
>
> ↓
> -
>
> left [1, -10] & right []
>
> ↓
> -
>
> left [-10] & right []
>
>
*Note: the sign "**↓**" here is just for explanation. It isn’t the part of JavaScript*
And when the left array riches an array with a single element [-10] the quickSort function will return results of the call stack. It will simply insert each pivot between the left and right arrays (**pivot is highlighted in bold and underlined**).
The sample: **left + pivot + right** (“+” = merge in this example).
> [**5**, 2, 6, 1, 30, -10] **(return [-10, 1, 2, 5, right array]])**
>
> ↑
> -
>
> left [**2**, 1, -10] **(return [-10, 1, 2])**
>
> ↑
> -
>
> left [**1**, -10] & right [] **(return [-10, 1])**
>
> ↑
> -
>
> left [-10] & right [] **(return [-10])**
>
>
The same operation will be for the right array:
> [**5**, 2, 6, 1, 30, -10] **(return [left array, 5, 6, 30]])**
>
> ↑
> -
>
> right: [**6**, 30] **(return [6, 30])**
>
> ↑
> -
>
> left [] & right [30] **(return [30])**
>
>
And eventually:
> return [left array(**-10, 1, 2**), pivot(**5**), right array(**6, 30**)]
>
> **Result: [-10, 1, 2, 5, 6, 30]**
>
>
The Final code
--------------
The final code of the Quick Sort function:
```
function quickSort(arr) {
if (arr.length < 2) return arr;
let pivot = arr[0];
const left = [];
const right = [];
for (let i = 1; i < arr.length; i++) {
if (pivot > arr[i]) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat(pivot, quickSort(right));
}
```
Moreover, you can look at the .gif explanation from Wikipedia.
I don’t know about you, but it’s always been difficult for me to understand such graphical explanations of algorithms. And so I write this article with the hope that there will be people who are just like me.
 Taken from [Wikipedia](https://en.wikipedia.org/wiki/Quicksort)
And what about efficiency?
--------------------------
**The average case** for the Quick Sort Algorithm is **O(n log n)** where n is the length of an array. But **the worst case** is **O(n²)**. You can look at the graph (X-axis is the number of elements in the array; Y-axis — operations or time)

In order to achieve the average case, we need to choose a random pivot each time. There are various implementations of Quick Sort with the random pivot but I usually do it so:
```
function quickSort(arr) {
if (arr.length < 2) return arr;
let min = 1;
let max = arr.length - 1;
let rand = Math.floor(min + Math.random() * (max + 1 - min));
let pivot = arr[rand];
const left = [];
const right = [];
arr.splice(arr.indexOf(pivot), 1);
arr = [pivot].concat(arr);
for (let i = 1; i < arr.length; i++) {
if (pivot > arr[i]) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quickSort(left).concat(pivot, quickSort(right));
}
```
Note: if you want the explanation of this code just writes about it in the comments below. If I see that people want to know it I will publish a new article “**Quick Sort with Random Pivot**” in a wink.
Conclusion
----------
I’m sure that after reading this article you fully understood the Quick Sort Algorithm and you will be confident in your job interview.
Moreover, if you want to plunge into algorithms learning I highly recommend you to read the book **[Aditya Bhargava “Grokking Algorithms”](https://github.com/KevinOfNeu/ebooks/blob/master/Grokking%20Algorithms.pdf)**(taken from <https://github.com/KevinOfNeu>). It contains a lot of simple explanations of all popular algorithms.
Maybe you have much simpler explanation of the Quick Sort Algorithm in JS. Write about it in the comments!
Also if you want to get notifications about my new articles you can follow me in Medium and my Twitter account:
* [Twitter](https://twitter.com/8Z64Su3u8Rfe7gf)
* [Medium](https://medium.com/@maxim_filanovich)
My social networks
------------------
If you have questions or you interested in my articles, you can check and subscribe on my social media:
* [GitHub](https://github.com/M-fil)
* [Telegram](https://t.me/Filan0vichMaxim)
* [VK](https://vk.com/id327021520) | https://habr.com/ru/post/490304/ | null | null | 1,665 | 65.42 |
RECOMMENDED: If you have Windows errors then we strongly recommend that you download and run this (Windows) Repair Tool.
Apr 4, 2008. in tMap component but i faced the following error. Exception in component tMap_1 java.lang.RuntimeException: java.text.ParseException: Unparseable date: "13 12 2011 06:00:00" at routines.TalendDate.parseDate(TalendDate.java: 643) at honey.create_my_first_job_0_1.Create_My_First_Job.
Error:"Unparseable date: "16/06/2013 00:00:00"" while scheduling a migrated Web Intelligence instances. The error appears with reports which contain date prompts.
Hi Experts,Can anyone please help me for the below queryOn the receiver side I need to get value as ‘ 2010-12-30TO8.00:00 ‘.To achive this in graphical mapping i used.
I want the date format as dd-MMM-yyyy. My code is: String v_date_str="Sun Mar 06 11:28:16 IST 2011"; DateFormat formatter; formatter = new.
When an issue is open, the "Fix Version/s" field conveys a target, not necessarily a commitment. When an issue is closed, the "Fix Version/s" field conveys the.
Hi,I am getting an "Unparseable date error", my source date format (from IDOC) is 27102006, in the target format it should be along with the time stamp like.
import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; public class.
Unparseable Date!!!. Hello everyone I had a.csv file and I converted it to a.arff file. When I tried to open the arff file I have got this error: File.arff not recognised as an 'Arff data.
Unparseable date exception if the date format is other than yyyy-MM-dd for the date range. [ERROR] ParseException.
Sales Forecast Error
Unparseable date error in WebSphere Portal. – dWAnswers. – LdapAdapter getDateString(Object) com.ibm.websphere.wim.exception. WIMSystemException: CWWIM1998E The following system exception occurred during processing: 'java.text.ParseException: Unparseable date: " 20160330080121.274000-0000Z"'. I have not seen this error before. What is going on?
Apr 23, 2017. below the error. Thanks a lot. Démarrage du job secondJob a 18:31 24/04/2017. [statistics] connecting to socket on port 3458 [statistics] connected. Exception in component tMap_1 java.lang.RuntimeException: java.text.ParseException: Unparseable date: "Begin date" at routines.TalendDate.
[4/21/16 10:04:28:564 EDT] 00000043 exception W com.ibm.ws.wim.adapter.ldap.LdapAdapter getDateString(Object) com.ibm.websphere.wim.exception.WIMSystemException: CWWIM1998E The following system exception occurred during processing: ‘java.text.ParseException: Unparseable date…
RECOMMENDED: Click here to fix Windows errors and improve system performance | http://visionsonore.net/unparseable-date-error/ | CC-MAIN-2018-17 | refinedweb | 426 | 54.9 |
:
- InheritanceType.SINGLE_TABLE - The whole inheritance hierarchy is mapped to one table. An object is stored in exactly one row in that table and the discriminator value stored in the discriminator column specifies the type of the object. Any fields not used in a superclass or a different branch of the hierarchy are set to NULL. This is the default inheritance mapping strategy used by JPA.
- InheritanceType.TABLE_PER_CLASS - Every concrete entity class in the hierarchy is mapped to a separate table. An object is stored in exactly one row in the specific table for its type. That specific table contains column for all the fields of the concrete class, including any inherited fields. This means that siblings in an inheritance hierarchy will each have their own copy of the fields they inherit from their superclass. A UNION of the separate tables is performed when querying on the superclass.
- InheritanceType.JOINED - Every class in the hierarchy is represented as a separate table, causing no field duplication to occur. An object is stored spread out over multiple tables; one row in each of the tables that make up its class inheritance hierarchy. The is-a relation between a subclass and its superclass is represented as a foreign key relation from the "subtable" to the "supertable" and the mapped tables are JOINed to load all the fields of an entity.
A nice comparison of the JPA inheritance mapping options with pictures, and including a description of the @MappedSuperclass option, can be found in the DataNucleus documentation.
Now the interesting question is: which method works best in what circumstances?
SINGLE_TABLE - Single table per class hierarchy
The SINGLE_TABLE strategy has the advantage of being simple. Loading entities requires querying only one table, with the discriminator column being used to determine the type of the entity. This simplicity also helps when manually inspecting or modifying the entities stored in the database.
A disadvantage of this strategy is that the single table becomes very large when there are a lot of classes in the hierarchy. Also, columns that are mapped to a subclass in the hierarchy should be nullable, which is especially annoying with large inheritance hierarchies. Finally, a change to any one class in the hierarchy requires the single table to be altered, making the SINGLE_TABLE strategy only suitable for small inheritance hierarchies.
TABLE_PER_CLASS - Table per concrete class
The TABLE_PER_CLASS strategy does not require columns to be made nullable, and results in a database schema that is relatively simple to understand. As a result it is also easy to inspect or modify manually.
A downside is that polymorphically loading entities requires a UNION of all the mapped tables, which may impact performance. Finally, the duplication of column corresponding to superclass fields causes the database design to not be normalized. This makes it hard to perform aggregate (SQL) queries on the duplicated columns. As such this strategy is best suited to wide, but not deep, inheritance hierarchies in which the superclass fields are not ones you want to query on.
JOINED - Table per class
The JOINED strategy gives you a nicely normalized database schema without any duplicate columns or unwanted nullable columns. As such it is best suited to large inheritance hierarchies, be the deep or wide.
This strategy does make the data harder to inspect or modify manually. Also, the JOIN operation needed to load entities can become a performance problem or a downright barrier to the size of your inheritance strategy. Also note that Hibernate does not correctly handle discriminator columns when using the JOINED strategy.
BTW, when using Hibernate proxies, be aware that lazily loading a class mapped with any of the three strategies above always returns a proxy that is an instanceof the superclass.
Are those all the options?
So to summarize you could say the following rules apply when choosing from JPA's standard inheritance mapping options:
- Small inheritance hierarchy -> SINGLE_TABLE.
- Wide inheritance hierarchy -> TABLE_PER_CLASS.
- Deep inheritance hierarchy -> JOINED.
But what if your inheritance hierarchy is very wide or very deep? And what if the classes in your system are modified often? As we found while building a persisted command framework and a flexible CMDB for our Java EE deployment automation product Deployit, the concrete classes at the bottom of a large inheritance hierarchy can change often. So these two questions often get a positive answer at the same time. Luckily there is one solution to both problems!
Using blobs
The first thing to note is that inheritance is a very large component of the object-relational impedance mismatch. And then question we should ask ourselves is: why are we even mapping all those often changing concrete classes to database tables? If object databases had really broken through, we might be better off storing those classes in such a database. As it is, relational database have inherited the earth so that is out of the question. It might also be that for a part of your object model the relational model actually makes sense because you want to perform queries and have the database manage the (foreign key) relations. But for some parts you are actually only interested in simple persistence of objects.
A nice example is the "persisted command framework" I mentioned above. The framework needs to store generic information about each command such as a reference to the "change plan" (a kind of execution context) it belongs to, start and end times, log output, etc. But it also needs to store a command object that represents the actual work to be done (an invocation of wsadmin or wlst or something similar in our case).
For the first part the hierarchical model is best suited. For the second part simple serialization will do. So we first define a simple interface that is implemented by the different command objects in our system:
public interface Command { void execute(); }
And then we create the entity that stores both the metadata (the data we want to store in a relational model) and the serialized command object:
@Entity public class CommandMetaData { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @ManyToOne private ChangePlan changePlan; private Date startOfExecution; private Date endOfExecution; @Lob private String log; @Lob @Column(name = "COMMAND", updatable = false) private byte[] serializedCommand; @Transient private Command command; public CommandMetaData(Command details) { serializedCommand = serializeCommand(details); } public Command getCommand() { if (command != null) { command = deserializeCommand(serializedCommand); } return command; } [... rest omitted ...] }
The serializedCommand field is a byte array that is stored as a blob in the database because of the @Lob annotation. The column name is explicitly set to "COMMAND" to prevent the default column name of "SERIALIZEDCOMMAND" from appearing in the database schema.
The command field is marked as @Transient to prevent it from being stored in the database.
When a CommandMetaData object is created, a Command object is passed in. The constructor serializes the command object and stores the results in the serializedCommand field. After that the command cannot be changed (there is no setCommand() method), so the serializedCommand can be marked as not updatable. This prevents that pretty big blob field from being written to the database every time another field of the CommandMetaData (such as the log field) is updated.
Every time the getCommand method is invoked, the command is deserialized if needed and then it is returned. The getCommand could be marked synchronized if this object were used in multiple concurrent threads.
Some things to note about this approach are:
- The serialization method used influences the flexibility of this approach. Standard Java serialization is simple but does not handle changing classes well. XML can be an alternative but that brings its own versioning problems. Picking the right serialization mechanism is left as an exercise for the reader.
- Although blobs have been around for a while, some databases still struggle with them. For example, using blobs with Hibernate and Oracle can be tricky.
- In the approach presented above, any changes made to the Command object after it has been serialized will not be stored. Clever use of the @PrePersist and @PreUpdate lifecycle hooks could solve this problem.
This semi-object database/semi-relational database approach to persistence worked out quite well for us. I am interested to hear whether other people have tried the same approach and how they fared. Or did you think of another solution to these problems?
For a list of all the JPA implementation pattern blogs, please refer to the JPA implementation patterns wrap-up.
Andrew Phillips -
June 21, 2009 at 9:23 pm
Is it desirable to have to the serializedCommand byte array as a member of your entity class? The transient command object would appear to be the one that is the "natural" member of your domain model - the fact that it happens to be persisted as a byte array is purely an implementation detail, and probably not something you would want to leak into your API in this way.
Would a Hibernate user type not be more appropriate in this case - I think there might even be a "Serializable2LobUserType" out there already.
Maarten Winkels -
June 22, 2009 at 3:00 am
@Andrew: The default for JPA is to store a complex, non-entity property in a BLOB. It uses standard Java Serialization of course. Due to its limitations Vincent mentions in the blog, the serialization/deserialization is performed in the Entity class, I suppose.
+1 for using a UserType for this kind of transformation. But I think UserTypes are Hibernate specific and not JPA-ish.
Vincent Partington -
June 22, 2009 at 8:27 am
@Andrew, @Maarten: As Maarten already guessed I perform the serialization/deserialization in the entity class to have more control over it. This way I can use different serialization mechanisms, set the blob field to be updatable, catch and handle ClassNotFoundExceptions and other serialization errors. Using a Hibernate UserType would have been nicer but does not work for all JPA providers.
The interesting thing with this and with other JPA implementation patterns (bidirectional associations, using @PreRemove, bidirectional associations vs. lazy loading, using UUIDs as primary keys) is that they all "pollute" the entity class with their "special JPA sauce". It would be nice if one could define an external "persistence handler" that takes care of all this nasty stuff. Something like a UserType but with more abilities. Instead of the @Pre/@Post lifecycle hooks with only invite you to do this kind of nasty stuff.
I guess this matches nicely with my comment at the beginning of the series that the JPA abstraction, as it is today, is pretty leaky.
Simon Massey -
September 18, 2009 at 12:56 am
We use the "clob/blob overflow column" pattern extensively in some framework code. In our case it is an XML serialization of the subclass fields. The proprietary framework in question is a few years old now so it is hibernate not jpa with interceptors not @pre/@Post hooks but doing exactly the same thing.
The framework allows for tens of thousands of custom types going into the same smallish set of entity tables. Our business users design new types on the fly from within the application and we use a custom class load to generate all the pojo classes at runtime on first use. So it has mega wide and mega deep hierarchies all generated at runtime.
The generated subclass types have unmapped properties fields with setters and getters. Within hibernate interceptor life cycle hooks we pack those unmapped subclass fields into the mapped xml base class blob to dehydrate the object to store it, then on rehydration unpack them from the xml to activate it. Once again you could do that with @pre/@post handlers.
It has been a few years since the first version of our framework. Your suggestion here on this blog is the first time I have head of anyone else doing the same thing.
Vincent Partington -
September 18, 2009 at 11:10 am
@Simon Massey: Using the @Pre/@Post handlers is an even neater way to solve this than doing it in the getters/setters as I propose. Basically, you actually implemented the "Clever use of the @PrePersist and @PreUpdate lifecycle hooks" I mention. 😉
Diigo Diary 08/08/2014 | Benx Blog -
August 8, 2014 at 2:31 am
[…] JPA implementation patterns: Mapping inheritance hierarchies | Xebia Blog […]
eddie -
October 6, 2015 at 7:58 am
Wonderful article here is one more nice and simple explanation. | http://blog.xebia.com/jpa-implementation-patterns-mapping-inheritance-hierarchies/ | CC-MAIN-2016-07 | refinedweb | 2,060 | 52.29 |
The product number of Sensor-Color LED is: MSDL11
Sensor-Color LED is full color LED, adopting single serial cascade protocol.
Only one I/O port can control the RGB color of each LED on the line.
If the power supply supports, it can support the cascade of as many as 1024 LEDs.
The ColorLED is a trinket which emits different colors based on the set red, green, and blue values. A Core module can control the ColorLED to output the desired colors.
Note: ColorLEDs can be connected together in a daisy chain fashion, and each ColorLED can be addressed individually using the index number. First ColorLED being 0, second ColorLED being 1, etc.
The ColorLED is used as an output pin. The library is based on the Adafruit_NeoPixel library (Read more) is used to control the ColorLED. Most of the functions are similar.
This is a simple example which:
Note: Important lines of code are highlighted.
//Include the required libraries to control the ColorLED
//Based on:
#include <Microduino_ColorLED.h>
//Define the pin the ColorLED is connected to
const int COLORLED_PIN = 6;
//Define the number of ColorLEDs daisy chained together
const int COLORLED_NUM = 1;
//Declare and initialize the ColorLED object
ColorLED strip = ColorLED(COLORLED_NUM, COLORLED_PIN);
void setup() {
// put your setup code here, to run once:
//Initial serial communication port at 9600 baud
Serial.begin(9600);
//Initialize the ColorLED class object
strip.begin();
//Initialize all ColorLEDs to 'off'
strip.show();
}
void loop() {
// put your main code here, to run repeatedly:
//Configure the first ColorLED to maximum red
strip.setPixelColor(0, 255, 0, 0);
//Set the ColorLED
strip.show();
//wait 1 second
delay(1000);
//Configure the first ColorLED to maximum green
strip.setPixelColor(0, 0, 255, 0);
//Set the ColorLED
strip.show();
//wait 1 second
delay(1000);
//Configure the first ColorLED to maximum blue
strip.setPixelColor(0, 0, 0, 255);
//Set the ColorLED
strip.show();
//wait 1 second
delay(1000);
}
Copy and paste the code above to the Arduino IDE or
Download the above example: n/a | http://wiki.microduinoinc.com/Sensor-Color_LED | CC-MAIN-2019-09 | refinedweb | 335 | 57.06 |
Beta Draft: 2017-03-31
Oracle JDK 9 Migration Guide
Release 9
E75632-02
April 2017
The purpose of this guide is to help you identify potential issues and give you suggestions on how to proceed as you migrate your existing Java application to JDK 9.
Every new Java SE release introduces some binary, source and behavioral incompatibilities with previous releases. The modularization of the Java SE Platform brings many benefits but also many changes. Code that uses only official Java SE Platform APIs and supported JDK-specific APIs should continue to work without change. Code that uses certain features or JDK-internal APIs may not run or may give different results.
To migrate your application, start by following the steps listed in Prepare for Migration.
Changes to the Installed JDK/JRE Image
Changes to Garbage Collection
Removed macOS-specific Features
Finally, once your application is running successfully on JDK 9, review Looking Forward, which will help you avoid problems with future releases.
This guide focuses on changes required to make your code run on JDK 9. For a comprehensive list of all of the new features of JDK 9, see Java Platform, Standard Edition What's New in JDK 9.
The steps in this section will assist you in your migration.
Get the JDK 9 Early Access Build
Run Your Program Before Recompiling
Update Third-Party Libraries
Download and install the latest Oracle JDK 9 early access release. Early access builds are only meant to be used for testing and debugging, not in production environments.
Try running your application on the Oracle JDK 9 early access version and see what happens. If your program uses only standard Java SE APIs, you may find that it runs without any modification.
Note:
Update Third-Party Libraries
Compile Your Application, and
When you run your application, look for warnings from the JVM about unrecognized VM options. If the VM fails to start, check for removed options, as VM flags that were deprecated in JDK 8 have been removed in JDK 9. See Removed GC Options.
If your application launches successfully, look carefully at your tests and make sure the behavior is the same as on JDK 8. For example, a few early adopters have noticed that their dates and currencies are formatted differently. See Use CLDR Locale Data by Default.
Even if your program appears to run successfully, you need to complete the rest of the steps in this guide, plus review the list of issues.
For every tool and third-party library that you use, you may need to have an updated version that supports JDK 9.
Check your third-party libraries and tools vendors websites for a version of each library or tool that is designed to work on Java 9. If one exists, download and install the new version.
If you use an IDE to develop your applications, it can help migrate existing code. The NetBeans, Eclipse, and IntelliJ IDEs all have early access versions available that include JDK 9 support.
You can see the status of the testing of many Free Open Source Software (FOSS) projects with OpenJDK builds at Quality Outreach on the OpenJDK wiki.
Compile your code using the JDK 9 compiler and check for warnings and errors.
Compilation may fail for a number of reasons specific to JDK 9.
Most of the JDK’s internal APIs have been made inaccessible by default. You may get compilation errors, or, at run time,
IllegalAccessErrors, that indicate that your application or its libraries are dependent on internal APIs .
To identify the dependencies, run the Java Dependency Analysis tool. See Run jdeps on Your Code. If possible, update your code to use the supported replacement APIs.
Check compilation warnings for any clues. You may see more deprecation warnings than previously. If you see deprecation with removal warnings, you should address those to avoid future problems.
If you use the underscore character ("_") as a one-character identifier in source code, it won’t compile in JDK 9. Its use generates a warning in JDK 8, and an error in JDK 9.
As an example, this code:
static Object _ = new Object();
generates the following error message from the compiler.
MyClass.java:2: error: as of release 9, '_' is a keyword, and may not be used as a legal identifier.
If you use the
-source and
-target options with
javac, check the values that you use. In JDK 9,
javac uses a "one plus three back" policy of supporting
-source and
-target options.
The supported
-source/-target values are 9 (the default), 8, 7, and 6 (6 is deprecated, warning issued when used).
In JDK 8,
-source and
-target values of 1.5/5 and earlier were deprecated and caused a warning to be generated. In JDK 9, those values cause an error.
>javac -source 5 -target 5 Sample.java warning: [options] bootstrap class path not set in conjunction with -source 1.5 error: Source option 1.5 is no longer supported. Use 1.6 or later. error: Target option 1.5 is no longer supported. Use 1.6 or later.
If possible, use the new
—release flag instead of
-source and
-target. The
—release N flag is conceptually a macro for
-source N -target N -bootclasspath $PATH_TO_rt.jar_FOR_RELEASE_N
The valid arguments for the
—release flag follow the same policy as for
-source and
-target, one plus three back.
javac can recognize and process class files of all previous JDKs, going all the way back to JDK 1.0.2 class files.
See JEP 182: Policy for Retiring javac -source and -target Options.
Run the
jdeps tool on your application. If you use internal APIs,
jdeps will suggest replacements to help you update your code.
jdeps is a static analysis tool that helps you see what packages and classes your applications and libraries depend on. Static analysis of code will not tell you everything. If you are using reflection to call an internal API,
jdeps will not warn you. At runtime, you may get a
java.lang.IllegalAccessException.
To look for dependencies on internal JDK APIs, run
jdeps with the
-jdkinternals option. For example, if you run
jdeps on a class that invokes
sun.misc.BASE64Encoder, you will see:
>jdeps -jdkinternals Sample.class Sample.class -> JDK removed internal API Sample -> sun.misc.BASE64Encoder JDK internal API (JDK removed internal API).BASE64Encoder Use java.util.Base64 @since 1.8
If you use Maven, there is a
jdeps plugin available.
For
jdeps syntax, see
jdeps in the Java Platform, Standard Edition Tools Reference for Oracle JDK.
If you find it necessary to use an internal API that has been made inaccessible by default, you can break encapsulation using the
--add-exports command line option described in JEP 261. This option should only be used as an aid to migration.
JDK 9 provides a new simplified version-string format. If your code relies on the version-string format to distinguish major, minor, security, and patch update releases, you may need to update it.
The format of the new version-string is:
$MAJOR.$MINOR.$SECURITY.$PATCH
For example, under the old scheme, the Java
9u5 release would have the version string
1.9.0_5-b20.
Under the new scheme, the short version of the same release is
9.0.1, and the long version is
9.0.1+20.
This change impacts java -version and related system properties, java.runtime.version, java.vm.version, java.specification.version, and java.vm.specification.version.
A simple Java API to parse, validate, and compare version strings has been added. See java.lang.Runtime.
See Version String Format in the Java Platform, Standard Edition Installation Guide and JEP 223: New Version-String Scheme.
The layout of files in the installed JDK and JRE image has changed in JDK 9.
After you install JDK 9, if you look at the file system, you’ll notice that the directory layout is different from that of previous releases.
In the past there was always a separate JRE, which you could download if you wanted a runtime environment, but not the full suite of developer tools. It consisted of a
jre directory which had a subset of the various runtime binaries, such as the
java launcher and other runtime tools.
If you wanted to develop software, you would download the full JDK, which wrapped that same
jre/ directory in a higher level
jdk/ directory and added more tools and libraries. In previous releases, both the
jre/ and
jdk/ directories each had their own
bin/ directories, resulting in duplicate binary files in the full JDK. In addition, the files that a user could edit and configure were scattered throughout the various directories. It wasn't clear exactly what files were intended to be tweaked by end users, and what files were internal to the JDK.
New Runtime Image Structure
In JDK 9, the JDK and JRE are two types of modular runtime images, where each contains the following directories:
bin: contains binary executables
conf: contains
.properties,
.policy, and other kinds of files intended to be edited by developers, deployers, and end users, which were formerly found in the
lib directory or its subdirectories.
lib: contains dynamically linked libraries and the complete internal implementation of the JDK.
There are still separate JDK and JRE downloads, but you get the same directory structure regardless of the image that you download. The JDK image contains the extra tools, such as
javac, and libraries that have historically been found in the JDK. There are no more
jdk/ vs
jre/ wrapper directories. and binaries (
java etc.) are not duplicated.
See JEP 220: Modular Run-Time Images.:
In JDK 9, ClassLoader::getSystemResource doesn’t return a URL pointing to a jar file (since there are no jar files). Instead it returns a valid URL.
For example, when run on JDK 8 the code:
ClassLoader.getSystemResource("java/lang/Class.class");
returns a jar URL of the form:
jar:file:/usr/local/jdk8/jre/lib/rt.jar!/java/lang/Class.class
which embeds a file URL to name the actual jar file within the run-time image. The getContent method of that URL object can be used to retrieve the content of the class file, via the built-in protocol handler for the jar URL scheme. A modular image doesn’t contain any jar files, so URLs of the above form make no sense.
The java.security.CodeSource API and security policy files use URLs to name the locations of code bases that are to be granted specific permissions. See Policy File Syntax in Java Platform, Standard Edition Security Developer's Guide. Components of the run-time system that require specific permissions are currently identified in the
conf/security/java.policy file via file URLs.
IDEs and other development tools require the ability to enumerate the class and resource files stored in a runtime image, and to read their contents directly by opening and reading
rt.jar and similar files. This is not possible with a modular image.
In previous releases, the extension mechanism made it possible for the runtime environment to find and load extension classes without specifically naming them on the class path.
In JDK 9, a more robust mechanism has been added to achieve the same result. Use upgradeable modules or put JARs on the classpath.
The
javac compiler and
java launcher will exit if the
java.ext.dirs system property is set, or if the
lib/ext directory exists. To additionally check the platform-specific system-wide directory, specify the
-XX:+CheckEndorsedAndExtDirs command-line option. This will cause the same exit behavior to occur if the directory exists and is not empty. The extension class loader is retained in JDK 9 for compatibility reasons..
If you need to use the extension classes, make sure the
jar files are on the
classpath.
See JEP 220: Modular Run-Time Images.
The
java.endorsed.dirs system property and the
lib/endorsed directory are no longer present. The
javac compiler and
java launcher will exit if either are detected.
In JDK 9, a more robust mechanism has been added to achieve the same result. Use upgradeable modules or put JARs on the classpath.
This mechanism was mostly intended for application servers to override components used in the JDK. Packages to be updated would be placed into JAR files, and the system property
java.endorsed.dirs would tell the Java runtime environment where to find them. If a value for this property was not specified, the default of
$JAVA_HOME/lib/endorsed would be used.
In JDK 8, you can use the
-XX:+CheckEndorsedAndExtDirs command-line argument to check for such directories anywhere on the system.
In JDK 9,.
This section highlights APIs that have been made inaccessible, removed, or altered in their default behavior. You may encounter the issues described in this section when compiling or running your application.
The Java team is committed to backwards compatibility. If an application runs in JDK 8, then it will run on JDK 9 as long as it uses APIs that are supported and intended for external use.
These include:
Supported APIs can be removed from the JDK, but only with advance notice. Find out if your code is using deprecated APIs by running the static analysis tool
jdeprscan.
The only java.* APIs that have been removed in JDK 9 are the previously deprecated methods from the java.util.logging.LogManager and java.util.jar.Pack200 packages:
java.util.logging.LogManager.addPropertyChangeListener java.util.logging.LogManager.removePropertyChangeListener java.util.jar.Pack200.Packer.addPropertyChangeListener java.util.jar.Pack200.Packer.removePropertyChangeListener java.util.jar.Pack200.Unpacker.addPropertyChangeListener java.util.jar.Pack200.Unpacker.removePropertyChangeListener
See JEP 162: Prepare for Modularization.
JDK 9 makes most of the JDK's internal APIs inaccessible by default, but leaves a few widely-used internal APIs accessible until supported replacements exist for most or all of their functionality.
Unlike the previously described APIs, almost all of the sun.* APIs are unsupported, JDK-internal APIs, and may go away at any time.
A few sun.* APIs have been removed in JDK 9. Notably, sun.misc.BASE64Encoder and sun.misc.BASE64Decoder have been removed. Instead, use the supported java.util.Base64 class, which was added in JDK 8.
These APIs are accessible by default at run time. They have been moved to the jdk.unsupported module, which is present in the JRE and JDK images. Modules that need these APIs must declare a dependency upon the jdk.unsupported module.
The remaining internal APIs in the sun.misc and sun.reflect packages have been moved, since they should not be accessible. See JEP 260: Encapsulate Most Internal APIs. If you need to use one of these internal APIs, you can break encapsulation using the
--add-exports command line option described in JEP 261. This option should only be used as a temporary aid to migration.
The java.awt.peer and java.awt.dnd.peer packages are not accessible in JDK 9. The packages were never part of the Java SE API, despite being in the java.* namespace.
All methods in the Java SE API that refer to types defined in these packages have been removed from JDK 9. Code that calls a method which previously accepted or returned a type defined in these packages will no longer compile or run. For example:
if (component.getPeer() instanceof java.awt.peer.LightweightPeer)
The non-standard package com.sun.image.codec.jpeg has been removed. Use the Java Image I/O API instead.
com.sun.image.codec.jpeg was added in JDK 1.2 as a non-standard Image I/O specification.
The RMI HTTP proxy implementation and RMI/JRMP HTTP tunneling implementation have been removed. This mechanism was deprecated in JDK 8.
The following system properties have been removed in JDK 9:
sun.rmi.transport.proxy.logLevel
sun.rmi.transport.tcp.proxy
sun.rmi.transport.proxy.connectTimeout
sun.rmi.transport.proxy.eagerHttpFallback
java.rmi.server.disableHttp
javac and
java. In JDK 9, the
-profile option is supported by
javac only in conjunction with the
--release 8 option, and is not supported by
java.
JDK 9 allows you to choose the modules that are used at compile and run time. By specifying modules with the new
--limit-modules option, you can obtain the same APIs that are in the compact profiles. This option is supported by both
javac and
java, as shown in the following examples:
javac --limit-modules java.base,java.logging MyApp.java
java --limit-modules java.base,java.logging MyApp
For the
compact1 profile: java.base, java.logging, java.scripting
For the
compact2 profile: java.base, java.logging, java.scripting, java.rmi, java.sql, java.xml
For the
compact3 profile:, you may see that you do not need to include that entire set of modules when you build your application. See
jdeps in Java Platform, Standard Edition Tools Reference for Oracle JDK.
See JEP 200: The Modular JDK. is, e.g.,
java.locale.providers=COMPAT,CLDR
See CLDR Locale Data Enabled by Default in the Java Platform, Standard Edition Internationalization Guide and JEP 252: Use CLDR Locale Data by Default.
Thread.stop(Throwable) is unsupported in JDK 9. If you use it, you will get an UnsupportedOperationException.
Thread.stop(Throwable), which forces the target thread to stop and throw a given Throwable as an exception, has the potential to compromise security. Objects may be left in an inconsistent state or the exception may be something that the thread is not prepared to handle.
There is no change to the deprecated no-argument Thread.stop() method.
See Java Thread Primitive Deprecation in the JDK 8 documentation.
The default java.policy no longer grants stopThread runtime permission in JDK 9.
In previous releases, untrusted code had the stopThread runtime permission by default. This allows untrusted code to call Thread.stop on threads other than the current one. Trusted code should not be expected to gracefully handle an arbitrary exception thrown asynchronously.
conf/security/java.policy:
permission java.lang.RuntimePermission "stopThread";
The ability to request a version of the JRE that is not the JRE being launched at launch time is removed in JDK 9.
Modern applications are typically deployed via launching an application. Version selection was possible through both a command-line option and manifest entry in the application's JAR file.
javalauncher is modified as follows:
-version:option is given on the command line.
JRE-Versionmanifest entry is found in a jar file.
See JEP 231: Remove Launch-Time JRE Version Selection.
In JDK 9, the ability to deploy an applet as a serialized object is not supported. With modern compression and JVM performance, there is no benefit to deploying an applet in this way.
The
object attribute of the
applet tag and the
object and
java object applet parameter tags are ignored during applet launching.
Instead of serializing applets, use standard deployment strategies.
JNLP has been updated to remove inconsistencies, make code maintenance easier, and enhance security.
JNLP has been updated as follows:
&replaces
&in JNLP file.
The JNLP file syntax now conforms with the XML specification and all JNLP files should be able to be parsed by standard XML parsers.
JNLP files allow you to specify complex comparisons. Previously this was done using
& but this not supported in standard XML. If you are using
& to create complex comparisons, then replace it with
& in your JNLP file.
& is compatible with all versions of JNLP.
Comparison of numeric version element types against non-numeric version element types.
Previously, when an
int version element was compared with another version element that could not be parsed as an
int, the version elements were compared lexicographically by ASCII value.
In JDK 9, if the element that can be parsed as an
int.
java(or
j2se) elements.
This is now permitted in the specification. It was previously supported, but this support was not reflected in the specification.
The JNLP specification has been enhanced to add a
"type" attribute to
application-desc element, and add sub-element
"param" in
application-desc (as it already is in
applet-desc).
This does not cause problems with existing applications because the previous way of specifying a JavaFX application is still supported.
See the JNLP specification updates at JSR-056.
The Garbage-First Garbage Collector (G1 GC) is the default garbage collector on 32- and 64-bit server configurations..
The following GC combinations will cause your application to not start in JDK 9.
DefNew + CMS
ParNew + SerialOld
Incremental CMS
The foreground mode for CMS has also been removed. The command line flags that were removed are
-Xincgc,
-XX:+CMSIncrementalMode,
-XX:+UseCMSCompactAtFullCollection,
-XX:+CMSFullGCsBeforeCompaction, and
-XX:+UseCMSCollectionPassing..
See JEP 214: Remove GC Combinations Deprecated in JDK 8.
Removed Permanent Generation
The permanent generation has been removed from the Java HotSpot Virtual Machine and therefore the options for tuning the size of the permanent generation have been removed.
Class metadata, interned strings, and class static variables have been moved to either the Java heap or native memory. Tools that are aware of the permanent generation may have to be updated.
The following options related to permanent generation, deprecated in JDK 8, are removed in JDK 9:
-XX:MaxPermSize=size: Sets the maximum size of the permanent generation
-XX:PermSize=size: Sets the initial size of the permanent generation
You should remove these options from your scripts. In JDK 9, the JVM issues a warning.
See JEP 122: Remove the Permanent Generation.
Garbage Collection (GC) logging now uses the JVM unified logging framework, and there are some differences between the new and the old logs. Any GC log parsers you are working with will probably need to change.
You may also need to update your JVM logging options. All GC-related logging should use the
gc tag, (e.g.,
—Xlog:gc), usually in combination with other tags. The
—XX:+PrintGCDetails and
-XX:+PrintGC options have been deprecated.
See Enable Logging with the JVM Unified Logging Framework in the Java Platform, Standard Edition Tools Reference for Oracle JDK and JEP 271: Unified GC Logging.
JavaDB, which was a rebranding of Apache Derby, is not included in JDK 9.
JavaDB was bundled with JDK 7 and JDK 8. It was found in the
db directory of the JDK installation directory.
You can download and install Apache Derby from Apache Derby Downloads.
The
hprof agent library has been removed.
The
hprof agent was written as demonstration code for the JVM Tool Interface and not intended to be a production tool. The useful features of the
hprof agent have been superseded by better alternatives, including several that are included in the JDK.
To create heap dumps in the
hprof format, use a diagnostic command or
jmap:
jcmd <pid> GC.heap_dump. See jcmd.
jmap -dump. See jmap.
For allocation profiler functionality, use the Java VisualVM tool.
CPU profiler capabilities are provided by the Java VisualVM and Java Flight Recorder, both of which are bundled with the JDK.
See JEP 240: Remove the JVM TI hprof Agent.
The jhat tool was an experimental, unsupported heap visualization tool added in JDK 6. Superior heap visualizers and analyzers have been available for many years.
The launchers
java-rmi.exe from Windows and
java-rmi.cgi from Linux and Solaris have been removed.
java-rmi.cgi was in
$JAVA_HOME/bin on Linux.
The IIOP transport support from the JMX RMI Connector along with its supporting classes have been removed in JDK 9.
In JDK 8, support for IIOP transport was downgraded from required to optional. This was the first step in a multi-release effort to remove support for the IIOP transport from the JMX Remote API. In JDK 9, support for IIOP has been removed completely.
Public API changes include:
javax.management.remote.rmi.RMIIIOPServerImpl class has been deprecated. Upon invocation, all its methods and constructors throw
java.lang.UnsupportedOperationException with an explanatory message.
Two classes,
org.omg.stub.javax.management.rmi._RMIConnection_Stub, and
org.omg.stub.javax.management.rmi._RMIConnection_Tie, are not generated.
In JDK 9, Windows 32 client VM is dropped and only a server VM is offered.
JDK 8 and earlier releases offered both a client JVM and a server JVM for Windows 32-bit systems. JDK 9 offers only the server JVM. The server JVM is tuned to maximize peak operating speed.
Visual VM is a tool that provides information about code running on a Java Virtual Machine. It was provided with JDK 6, JDK 7, and JDK 8.
Visual VM is not bundled with JDK 9. If you would like to use Visual VM with JDK 9, you can get it from the Visual VM open source project site.
More information about Visual VM can be found on the NetBeans Profiler and Visual VM blog.
The
native2ascii tool is removed in JDK 9. Because JDK 9 supports UTF-8 based properties resource bundles, the conversion tool for UTF-8 based properties resource bundles to ISO-8859-1 is no longer needed.
See UTF-8 Properties Files in Java Platform, Standard Edition Internationalization Guide
This section includes macOS-specific features that have been removed in JDK 9.
The
java.awt.Desktop class now contains replacements for the APIs in the JDK-internal
com.apple.eawt and
com.apple.eio packages. The new APIs supersede the macOS APIs and are platform independent.
Internal APIs
com.apple.eawt and
com.apple.eio packages are not accessible by default in JDK 9. Existing libraries or applications that use the internal classes in the
apple and
com.apple packages and their sub-packages will need to migrate to the new API.
The
com.apple.concurrent and
apple.applescript packages are removed without any replacement.
See JEP 272: Platform-Specific Desktop Features.
AppleScript engine, a platform-specific javax.script implementation, has been removed without any replacement in JDK 9.
The AppleScript engine has been mostly unusable in recent releases. The functionality only worked in JDK 7 or JDK 8 on systems that already had Apple's version of
AppleScriptEngine.jar on the system.
The
com.apple.concurrent.Dispatch API, a seldom-used, unsupported macOS-specific API, is removed from JDK 9.
If your application used this API, use the standard
java.util.concurrent.Executor and
java.util.concurrent.ExecutorService implementations instead.
Once you have your application working on JDK 9, here are some suggestions that can help you get the most from the Java SE platform.
Read Java Platform, Standard Edition What's New in JDK 9 to learn about new features of JDK 9.
If needed, cross-compile to an older release of the platform using the new
–release flag in
javac.
Take advantage of your IDE’s suggestions for updating your code with the latest features.
Find out if your code is using deprecated APIs by running the static analysis tool
jdeprscan. As already mentioned in this guide, supported APIs can be removed from the JDK, but only with advance notice.
For information about Oracle's commitment to accessibility, visit the Oracle Accessibility Program website at.
Access to Oracle Support
Oracle customers that have purchased support have access to electronic support through My Oracle Support. For information, visit or visit if you are hearing impaired.
Java Platform, Standard Edition Oracle JDK 9 Migration Guide, Release 9
E75632-02
This guide will help you migrate your application to Oracle JDK. | https://docs.oracle.com/javase/9/migrate/toc.htm | CC-MAIN-2017-17 | refinedweb | 4,554 | 58.28 |
mock alternatives and similar packages
Based on the "Testing" category
hound9.8 0.0 mock VS houndElixir library for writing integration tests and browser automation.
ex_machina9.8 3.0 mock VS ex_machinaFlexible test factories for Elixir. Works out of the box with Ecto and Ecto associations.
wallaby9.7 7.0 mock VS wallabyWallaby helps test your web applications by simulating user interactions concurrently and manages browsers.
meck9.6 5.5 mock VS meckA mocking library for Erlang.
proper9.6 6.8 mock VS properPropEr (PROPerty-based testing tool for ERlang) is a QuickCheck-inspired open-source property-based testing tool for Erlang.
mox9.4 5.1 mock VS moxMocks and explicit contracts for Elixir.
faker9.4 7.2 mock VS fakerFaker is a pure Elixir library for generating fake data.
espec9.4 3.8 mock VS especBDD test framework for Elixir inspired by RSpec.
mix_test_watch9.3 0.7 mock VS mix_test_watchAutomatically run your Elixir project's tests each time you save a file.
bypass9.3 6.5 mock VS bypassBypass provides a quick way to create a mock HTTP server with a custom plug.
ExVCR9.2 5.5 mock VS ExVCRHTTP request/response recording library for Elixir, inspired by VCR.
StreamData9.2 3.8 mock VS StreamDataData generation and property-based testing for Elixir. 🔮
excheck8.4 0.0 mock VS excheckProperty-based testing library for Elixir (QuickCheck style).
Quixir8.0 0.0 mock VS QuixirProperty-based testing for Elixir
white_bread8.0 1.5 mock VS white_breadStory based BDD in Elixir using the gherkin syntax.
amrita7.9 0.0 mock VS amritaA polite, well mannered and thoroughly upstanding testing framework for Elixir.
ponos7.7 0.0 mock VS ponosPonos is an Erlang application that exposes a flexible load generator API.
power_assert7.6 0.0 mock VS power_assertPower Assert in Elixir. Shows evaluation results each expression.
blacksmith7.5 0.0 mock VS blacksmithData generation framework for Elixir.
espec_phoenix7.4 0.0 mock VS espec_phoenixESpec for Phoenix web framework.
shouldi7.3 0.0 mock VS shouldiElixir testing libraries with nested contexts, superior readability, and ease of use.
FakerElixir7.1 0.0 mock VS FakerElixirFakerElixir generates fake data for you.
pavlov7.0 0.0 mock VS pavlovBDD framework for your Elixir projects.
chaperon7.0 2.4 mock VS chaperonAn HTTP service performance & load testing framework written in Elixir.
katt6.7 0.0 mock VS kattKATT (Klarna API Testing Tool) is an HTTP-based API testing tool for Erlang.
ex_unit_notifier6.6 0.0 mock VS ex_unit_notifierDesktop notifications for ExUnit.
Stubr6.4 0.0 mock VS StubrStubr - a stubbing framework for Elixir
ex_spec6.2 0.0 mock VS ex_specBDD-like syntax for ExUnit.
FakeServer6.2 0.9 mock VS FakeServerFakeServer integrates with ExUnit to make external APIs testing simpler
Mockery5.9 0.4 mock VS MockerySimple mocking library for asynchronous testing in Elixir.
blitzy5.9 0.0 mock VS blitzyA simple HTTP load tester in Elixir.
mecks_unit5.1 3.4 mock VS mecks_unitA package to elegantly mock module functions within (asynchronous) ExUnit tests using meck.
Walkman4.9 0.1 mock VS WalkmanIsolate tests from the real world, inspired by Ruby's VCR.
factory_girl_elixir4.7 0.0 mock VS factory_girl_elixirMinimal implementation of Ruby's factory_girl in Elixir.
test_selector4.6 4.6 mock VS test_selectorA set of test helpers that make sure you always select the right elements in your Phoenix app.
double4.5 0.0 mock VS doubleCreate stub dependencies for testing without overwriting global modules.
definject4.3 8.0 mock VS definjectUnobtrusive dependency injector for Elixir.
cobertura_cover3.9 0.0 mock VS cobertura_coverWrites a coverage.xml from mix test --cover file compatible with Jenkins' Cobertura plugin.
ex_parameterized3.8 2.6 mock VS ex_parameterizedSimple macro for parametarized testing.
exkorpion3.7 0.0 mock VS exkorpionA BDD library for Elixir developers.
mix_erlang_tasks3.7 0.0 mock VS mix_erlang_tasksCommon tasks for Erlang projects that use Mix.
mix_eunit3.6 0.0 mock VS mix_eunitA Mix task to execute eunit tests.
ex_unit_fixtures3.4 0.0 mock VS ex_unit_fixturesA library for defining modular dependencies for ExUnit tests.
hypermock3.4 0.0 mock VS hypermockHTTP request stubbing and expectation Elixir library.
ElixirMock3.1 2.6 mock VS ElixirMock(alpha) Sanitary mock objects for elixir, configurable per test and inspectable
efrisby3.0 0.0 mock VS efrisbyA REST API testing framework for erlang.
apocryphal2.9 0.0 mock VS apocryphalSwagger based document driven development for ExUnit.
test_that_json2.1 0.0 mock VS test_that_jsonJSON assertions and helpers for your Elixir testing needs.
kovacs2.1 0.0 mock VS kovacsA simple ExUnit test runner.
ExopData2.1 0.4 mock VS ExopDataA library that helps you to write property-based tests by providing a convenient way to define complex custom data generators.
Scout APM: Application Performance Monitoring
Do you think we are missing an alternative of mock or a related project?
Popular Comparisons
README
Mock
A mocking library for the Elixir language.
We use the Erlang meck library to provide module mocking functionality for Elixir. It uses macros in Elixir to expose the functionality in a convenient manner for integrating in Elixir tests.
See the full reference documentation.
Table of Contents
- Mock
- Installation
- with_mock - Mocking a single module
- with_mocks - Mocking multiple modules
- test_with_mock - with_mock helper
- setup_with_mocks - Configure all tests to have the same mocks
- Mocking input dependant output
- Mocking functions with different arities
- passthrough - partial mocking of a module
- Assert called - assert a specific function was called
- Assert not called - assert a specific function was not called
- Assert called exactly - assert a specific function was called exactly x times
- NOT SUPPORTED - Mocking internal function calls
- Tips
- Suggestions
Installation
First, add mock to your
mix.exs dependencies:
def deps do [{:mock, "~> 0.3.0", only: :test}] end
and run
$ mix deps.get.
with_mock - Mocking a single module
The Mock library provides the
with_mock macro for running tests with
mocks.
For a simple example, if you wanted to test some code which calls
HTTPotion.get to get a webpage but without actually fetching the
webpage you could do something like this:
defmodule MyTest do use ExUnit.Case, async: false import Mock test "test_name" do with_mock HTTPotion, [get: fn(_url) -> "<html></html>" end] do assert "<html></html>" == HTTPotion.get("") end end end
The
with_mock macro creates a mock module. The keyword list provides a set
of mock implementation for functions we want to provide in the mock (in
this case just
get). Inside
with_mock we exercise the test code
and we can check that the call was made as we expected using
called and
providing the example of the call we expected.
with_mocks - Mocking multiple modules
You can mock up multiple modules with
with_mocks.
defmodule MyTest do use ExUnit.Case, async: false import Mock test "multiple mocks" do with_mocks([ {Map, [], [get: fn(%{}, "") -> "<html></html>" end]}, {String, [], [reverse: fn(x) -> 2*x end, length: fn(_x) -> :ok end]} ]) do assert Map.get(%{}, "") == "<html></html>" assert String.reverse(3) == 6 assert String.length(3) == :ok end end end
The second parameter of each tuple is
opts - a list of optional arguments
passed to meck.
test_with_mock - with_mock helper
An additional convenience macro
test_with_mock is supplied which internally
delegates to
with_mock. Allowing the above test to be written as follows:
defmodule MyTest do use ExUnit.Case, async: false import Mock test_with_mock "test_name", HTTPotion, [get: fn(_url) -> "<html></html>" end] do HTTPotion.get("") assert_called HTTPotion.get("") end end
The
test_with_mock macro can also be passed a context argument
allowing the sharing of information between callbacks and the test
defmodule MyTest do use ExUnit.Case, async: false import Mock setup do doc = "<html></html>" {:ok, doc: doc} end test_with_mock "test_with_mock with context", %{doc: doc}, HTTPotion, [], [get: fn(_url, _headers) -> doc end] do HTTPotion.get("", [foo: :bar]) assert_called HTTPotion.get("", :_) end end
setup_with_mocks - Configure all tests to have the same mocks
The
setup_with_mocks mocks up multiple modules prior to every single test
along while calling the provided setup block. It is simply an integration of the
with_mocks macro available in this module along with the
setup
macro defined in elixir's
ExUnit.
defmodule MyTest do use ExUnit.Case, async: false import Mock setup_with_mocks([ {Map, [], [get: fn(%{}, "") -> "<html></html>" end]} ]) do foo = "bar" {:ok, foo: foo} end test "setup_with_mocks" do assert Map.get(%{}, "") == "<html></html>" end end
The behaviour of a mocked module within the setup call can be overridden using any
of the methods above in the scope of a specific test. Providing this functionality
by
setup_all is more difficult, and as such,
setup_all_with_mocks is not currently
supported.
Currently, mocking modules cannot be done asynchronously, so make sure that you
are not using
async: true in any module where you are testing.
Also, because of the way mock overrides the module, it must be defined in a separate file from the test file.
Mocking input dependant output
If you have a function that should return different values depending on what the input is, you can do as follows:
defmodule MyTest do use ExUnit.Case, async: false import Mock test "mock functions with multiple returns" do with_mock(Map, [ get: fn (%{}, "") -> "<html>Hello from example.com</html>" (%{}, "") -> "<html>example.org says hi</html>" (%{}, url) -> conditionally_mocked(url) end ]) do assert Map.get(%{}, "") == "<html>Hello from example.com</html>" assert Map.get(%{}, "") == "<html>example.org says hi</html>" assert Map.get(%{}, "") == "<html>Hello from example.xyz</html>" assert Map.get(%{}, "") == "<html>example.tech says hi</html>" end end def conditionally_mocked(url) do cond do String.contains?(url, ".xyz") -> "<html>Hello from example.xyz</html>" String.contains?(url, ".tech") -> "<html>example.tech says hi</html>" end end end
Mocking functions with different arities
You can mock functions in the same module with different arity:
defmodule MyTest do use ExUnit.Case, async: false import Mock test "mock functions with different arity" do with_mock String, [slice: fn(string, range) -> string end, slice: fn(string, range, len) -> string end] do assert String.slice("test", 1..3) == "test" assert String.slice("test", 1, 3) == "test" end end end
passthrough - partial mocking of a module
By default, only the functions being mocked can be accessed from within the test.
Trying to call a non-mocked function from a mocked Module will result in an error.
This can be circumvented by passing the
:passthrough option like so:
defmodule MyTest do use ExUnit.Case, async: false import Mock test_with_mock "test_name", IO, [:passthrough], [] do IO.puts "hello" assert_called IO.puts "hello" end end
Assert called - assert a specific function was called
You can check whether or not your mocked module was called.
Assert called - specific value
It is possible to assert that the mocked module was called with a specific input.
defmodule MyTest do use ExUnit.Case, async: false import Mock test "test_name" do with_mock HTTPotion, [get: fn(_url) -> "<html></html>" end] do HTTPotion.get("") assert_called HTTPotion.get("") end end end
Assert called - wildcard
It is also possible to assert that the mocked module was called with any value
by passing the
:_ wildcard.
defmodule MyTest do use ExUnit.Case, async: false import Mock test "test_name" do with_mock HTTPotion, [get: fn(_url) -> "<html></html>" end] do HTTPotion.get("") assert_called HTTPotion.get(:_) end end end
Assert called - pattern matching
assert_called will check argument equality using
== semantics, not pattern matching.
For structs, you must provide every property present on the argument as it was called or
it will fail. To use pattern matching (useful when you only care about a few properties on
the argument or need to perform advanced matching like regex matching), provide custom
argument matcher(s) using
:meck.is/1.
defmodule User do defstruct [:id, :name, :email] end defmodule Network do def update(%User{} = user), do: # ... end defmodule MyTest do use ExUnit.Case, async: false import Mock test "test_name" do with_mock Network, [update: fn(_user) -> :ok end] do user = %User{id: 1, name: "Jane Doe", email: "jane.doe@gmail.com"} Network.update(user) assert_called Network.update( :meck.is(fn user -> assert user.__struct__ == User assert user.id == 1 # matcher must return true when the match succeeds true end) ) end end end
Assert not called - assert a specific function was not called
assert_not_called will assert that a mocked function was not called.
defmodule MyTest do use ExUnit.Case, async: false import Mock test "test_name" do with_mock HTTPotion, [get: fn(_url) -> "<html></html>" end] do # Using Wildcard assert_not_called HTTPotion.get(:_) HTTPotion.get("") # Using Specific Value assert_not_called HTTPotion.get("") end end end
Assert called exactly - assert a specific function was called exactly x times
assert_called_exactly will assert that a mocked function was called exactly the expected number of times.
defmodule MyTest do use ExUnit.Case, async: false import Mock test "test_name" do with_mock HTTPotion, [get: fn(_url) -> "<html></html>" end] do HTTPotion.get("") HTTPotion.get("") # Using Wildcard assert_called_exactly HTTPotion.get(:_), 2 # Using Specific Value assert_called_exactly HTTPotion.get(""), 2 end end end
Assert call order
call_history will return the
meck.history(Module) allowing you assert on the order of the function invocation:
defmodule MyTest do use ExUnit.Case, async: false import Mock test "test_name" do with_mock HTTPotion, [get: fn(_url) -> "<html></html>" end] do HTTPotion.get("") assert call_history(HTTPotion) == [ {pid, {HTTPotion, :get, [""]}, "<html></html>"} ] end end end
You can use any valid Elixir pattern matching/multiple function heads to accomplish
this more succinctly, but remember that the matcher will be executed for all function
calls, so be sure to include a fallback case that returns
false. For mocked functions
with multiple arguments, you must include a matcher/pattern for each argument.
defmodule Network.V2 do def update(%User{} = user, changes), do: # ... def update(id, changes) when is_integer(id), do: # ... def update(_, _), do: # ... end defmodule MyTest do use ExUnit.Case, async: false import Mock test "test_name" do with_mock Network.V2, [update: fn(_user, _changes) -> :ok end] do Network.V2.update(%User{id: 456, name: "Jane Doe"}, %{name: "John Doe"}) Network.V2.update(123, %{name: "John Doe", email: "john.doe@gmail.com"}) Network.V2.update(nil, %{}) # assert that `update` was called with user id 456 assert_called Network.V2.update( :meck.is(fn %User{id: 456} -> true _ -> false end), :_ ) # assert that `update` was called with an email change assert_called Network.V2.update( :_, :meck.is(fn %{email: "john.doe@gmail.com"} -> true _ -> false end) ) end end end
NOT SUPPORTED - Mocking internal function calls
A common issue a lot of developers run into is Mock's lack of support for mocking internal functions. Mock will behave as follows:
defmodule MyApp.IndirectMod do def value do 1 end def indirect_value do value() end def indirect_value_2 do MyApp.IndirectMod.value() end end
defmodule MyTest do use ExUnit.Case, async: false import Mock test "indirect mock" do with_mocks([ { MyApp.IndirectMod, [:passthrough], [value: fn -> 2 end] }, ]) do # The following assert succeeds assert MyApp.IndirectMod.indirect_value_2() == 2 # The following assert also succeeds assert MyApp.IndirectMod.indirect_value() == 1 end end end
It is important to understand that only fully qualified function calls get mocked. The reason for this is because of the way Meck is structured. Meck creates a thin wrapper module with the name of the mocked module (and passes through any calls to the original Module in case passthrough is used). The original module is renamed, but otherwise unmodified. Once the call enters the original module, the local function call jumps stay in the module.
Big thanks to @eproxus (author of Meck) who helped explain this to me. We're looking into some alternatives to help solve this, but it is something to be aware of in the meantime. The issue is being tracked in Issue 71.
In order to workaround this issue, the
indirect_value can be rewritten like so:
def indirect_value do __MODULE__.value() end
Or, like so:
def indirect_value do MyApp.IndirectMod.value() end
Tips
The use of mocking can be somewhat controversial. I personally think that it works well for certain types of tests. Certainly, you should not overuse it. It is best to write as much as possible of your code as pure functions which don't require mocking to test. However, when interacting with the real world (or web services, users etc.) sometimes side-effects are necessary. In these cases, mocking is one useful approach for testing this functionality.
Also, note that Mock has a global effect so if you are using Mocks in multiple
tests set
async: false so that only one test runs at a time.
Open an issue.
Publishing New Package Versions
For library maintainers, the following is an example of how to publish new versions of the package. Run the following commands assuming you incremented the version in the
mix.exs file from 0.3.4 to 0.3.5:
git commit -am "Increase version from 0.3.4 to 0.3.5" git tag -a v0.3.5 -m "Git tag 0.3.5" git push origin --tags mix hex.publish
Suggestions
I'd welcome suggestions for improvements or bugfixes. Just open an issue. | https://elixir.libhunt.com/mock-alternatives | CC-MAIN-2020-45 | refinedweb | 2,792 | 58.18 |
Technical Support
On-Line Manuals
RL-ARM User's Guide (MDK v4)
#include <rtl.h>
OS_TID os_tsk_create_ex (
void (*task)(void *), /* Task to create */
U8 priority, /* Task priority (1-254) */
void* argv ); /* Argument to the task */
The os_tsk_create_ex function creates the task identified
by the task function pointer argument and adds the task to the
ready queue. The function dynamically assigns a task identifier value
(TID) to the new task. The os_tsk_create_ex function is an
extension to the os_tsk_create argv argument is passed directly to the task when it
starts. An argument to a task can be useful to differentiate between
multiple instances of the same task.
The os_tsk_create_ex function is in the RL-RTX library. The
prototype is defined in rtl.h.
note
The os_tsk_create_ex function returns the task identifier
value (TID) of the new task. If the function fails, for example due
to an invalid argument, it returns 0.
os_tsk_create, os_tsk_create_user, os_tsk_create_user_ex
#include <rtl.h>
OS_TID tsk1, tsk2_0, tsk2_1;
int param[2] = {0, 1};
__task void task1 (void) {
..
tsk2_0 = os_tsk_create_ex (task2, 1, ¶m[0]);
tsk2_1 = os_tsk_create_ex (task2, 1, ¶m[1]);
..
}
__task void task2 (void *argv) {
..
switch (*(int *)argv) {
case 0:
printf("This is a first instance of task2.\n");
break;
case 1:
printf("This is a second instance of task2.. | http://www.keil.com/support/man/docs/rlarm/rlarm_os_tsk_create_ex.htm | CC-MAIN-2020-05 | refinedweb | 211 | 58.18 |
This action might not be possible to undo. Are you sure you want to continue?
Neural Networks
David Kriesel
dkriesel.com
Download location: NEW – for the programmers: Scalable and efficient NN framework, written in JAVA
dkriesel.com
In remembrance of Dr. Peter Kemp, Notary (ret.), Bonn, Germany.
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
iii
Please let me know if you find out that I have violated this principle. everything is explained in both colloquial and formal language.give a short overview – but this is also ex- v . to provide a comprehensive overview of the subject of neural networks and.com on 5/27/2005). while the opposite holds for readers only interested in the subject matter. most of them directly in A L TEX by using XYpic. I did all the illustrations myself. Ambition and intention of this manuscript The entire text is written and laid out more effectively and with more illustrations than before. The sections of this text are mostly independent from each other The document itself is divided into different parts.learning procedures).dkriesel. they are also individually accessible to readers with little previous knowledge. Although the chapters contain cross-references. First and foremost. the classic neural network structure: the perceptron and its Nevertheless.A small preface "Originally. ever since the extended text (then 40 pages long) has turned out to be a download hit. stand the definitions without reading the running text. second. the mathematically and for.g. And who knows – maybe one day this summary will become a real preface!" Abstract of this work. the smaller chapters mally skilled readers will be able to under. which are again divided into chapters. end of 2005 The above abstract has not yet become a preface but at least a little preface. They reflect what I would have liked to see when becoming acquainted with the subject: Text and illustrations should be memorable and easy to understand to offer as many people as possible access to the field of neural networks. but it has been and will be extended (after being presented and published online under www. There are larger and smaller chapters: While the larger chapters should provide profound insight into a paradigm of neural networks (e. this work has been prepared in the framework of a seminar of the University of Bonn in Germany. just to acquire more and more A knowledge about L TEX .
com plained in the introduction of each chapter. In addition to all the definitions and explanations I have included some excursuses to provide interesting information not directly related to the subject. Snipe may have lots and lots more capabilities than may ever be covered in the manuscript in the form of practical hints. It is available at no SNIPE: This manuscript frequently incorporates Snipe. I omitthan lots of other implementations due to 1 Scalable and Generalized Neural Information Processing Engine.com/tech/snipe. I was not able to find free German sources that are multi-faceted in respect of content (concerning the paradigms of neural networks) and. class names are used. Recently. reading. nevertheless. the original high-performance simulation design goal. online JavaDoc at. I decided to just have to skip the shaded Snipegive it away as a professional reference imparagraphs! The Snipe-paragraphs asplementation that covers network aspects sume the reader has had a close look at handled within this work. dkriesel. feature-rich and usable way. in my experience almost all of the implementation reWant to learn not only by quirements of my readers are covered well. Some of the kinds of neural networks are not supported by Snipe. neural networks in a speedy. Those of you who are up for learning by doing and/or have to use a fast and stable neural networks implementation for some reasons.dkriesel.dkriesel. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . same time being faster and more efficient Often. while when it comes to other kinds of neural networks. downloadable at. but also by coding? On the Snipe download page.com ted the package names within the qualified class names for the sake of readability. Unfortunately. should definetely have a look at Snipe. the aspects covered by Snipe are not entirely congruent with those covered by this manuscript. look for the Use SNIPE! section "Getting started with Snipe" – you will find an easy step-by-step guide conSNIPE 1 is a well-documented JAVA li. However. As Snipe consists of only a few different packages. as brary that implements a framework for well as some examples. written in coherent style. This also implies that those who do not want to use Snipe. Shaded Snipe-paragraphs cost for non-commercial purposes. It was like this one are scattered among large originally designed for high performance parts of the manuscript. while at the the "Getting started with Snipe" section. simultaneously. Anyway. providing inforsimulations with lots and lots of neural mation on how to implement their connetworks (even large ones) being trained text in Snipe. vi D. The aim of this work is (even if it could not be fulfilled at first go) to close this gap bit by bit and to provide easy access to the subject.cerning Snipe and its documentation.
which then is marked in the ta. and speaking ones. Speaking headlines throughout the text.com It’s easy to print this manuscript This text is completely illustrated in color. Other chapters additionally depend This document contains different types of on information given in other (preceding) indexing: If you have found a word in chapters. such long headlines would bloat the table of contents in an unacceptable way. too. you can easily find it by searching ble of contents. throughout the text. There are many tools directly integrated into the text Different aids are directly integrated in the document to make reading more flexible: Marginal notes are a navigational However. but it can also be printed as is in monochrome: The colors of figures. tables and text are well-chosen so that in addition to an appealing design the colors are still easy to distinguish when printed in monochrome. anyone (like me) who prefers aid reading words on paper rather than on screen can also enjoy some features. x D. but centralize the information given in the associated section to a single sentence. short ones in the table of contents The whole manuscript is now pervaded by such headlines. like the latter. In the named instance. that are marked as "fundamental" are definitely ones to read because almost There are several kinds of indexing all subsequent chapters heavily depend on them. Speaking headlines are not just title-like ("Reinforcement Learning").dkriesel.the index and opened the corresponding page. allowing you to "scan" the document quickly to find a certain pasIn the table of contents. The entire document contains marginal notes in colloquial language (see the example in the margin). an appropriate headline would be "Reinforcement learning methods provide feedback to the network. Chapters. marked within the table of contents. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) vii . Hypertext on paper :-) types of chapters are marked New mathematical symbols are marked by specific marginal notes for easy finding Different types of chapters are directly (see the example for x in the margin). However. different sage in the text (including the titles). So I used short titles like the first one in the table of contents. whether it behaves good or bad".
or me and my readers very much. Acknowledgement 1. Terms of use and license Beginning with the epsilon edition. 3. Those are indexed in the category "Persons" and are still mine.com for highlighted text – all indexed words are highlighted like this. to the success of this work.dkriesel. In albuild upon the document except for phabetical order: Wolfgang Apolinarski. since a work like this needs many helpers. transform. Paul Imhoff. Thomas 2. the text is licensed under the Creative Commons Attribution-No Derivative Works 3. so you need to be careful with your citation. First of all. I want to thank the proofreaders of this text. respectively the subpage concerning the manuscript3 . except for some little portions of the work licensed under more liberal licenses as mentioned (mainly some figures from Wikimedia Commons). personal use. Mathematical symbols appearing in several chapters of this document (e. Kathrin Gräve.0 Unported License 2 .com/en/science/ neural_networks viii D. Note that this license does not extend to the source Names of persons written in small caps files used to produce the document. A quick license summary: ment (even though it is a much better idea to just distribute the URL of my homepage. the above bullet-point summary is just informational: if there is any conflict in interpretation between the summary and the actual license.Now I would like to express my grati- tude to all the people who contributed. You are free to redistribute this docu. the actual license always takes precedence. Please find more information in English and German language on my homepage. so they can easily be assigned to the corresponding term. for it always contains the most recent version of the text).g. ordered by the last names. You may not modify.org/licenses/ by-nd/3. in whatever manner. You may not use the attribution to imply that the author endorses you or your document use. For I’m no lawyer. who helped 2. How to cite this manuscript There’s no official publisher.dkriesel.0/ 3. 4. Ω for an output neuron. You must maintain the author’s attri- bution of the document at all times. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . I tried to maintain a consistent nomenclature for regularly recurring elements) are separately indexed under "Mathematical Symbols".
Matthias Siegmund. Joachim Nock. Julia Damaschek. Department of Computer Science Dr. Christian Schulz and Tobias Wilken. I want to thank my parents who never get tired to buy me specialized and therefore expensive books and who have always supported me in my studies. Malte Lohmeyer. suggestions and remarks. Oliver Tischler. I would like to thank Beate Frank Nökel. Andreas Hochrath. Kolb in Bonn. Igor Wall. Alexander Schier. In particular. Andreas Müller. Andreas Friedmann. Rainer Penninger. Mario Krenn. Sebastian Hirsch. Adam Maciak.low . Kemp! D. Achim Weber. Conversations with Prof.dkriesel. Jochen Döll. Boris Jentsch. I’d like to thank Sebastian Merzbach. Frank Weinreis.-) I want to thank Andreas Huber and Tobias Treutler. always felt to be in good hands and who Rolf Eckmiller and Dr. Thilo Keller. Sascha Fink. Daniel Rosenthal. Christoph Kunze. Maximilian Ernestus.com Kühn. Especially Dr. Additionally. Mathias Tirtasana. Wilfried Hartmann. and for her questions Furthermore I would like to thank the which made me think of changing the whole team at the notary’s office of Dr. who examined this work in a very conscientious way finding inconsistencies and errors. of the University of Bonn – they all made sure that I always learned (and also had to learn) something new about neural networks and related subjects. Lena Reichel. Anne Feldmeier. Hardy Falk. Since our first semester it has rarely been boring with you! Now I would like to think back to my school days and cordially thank some teachers who (in my opinion) had imparted some scientific knowledge to me – although my class participation had not always been wholehearted: Mr. Gideon Maillette de Buij Wenniger. Thomas Ihme. Especially. Kuhl for translating the entire text from German to English. Eckmiller made me step back from the whiteboard to get a better overall view on what I was doing and what I should do next. Hubert Peters and Mr. Marie Christ. Tim Hussein. Maikel Linke. he cleared lots and lots of language clumsiness from the English version. I want to thank the readers Dietmar Berger. Maximilian Voit. Mr. Markus Gerhards. Jan Gassen. Kemp and Dr. Nico Höft. Goerke has always been willing to respond to any questions I was not able to answer myself during the writing process. Mirko Kunze. where I have I would particularly like to thank Prof. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) ix . Daniel Plohmann. David Möller.in particular Christiane Flamme and matics. Igor Buchmüller. Globally. and not only in the context of this work. Nils Goerke as have helped me to keep my printing costs well as the entire Division of Neuroinfor. Benjamin Meier. phrasing of some paragraphs. For many "remarks" and the very special and cordial atmosphere . Additionally. Philipp Woock and many others for their feedback.
dkriesel. so to speak.com Thanks go also to the Wikimedia Commons. and Christiane Schultze. David Kriesel x D. where I took some (few) images and altered them to suit this text. who found many mathematical and logical errors in my text and discussed them with me. who carefully reviewed the text for spelling mistakes and inconsistencies. although she has lots of other things to do. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . a place of honor: My girlfriend Verena Thomas. Last but not least I want to thank two people who made outstanding contributions to this work who occupy.
. . . . . . . . . . . . . . .4 The amount of neurons in living organisms . . . . .2 Simple application examples . . . . . . . . . . .1.2. . . . . .1 Peripheral and central nervous system . . 1. . .1. . . . . . . . .3 Light sensing organs . . . . . . . . . .1 Various types . . . . . . . . . . . . . . . 2. . . . . . . 2. . . . . . . .3 Cerebellum .3 Long silence and slow reconstruction 1. . . . . . . . . . . . . . . . . . . . 2. . .Contents A small preface v I From biology to formalization – motivation. . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . .2 Information processing within the nervous 2.5 Brainstem . . . . . . . . 2. . . . .1 Components . . . . .4 Diencephalon . . 3 3 5 6 8 8 9 11 12 12 13 13 13 14 15 15 16 16 16 19 24 24 25 26 28 1 Introduction. . . 2. . . . . . . 1. . . . history and realization of neural models 1 . . . . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . . 2. . . .3. . . . motivation and history 1. .2 Electrochemical processes in the neuron . . 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . philosophy. . . . . . . . . . . . 2 Biological neural networks 2. . . . .1. . . . . . . . . . . . . . . . . .1 Why neural networks? . .2. . . . . . . . . . . . .1. . . . . . .3 Receptor cells . . . . . . . . . . . . . . . . . . . .2. . . . 1. . . . . . . . . . . . . . . . .1 The vertebrate nervous system . . . 2. . . 2. . . 1. . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . 2. . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . .1. . . . 1. .1 The 100-step rule . . . . . . . . . . . . . . . . . .2 Golden age . . . . . . . . . . . . . . . . . . . . . . . 1. . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . .2. . . . . . . . . . . .2 History of neural networks . . . . . . . . . . . . . . . . .2 Cerebrum . . xi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2. .1. . . . . system . . . . . . . . . . . . .2. . . .2 The neuron . . . 2. . . . .1 The beginning . . .4 Renaissance . . . . . . . .
. 3. . .2 Training patterns and teaching input . . . . . . . . . 3. . . . 4.1.1 Connections . . . . . . . . . . . . . . . . 3. . . . . .Contents dkriesel. . . . . . . . . . . . . . . .4. .2 Propagation function and network input . .1.1 Paradigms of learning . . . . . . . . . .3 Supervised learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3. .2. 31 3 Components of artificial neural networks (fundamental) 3. .2. . . . . . . . . . . . . . . . . . . . . . . .1 Feedforward . . . . . . . . . . . . . . . .5 Technical neurons as caricature of biology . . 3. . . . . . . .3 Network topologies . . . . . . . . . . . . . . . . . . . . . . . . . .1 Synchronous activation . . . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . .2.6 Orders of activation . . . . . . . . . . . . . . . . . .1. . . . . . 4. . . . . . .2 Components of neural networks . . . . . . . . . . . . . . . . . . . . . . . 4. . . . . . . . .2. . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . 33 33 33 34 34 35 36 36 37 38 38 39 39 40 42 43 45 45 45 46 48 48 51 51 52 53 53 54 54 54 56 57 57 58 59 (fundamental) xii D. .1 When do we stop learning? . . . . . . . . .8 Learning strategy . . 3. . . . . . . . . . . 4. . . . . . . . . . . . . . . . 3. . . . . . . . . . 4. . . . . . . . . . . . . . . .3. . .3. . . . . . . . . . . . . . . . . . . . . . . . . .4 Offline or online learning? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . .2 Asynchronous activation .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3. . . . .2.2 Reinforcement learning . .2. . 4. . . . . . . . . . .3 Activation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 The bias neuron . . 3. . . . . . . . . . . . . . . . Exercises .3. . . . 3. . 3. . .3 Using training samples . . . . . . . . . . . . . . . . . . . .5 Representing neurons . . .4 Threshold value . . . . . . . . . . . . . . . . . . . 3. . 3. . . . . 3. . . .7 Output function . . . . .7 Input and output of data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 Division of the training set . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . .1 The concept of time in neural networks . . . . . . . . . 4. . . . . .2. . . . . . . . . . . . . . . . . . . . . . . 3. . . . . . . . . . . . . . 3. . . . . . . . . .3 Completely linked networks . . . . . . . . . . . . . . .4 Learning curve and error measurement . . . . . . . . . . . . . . . . . 3. . . . . . 3. . . . . .1 Unsupervised learning . . . . . 3. . . 4. . . . 4 Fundamentals on learning and training samples 4. . . . . .6 Common activation functions . . . .2 Order of pattern representation . 4. . . . . . . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . .com 2. . . . . . . . . .5 Activation function . . . . .2 Recurrent networks . . . . . . . . . . . . . . . . . . . 4. . 30 Exercises . . .3. . . . . . . . . .5 Questions in advance . . . . . . . . 3. . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . .
. . 4. . . . . . 4. . . . . . . . . . . . . . . . . . . . . . . . . . .7. . . 4.7. . . . . . . . . . . . . 4. . . . . . 4. . . . . . . . . . . . . . . . . . . . . D. . . . . . . . . . .1 The singlelayer perceptron . . . . . . . . . . . . . . . . . . . . . . . . . . .3 Rprop in practice .5. . . . . . . . . . . . . . . . . . . . . . . . .2 Linear separability . . . . . . . Exercises . . . . . . . 5.2 The parity function . . . . . . . 5. . . . . . . . . . 5. . . . . .4 Weight decay .6. . . . . . . . . . . . . . . 5. . . . 5. . . .1 Number of layers . . . . . . . . . . . . . .6 Other exemplary problems .6. . . . . . . . . . . . . . . . 4. Contents . . . . . . . . .6. . . . . .2 Dynamic learning rate adjustment . . . . . . . . . . . . . . . . . . .7. . 4. . . .7 Hebbian rule .1 Momentum term . . . . . . . . . . . . . . . . . . . 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Resilient backpropagation . . . . . 5. . . . . 61 62 64 64 64 64 65 65 66 66 66 67 67 II Supervised learning network paradigms . . . . 5. . . . . . . . . . . . . . . . 69 71 74 75 75 81 84 86 87 91 92 93 94 94 95 96 96 97 98 98 98 99 99 100 5 The perceptron.3 The multilayer perceptron . . . . . . . . . . . . . . . . . .3 Second order backpropagation . . . . . .1 Problems of gradient procedures 4. . . . . . . . . . . . . . . . . .4 The checkerboard problem .3 Selecting a learning rate . . . . . . . . . . . . . .5 . . . . . . . . . .2 Flat spot elimination .7. . . . . . . . . . . . . . . . . . . .6. . . . . 5. . . . . . . . .5 The identity function . . . . . . . . .1 Boolean functions . . . 4. . . . . . .4. . . .2 Generalized form . . . . . . . . . . . . . . . . . . . . . . . . . .4. . . . . . .1. . .6. . . . . . . . . .5. . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5. . . . . .2 The number of neurons . . . . 5. . . . . . . .6. . . . . . . . . . . . . . . . . .6. .6 Exemplary problems . . . . . . . . . . . . . . . . . 5.2 Boiling backpropagation down to the delta rule . . . . . . .1 Perceptron learning algorithm and convergence theorem 5. . . 4. . 4. . . . . . . . 5. . . . . . . . . . . . . 4. . . . . . . . . . . . . .1 Derivation . . . . . .5 Pruning and Optimal Brain Damage . . . 5. . . . 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . .5.6. . .2 Delta rule . . . . . . . . . 5. . . . . . . . . .1 Original rule . .6. . 5. .6. . .com Gradient optimization procedures . . . .dkriesel. . . 5. . . . . . . .6 Further variations and extensions to backpropagation . . . . . . . .4.7 Initial configuration of a multilayer perceptron . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Backpropagation of error . . . . . . . .6. . . backpropagation and its variants 5. . . 5. . . . . .5. . . . . . . . . . . . . . . . . . .1 Adaption of weights . . . . . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) xiii . . . . . . 5. . . . . . . . . .3 The 2-spiral problem . . . . . . .
. . . .4 Initializing weights . . . 6. . 111 . . . . . . . . . . . . . . . . .4 Training with evolution . . . . . . . . . . . .1 Components and structure . . . . . . 131 . . . . . .5. . . . . . . . . .3. . . 7 Recurrent perceptron-like networks (depends on chapter 5) 7. . . . . . . . . . . . . . . . . . 7. . .3 Training recurrent networks . 8.2. . . . . .3 Recurrent backpropagation .com . . . . . . . . . . . . . . . . . . . . . .2. . . . . 6. . . . . . . 129 . 5. .2 Limiting the number of neurons . . . . .2 Teacher forcing . . . . . . . . . . . . . . . . 118 .4. . . . . . . . . 6. . . . . . . . 6. . . . . . . . . 133 . . . .1 Generating the heteroassociative matrix . . . 7. . . . . . . . . . . .5.1 Unfolding in time .5 Comparing RBF networks and multilayer perceptrons Exercises . . . . . . . . . . .2. . . . 129 . . . . . . . . .4. . . . . . . 121 122 123 124 125 127 127 127 8 Hopfield networks 8. . . . . . . . . . . . . . 8. . . . . . . . . 7. . . . . . . . . . . . 105 . . . . . . . . 115 . 131 . . . . . . 8. . . . . . 130 . . . . . . . . . . . . . . 5. . . . . . . . 8. . 119 . . .7. .5. . . . . . . . . . . 134 . .4 Growing RBF networks . . . .3 Generating the weight matrix . . . . . . 119 . . . . . . . . . . . .2 Elman networks . . . . . . . . 135 . . . . . . . . . . . . . .3 Biological motivation of heterassociation . . . .3 Selecting an activation function . . . . . . . . . . 6. . . . . . . . . . . . . . .4. . . . . . 6. . . . . . . . 135 . . . . . . .1 Centers and widths of RBF neurons .3 Change in the state of neurons . 108 . . . . . . . 8. . 129 . . 114 . . . . . . . . . . . . . . . . . . . . . . . 6. . . . . . . . . .4 Autoassociation and traditional application . . . . . . 106 . . . . . . . . . . . . . . 6. . . . . . . . . . . . . . .2 Information processing of an RBF network . . . . . . . .Contents 5. . . . . . . . 7. . . . . . .2. . . . . . . . . . . . . . . .1 Jordan networks . . . . . . .3. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . . . . . . . . . . . . . . . . . . . . . . . . . . .3. . . .2 Analytical thoughts prior to the training . . . 105 . . . .1 Information processing in RBF neurons . . . . . . 7. . . . . . . . . .2 Structure and functionality . . . .7. . . . .2 Significance of weights . . . . . . . . . . . 100 101 101 102 6 Radial basis functions 6. . . . . .2 Stabilizing the heteroassociations . . . . 8. . . . .8 The 8-3-8 encoding problem and related problems Exercises . . . . . . . . 6. . . .5 Heteroassociation and analogies to neural data storage 8. . . . . . . . . . .2. . . . . . . . 118 . . . . 8. 8. . . . . . . . . 132 . . . .3. . . . . . . . . . . . . . . . 136 xiv D. . . . 6. . . 7. . . 8. . .1 Adding neurons . 120 . . . . . . . . . 119 . . . . . . . . . . . . . . . .3 Deleting neurons . . . . . . . . . . . . .3. . . . . dkriesel. . . .3 Training of RBF networks . . . . . . . . . . . . . . . . . . . . . . . . . .1 Input and output of a Hopfield network . .1 Inspired by magnetism . . . . . . . . .
. . . . . . . . . . . . . . . . . . . 140 . . . . . . . . . . . . . . . . . . . . . . . . Exercises . . . . . . . . . . . . . . . . . . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) xv . . 10. . . . . . . . . . . . . . . . . . . . 10. . . . . . . . . . . . . 10. . . . . . . . . . . .dkriesel.1 Resonance . . . . . .1 Topological defects . . . . . .2 Resonance and bottom-up learning . . . .4. . . . . . . . .5 Adjustment of resolution and position-dependent learning rate . . . . . . . . . . . . . . . . . . . . . .2 Purpose of LVQ . . . . . . . . . . . . . . . . . . . . . . . . . 165 . .7. . . . . . . . . . . . . . . . . . . . . . 141 . . . 9. . . 10.7.2. .1 About quantization . . . . . . . . . . . . . . . . . . . . . . . . . . 11. . . .7. . . . . . . . . . .1 The procedure of learning 9. . .3. . . . .4 Examples . .1 Neural gas . . . . . . . . . . . . . . . . . . . . . . . . . . 137 9 Learning vector quantization 9. .1 Task and structure of an ART network .4 Adjusting codebook vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . 167 . . . . . . .4 Growing neural gas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 . . . . . . . . . . . . 141 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .com Contents 8. . . . . . . . . . . . . . . . . . . . . . . . .4. . . . 9. . . . . . . . . . . . 167 D. . . . . . 11. . . . . . . . . 10. . .3 Multi-neural gas . . . . . . .3. . 140 . . . 167 . . . .1 Interaction with RBF networks . . .5 Connection to neural networks . . . .3 Training . . . . . . .6 Application .2 Functionality and output interpretation . . .1 Structure . . . . . . . . . . . . . . . . . . . . . .7. 10. . . 139 . . . . . . . . . . . . . . . . . . . .7 Variations . . . . 166 . . . . . . . . . . 9. 143 . . 10. . . . . . . .6. . . . . 11 Adaptive resonance theory 11. . . . . . . .2 Learning process . 10. . 11. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10. .2. . . . . . . Exercises . . . . . . . . . . . . . .3 Using codebook vectors . . . . . . . . . . . . . . . . . . . . 136 Exercises . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.1 Pattern input and top-down learning 11. . . . . . . . . . . .6 Continuous Hopfield networks . . . .2 Multi-SOMs . . . . . .2 Monotonically decreasing learning rate and neighborhood 10. . . . .1 The topology function . . . . . . 11. . . . . . . . . 10. 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 147 147 149 149 150 152 155 156 156 159 161 161 161 163 163 164 164 165 . . . . . . . . . . . . . . 143 III Unsupervised learning network paradigms 10 Self-organizing feature maps 10. . . . .3 Adding an output neuron . . . . . . . . . . . 10. . . . . . . . . . . 139 . . . . . . . . 9.
. . . .2. A.1 Structure of a ROLF . . . . .1 About time series . . . . . .1 The gridworld . . . . . . . . . . . .5 The policy . . . . . . . C. . . . . . . . . . . . . .5. . C.3. . . . . . . .5. . . . . . . . . . . . . . . .2 The state-value function . . . . . .4 Comparison with popular clustering methods . C. . . . . . . . . . . . . . . .1 Changing temporal parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A. . . 169 171 172 172 173 173 175 176 177 178 179 180 180 180 181 181 183 185 185 185 185 185 187 187 191 192 192 193 194 195 196 198 198 199 xvi D. . B. . . . .Contents dkriesel. . . . . . . . . . . . . . . . . . . .1 Recursive two-step-ahead prediction . . . . . . . . .5. . .3 ε-nearest neighboring . . . . . . . . . . . B. .5. . . . . . . . . .3 States. . . . .4. . . . . . . . .6 Application examples . . . .5 Initializing radii. . . . . . . . . . .3 Extensions . . learning rates and multiplier . . . . . . . A. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . .2. . . . . . .2 Direct two-step-ahead prediction . . . . . . appendices and registers A Excursus: Cluster analysis and regional and online learnable fields A. . . . . . .1. . .1. . . . . . . . . . . . . . . . . . . . . . . . . B. . . A. . . . . . . . . . . . . . A. .3. . . . . . . . . . . . . . . . . . A. . . . . . . . .1 k-means clustering . . . . . . . . . . . . . . . . . . .1 System structure . . . . . . . . . . . . . . . . . . . . . . . B. . . . . . . . . . . . . . . . . . . . . . . . . . 167 IV Excursi.3 Two-step-ahead prediction . . . . . . . . . .2 Agent und environment . . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . . . . . . . . B. . . C. . . .1 Rewarding strategies . . . . . . . . . . . . . . . . . . . .4 Additional optimization approaches for prediction . . . . . . . . . . . .4 The silhouette coefficient . . . . . . . . . . . . . . C. . . . . . . . . . . . . . A. . . . . . . . . .2 Learning process . . . . . . . . . . . B. .4 Reward and return . . . . . . C Excursus: reinforcement learning C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C. . . . . . . . . . . . .2 One-step-ahead prediction . . . . . . . . . . . . . . . . . A. . . . . . . . . . C.2 Heterogeneous prediction . .5 Remarks on the prediction of share prices . . . . . . . . . . . . . . . . . . Exercises . . . . . . . .1. . .com 11. . . . B Excursus: neural networks used for prediction B. . . . . . . . . . . . A. .2 Training a ROLF . . . . B. . . . . . . . . . . . A. . . . . . . . . . . . situations and actions C. . . . . . . . .5. . . . . . . . . . . . . . . . . .4. . . .1. . . . . . . . . . . . . . .5. B. . . . .5 Regional and online learnable fields . . . . . . .3 Evaluating a ROLF . . . . . . . . . . . . . .2 k-nearest neighboring . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . C. . . . . . . . . . Contents . . C. . . . . . . . . . . . . . . . . . . .3. . . . . . . . . . . . . .2. . . . . .2. . . .3 The pole balancer . . . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) xvii . . . . . . .2. . . . . C. . . . . . . .dkriesel. . . neural . . . . . . . . with . . . .com C. .2 The car in the pit . . . . . . . . 201 202 203 204 205 205 205 206 207 207 209 215 219 D. . . .1 TD gammon . . . . . . . . C. . . . . . . . . . . . . . . . .6 Q learning . . . . . . .3 Monte Carlo method . . .3. . . . . . . . . . . . . . . . C. . .4 Temporal difference learning C. . . . . . . . . . . . . . . networks . . . . . . . . . . . . . . . .4 Reinforcement learning in connection Exercises . . . . . C. .2. . . . . .5 The action-value function . . . . . .3. . . . . . . . . . . . . . . . . . . . . . . . . . C.3 Example applications . Bibliography List of Figures Index . . . . . . . . . . . . . . . . . . . .
.
history and realization of neural models 1 . philosophy.Part I From biology to formalization – motivation.
.
Living beings do not have any programmer writing a program for developing their skills. development. the computer should be more powerful than our brain: It comprises 109 transistors with a switching time of 10−9 seconds. but they are not adaptive. The brain contains 1011 neurons. decline and resurgence of a wide approach to solve problems. we will note that. They allow the computer to perform the most complex numerical calculations in a very short time. What qualities are needed to achieve such a behavior for devices like computers? Can such cognition be adapted from biology? History. for example the purchase price of a real estate which our brain can (approximately) calculate. Humans have a brain that can learn. theoretically. while the largest part of the computer is only passive data storage.1 Why neural networks? There are problem categories that cannot be formulated as an algorithm. parallelism Computers cannot learn 3 .Chapter 1 Introduction. motivation and history How to teach a computer? You can either write a fixed program – or you can enable the computer to learn on its own. Computers have some processing units and memory. Therefore the question to be asked is: How do we learn to explore such problems? Exactly – we learn . The largest part of the brain is working continuously. Nevertheless. this comparison is . They learn by themselves – without the previous knowledge from external impressions – and thus can solve problems better than any computer today. Problems that depend on many subtle factors. since response time and quantity do not tell anything about quality and performance of the processing units as well as neurons and transistors cannot be compared directly. Thus. the comparison serves its purpose and indicates the advantage of parallelism by means of processing time. but these only have a switching time of about 10−3 seconds. If we compare computer and brain1 . which then only has to be executed. 1. a capability computers obviously do not have. the brain is parallel and therefore performing close to its theoretical maxi1 Of course.for obvious reasons .controversially discussed by biologists and computer scientists. Without an algorithm a computer cannot do the same.
heard that someone forgot to install the n. I have never the capability of neural networks to gen.with a carrot and a stick. is not One result from this learning procedure is automatically fault-tolerant. motivation and history Brain ≈ 1011 Neurons massively parallel associative ≈ 10−3 s ≈ 1013 1 s ≈ 1012 1 s dkriesel. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . Inspired by: [Zel94] mum. tioned. Our modern technology. the brain is tolerant against internal There is no need to explicitly program a errors – and also against external errors.1: The (flawed) comparison between brain and computer at a glance.Chapter 1 Introduction. which . aspects) have the capability to learn. Thus. in which this characteristic is very distinct: As previously menbrain for a computer system.in (about 105 neurons can be destroyed while comparison to the overall system . network fault tolerant 4 D. our cogniis probably one of the most significant tive abilities are not significantly affected. a human has about 1011 neurons So the study of artificial neural networks that continuously reorganize themselves is motivated by their similarity to success. a computer is static . from which the computer is orders of magnitude away (Table 1. however. Nevertheless.consist in a drunken stupor. neural network. network capable to learn Within this text I want to outline how Fault tolerance is closely related to biologwe can use the said characteristics of our ical neural networks. to compensate errors and so forth. so to speak (reinforcement learning ).or are reorganized by external influences fully working biological systems. eralize and associate data : After successful training a neural network can find reasonable solutions for similar problems of the same class that were not explicitly trained. of processing units Type of processing units Type of calculation Data storage Switching time Possible switching operations Actual switching operations Table 1.the brain as a biological neural network can reorganize itself during its "lifespan" and therefore is able to learn. it can learn for we can often read a really "dreadful from training samples or by means of en. some types of food of very simple but numerous nerve cells or environmental influences can also dethat work massively in parallel and (which stroy brain cells). simple but many processing units n.scrawl" although the individual letters are couragement .1). This in turn results in a high degree of fault tolerance against noisy input data.com Computer ≈ 109 Transistors usually serial address-based ≈ 10−9 s ≈ 1018 1 s ≈ 1010 1 s No. nearly impossible to read. For instance. Additionally.
There are different paradigms for neural networks. so that the system as a whole was affected by the missing component.≈ 10−3 seconds in ≈ 100 discrete time steps of parallel processing. Most often we can only transfer knowledge into our neural network by means of a learning procedure. however. which can cause several errors and is not always easy to manage. but the data stream remains largely responds to a neuron switching time of unaffected. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 5 .e. i. Generalization capability and Now we want to look at a simple application example for a neural network. can do practically nothing in 100 time steps of sequential proSelf-organization and learning capacessing. how they are trained and where they are used. My goal is to introduce some of these paradigms and supplement some remarks for practical application. which cority.or person in ≈ 0. but not completely destroyed. i. If there is a scratch on a 1. Important! We have already mentioned that our brain works massively in parallel. the audio information on this spot will be completely lost (you will hear a pop) and then the music goes on. parallel processing D.1 seconds. on the other hand. it is easier to perform such analyses for conventional algorithms.dkriesel. thing.com hard disk controller into a computer and therefore the graphics card automatically took over its tasks.e. Usually. In the introductory chapter I want to clarify the following: "The neural network" does not exist. can be cited.1 Why neural networks? What types of neural networks particularly develop what kinds of abilities and can be used for what problem classes will be discussed in the course of this work. is already more sophisticated in state-ofthe-art technology: Let us compare a record and a CD. Fault tolerance.1 The 100-step rule record.A computer following the von Neumann tics we try to adapt from biology: architecture. removed conductors and developed communication. every component is active at any time. A disadvantage of this distributed faulttolerant storage is certainly the fact that we cannot realize at first sight what a neural neutwork knows and performs or where its faults lie. If we want to state an argument for massive parallel processing. 1. in contrast to the functioning of a computer. So let us summarize the main characteris. On a CD Experiments showed that a human can the audio data are distributedly stored: A recognize the picture of a familiar object scratch causes a blurry sound in its vicin. The listener won’t notice any.1. cycle steps. then the 100-step rule Fault tolerance of data. which are 100 assembler steps or bility.
1. Each sensor provides a real numeric value at any time.2 The way of learning On the other hand.2. Such procedures are applied in the classic artificial intelligence. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . This robot has eight distance sensors from which it extracts input data: Three sensors are placed on the front right. After that we refer to the technical reference of the sensors.2 Simple application examples Let us assume that we have a small robot as shown in fig. 1. 1. – and the robot shall learn on its own what to do in the course of its robot life.2. We first treat the 6 D. since the example is very simple). The arrow indicates the driving direction. study their characteristic curve in order to learn the values for the different obstacle distances. On the one hand. and if you know the exact rules of a mapping algorithm. more interesting and more successful for many mappings and problems that are hard to comprehend straightaway is the way of learning : We show different possible situations to the robot (fig.Chapter 1 Introduction. that applies the input signals to a robot activity.1. Thus. and embed these values into the aforementioned set of rules.1. our output is binary: H = 0 for "Everything is okay. and finally the result is a circuit or a small computer program which realizes the mapping (this is easily possible. Therefore we need a mapping f : R8 → B1 .1 The classical way There are two ways of realizing this mapping. 1. and two on the back.com put is called H for "halt signal"). that means we are always receiving an input I ∈ R8 .1. 1. there is the classical way : We sit down and think for a while. three on the front left. Despite its two motors (which will be needed later) the robot in our simple example is not capable to do much: It shall only drive on but stop when it might collide with an obstacle. motivation and history dkriesel. you are always well advised to follow this scheme. 1. In this example the robot shall simply drive on" and H = 1 for "Stop" (The out.learn when to stop.2 on page 8).1: A small robot with eight sensors and two motors. Figure 1.
This means we do not know its structure but just regard its behavior in Our goal is not to learn the samples by heart. good samples.e changing. has two motors with wheels eralize from these samples and find a uniand various sensors. on. stop the robot but also lets it avoid obstacles.g. As a consequence. the sensor values are changed once again. In this case we are looking for a mapping cannot only. approx.network and changes its position. with the sensor layout being the same. into the neural net. Again the robot queries the edge. algorithm or a mathematical formula.is a constant cycle: The robot queries the ing sample consists of an exemplary input network. It is obvious that this system can also The samples can be taught to a neural be adapted to dynamic. ommend to refer to the internet. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 7 . Figure 1. and so work. placing the robot able to avoid obstacles. and de facto a neural network would neural network as a kind of black box be more appropriate. Here it is more difficult to analytically derive the rules. 1. to continously avoid obstacles. the neural network will gen7 cm in diameter.sors values. i. a train.dkriesel.g.vironments (e. for example. ennetwork by using a simple learning pro. In particular. If we have done everything right and chosen 2 There is a robot called Khepera with more or less similar characteristics. it will drive and a corresponding desired output.neural network in any situation and be sured sensor values (e. the information. For the purpose of direction control it would be possible to control the motors of our robot separately2 . (fig. D.1 Why neural networks? Our example can be optionally expanded. the robot should apply the The situations in form of simply mea. the in front of an obstacle. we regard the robot control as a black box whose inner life is unknown.3). f : R8 → R2 . but to realize the principle behind practice. which changes the senthe question is how to transfer this knowl. robot should query the network continuwhich we show to the robot and for which ously and repeatedly while driving in order we specify whether to drive on or to stop. It is round-shaped. the moving obstacles in cedure (a learning procedure is a simple our example). them: Ideally. see illustration). The black box receives eight real sensor values and which gradually controls the two motors by means of the sensor inputs and thus maps these values to a binary output value.3: Initially. For more information I recversal rule when it has to stop. The result are called training samples. Now in one direction.com 1. Thus.
as we will see soon. The youth of this field of research. as with the field of computer science itself.1 The beginning in text form but more compact in form of a timeline.com Figure 1. like any nized due to the fact that many of the other field of science. Citations and bibliographical references are added mainly for those topics As soon as 1943 Warren McCulloch and Walter Pitts introduced modthat will not be further discussed in this els of neurological networks. We add the desired output values H and so receive our learning samples.2: The robot is positioned in a landscape that provides sensor values for different situations. Citations for keywords that will be ated threshold switches based on neuexplained later are mentioned in the correrons and showed that even simple sponding chapters. can be easily recogThe field of neural networks has. The directions in which the sensors are oriented are exemplarily applied to two robots. Further- 1. motivation and history dkriesel. recretext.2.Chapter 1 Introduction. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . development with many ups and downs. a long history of cited persons are still with us. networks of this kind are able to The history of neural networks begins in calculate nearly any logic or ariththe early 1940’s and thus nearly simultametic function [MP43]. neously with the history of programmable electronic computers. To continue the style of my work I will not represent this history 1.2 A brief history of neural networks 8 D.
Hebb could postulate this rule. tween top-down and bottom-up research developed. brain information storage is realized as a distributed system. D. how but due to the absence of neurological to simulate a brain. "in the order of appearance" as far as possible. Hebb. where only the extent but not the location of the destroyed nerve tissue influences the rats’ performance to find their way out of a labyrinth. Bernard Widrow. but nobody really plies that the connection between two knows what it calculates.dkriesel. who was tired of calculating ballistic trajectories by hand. since it is capable learning procedures.4: Some institutions of the field of neural networks. Hebb formulated the Snark. 1951: For his dissertation Marvin Minsky developed the neurocomputer 1949: Donald O. to put it crudely. While the early 1950: The neuropsychologist Karl Lashley defended the thesis that 3 We will learn soon what weights are. But it has never been practiform the basis of nearly all neural cally implemented. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 9 . The rule imto busily calculate.2 Golden age namely the recognition of spacial patterns by neural networks [PM47]. 1956: Well-known scientists and ambiThis change in strength is proportious students met at the Darttional to the product of the two activmouth Summer Research Project ities. the first computer precursors ("electronic brains")were developed.2. Seymour Papert. Marvin Minsky. From left to right: John von Neumann. 1. neurons is strengthened when both neurons are active at the same time. among others supported by Konrad Zuse. Differences beresearch he was not able to verify it. His thesis was based on experiments on rats. John Hopfield. 1947: Walter Pitts and Warren McCulloch indicated a practical field of application (which was not mentioned in their work from 1943). which has already been capaclassical Hebbian rule [Heb49] which ble to adjust its weights3 automatirepresents in its more generalized cally. more.2 History of neural networks Figure 1. Teuvo Kohonen. and discussed. Donald O.com 1.
Charles Wightman and their coworkers developed the first successful neurocomputer. and a learning limits. In the following stagnation and out of fear of scientific unpopularity of the neural networks ADALINE was renamed in adaptive linear element – which was undone again later on. motivation and history supporters of artificial intelligence wanted to simulate capabilities by means of software. 1960: Bernard Widrow and MarNils Nilsson gave an overview of cian E. was a PhD student of Widrow.com modern microprocessors. a fast and precise assumed that the basic principles of adaptive learning system being the self-learning and therefore. dkriesel. supporters of neural networks wanted to achieve system behavior by imitating the smallest parts of the system – the neurons. he deconvergence theorem. who 1969: Marvin Minsky and Seymour Papert published a precise mathehimself is known as the inventor of 10 D. Today this asnearly every analog telephone for realsumption seems to be an exorbitant time adaptive echo filtering and was overestimation. which was capable to recognize simple numerics by means of a 20 × 20 pixel image sensor and electromechanically worked with 512 motor driven potentiometers . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .each potentiometer representing one vari1961: Karl Steinbuch introduced techable weight. the Mark I perceptron .Chapter 1 Introduction. Additionally. nical realizations of associative mem1959: Frank Rosenblatt described difory. the connecting weights also changed in larger steps – the smaller the steps. rule adjusting the connecting weights. but at that time it trained by menas of the Widrow-Hoff provided for high popularity and sufrule or delta rule. development accelerates first spread use 1957-1958: At the MIT. Disadvantage: missapplication led to infinitesimal small steps close to the target. generally first widely commercially used neuspeaking. and analyzed their possibilities and threshold switches. which can be seen as predecessors ferent versions of the perceptron. It was ron ) [WH60]. One advantage the delta rule had over the original perceptron learning algorithm was its adaptivity : If the difference between the actual output and the correct solution was large. the closer the target was. ficient research funds. forof today’s neural associative memmulated and verified his perceptron ories [Ste61]. 1965: In his book Learning Machines. Frank Rosenblatt. Hoff introduced the ADAthe progress and works of this period LINE (ADAptive LInear NEuof neural network research. "intelligent" systems had alral network: It could be found in ready been discovered. He described scribed concepts for neural techniques neuron layers mimicking the retina. At that time Hoff. later co-founder of Intel Corporation.
In the same year. independently developed neural network paradigms: They researched. The implication that more powerful mod1974: For his dissertation in Harvard els would show exactly the same probPaul Werbos developed a learning lems and the forecast that the entire procedure called backpropagation of field would be a research dead end reerror [Wer74]. Furthermore.2.3 Long silence and slow numerous neural models are analyzed reconstruction mathematically. the [Koh72]. but it was not until sulted in a nearly complete decline in one decade later that this procedure research funds for the next 15 years reached today’s importance. He was received. – no matter how incorrect these forecasts were from today’s point of view.dkriesel. however. extremely short. [MP69] to show that the perceptron model was not capable of representing many important problems (keywords: 1973: Christoph von der Malsburg used a neuron model that was nonXOR problem and linear separability ). self-organizing feature maps (SOM) [Koh82. enough memory for a structure like a model of an associative memory the brain. he dedicated himself to the problem of The research funds were. Under conferences nor other events and therefore cooperation of Gail Carpenter only few publications. vated [vdM73]. Anderson matical analysis of the perceptron [And72]. such a brain has to organize and create model was presented independently itself for the most part). the basic theories for the still looking for the mechanisms involving continuing renaissance were laid at that self-organization in the brain (He time: knew that the information about the creation of a being is stored in the 1972: Teuvo Kohonen introduced a genome. but there were neither already learned associations.2 History of neural networks research funds were stopped of view by James A. which has. linear and biologically more motiand so put an end to overestimation. Everywhere of learning without destroying research went on.com 1. As a consequence. and from a neurophysiologist’s point backprop developed D. but there 1982: Teuvo Kohonen described the was no discourse among them. This isolation of this led to models of adaptive individual researchers provided for many resonance theory (ART). Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 11 . popularity and research funds. 1976-1980 and thereafter: Stephen Grossberg presented many papers (for instance [Gro76]) in which 1. as previouslykeeping a neural network capable mentioned. not model of the linear associator. Koh98] – also In spite of the poor appreciation the field known as Kohonen maps.
Chapter 1 Introduction. A company using neural networks. Exercise 1. They were not widely used in technical applications. explosive.4 Renaissance time a certain kind of fatigue spread John Hopfield also invented the in the field of artificial intelligence. netism in physics. Briefly characterize the four development phases of neural networks and give expressive examples for each phase.2. who had personally convinced many researchers of the importance of the field. Give one example for each of the following topics: A book on neural networks or neuroinformatics. but some of its results will be 1983: Fukushima. troduced the neural model of the Neocognitron which could recognize handwritten characters [FMI83] and was an extension of the Cognitron net. Show at least four applications of technical neural networks: two from the field of pattern recognition and two from the field of function approximation. 1985: John Hopfield published an article describing a way of finding acceptable solutions for the Travelling Salesman problem by using Hopfield nets. Through the influence of John Hopfield. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .Exercises work already developed in 1975. the development of but the field of neural networks slowly the field of research has almost been regained importance. Exercise 3. A collaborative group of a university working with neural networks. the field of neural networks slowly showed signs of upswing. Miyake and Ito inseen in the following. It can no longer be itemized. and the wide publication of backpropagation by Rumelhart. A software tool realizing neural networks ("simulator"). and A product or service being realized by means of neural networks. so-called Hopfield networks [Hop82] caused by a series of failures and unwhich are inspired by the laws of magfulfilled hopes. Exercise 2. Hinton and Williams. motivation and history dkriesel. 1986: The backpropagation of error learning procedure as a generalization of the delta rule was separately developed and widely published by the Parallel Distributed Processing Group [RHW86a]: Non-linearly-separable problems could be solved by multilayer perceptrons.com 1. and Marvin Minsky’s negative evaluations were disproven at a single blow. From this time on. At the same Renaissance 12 D.
Chapter 2 Biological neural networks
How do biological systems solve problems? How does a system of neurons work? How can we understand its functionality? What are different quantities of neurons able to do? Where in the nervous system does information processing occur? A short biological overview of the complexity of simple elements of neural information processing followed by some thoughts about their simplification in order to technically adapt them.
Before we begin to describe the technical side of neural networks, it would be useful to briefly discuss the biology of neural networks and the cognition of living organisms – the reader may skip the following chapter without missing any technical information. On the other hand I recommend to read the said excursus if you want to learn something about the underlying neurophysiology and see that our small approaches, the technical neural networks, are only caricatures of nature – and how powerful their natural counterparts must be when our small approaches are already that effective. Now we want to take a brief look at the nervous system of vertebrates: We will start with a very rough granularity and then proceed with the brain and up to the neural level. For further reading I want to recommend the books [CR00, KSJ00], which helped me a lot during this chapter.
2.1 The vertebrate nervous system
The entire information processing system, i.e. the vertebrate nervous system, consists of the central nervous system and the peripheral nervous system, which is only a first and simple subdivision. In reality, such a rigid subdivision does not make sense, but here it is helpful to outline the information processing in a body.
2.1.1 Peripheral and central nervous system
The peripheral nervous system (PNS ) comprises the nerves that are situated outside of the brain or the spinal cord. These nerves form a branched and very dense network throughout the whole body. The pe-
13
Chapter 2 Biological neural networks ripheral nervous system includes, for example, the spinal nerves which pass out of the spinal cord (two within the level of each vertebra of the spine) and supply extremities, neck and trunk, but also the cranial nerves directly leading to the brain. The central nervous system (CNS ), however, is the "main-frame" within the vertebrate. It is the place where information received by the sense organs are stored and managed. Furthermore, it controls the inner processes in the body and, last but not least, coordinates the motor functions of the organism. The vertebrate central nervous system consists of the brain and the spinal cord (Fig. 2.1). However, we want to focus on the brain, which can - for the purpose of simplification - be divided into four areas (Fig. 2.2 on the next page) to be discussed here.
dkriesel.com
2.1.2 The cerebrum is responsible for abstract thinking processes.
The cerebrum (telencephalon ) is one of the areas of the brain that changed most during evolution. Along an axis, running from the lateral face to the back of the head, this area is divided into two hemispheres, which are organized in a folded structure. These cerebral hemispheres are connected by one strong nerve cord ("bar ") and several small ones. A large number of neurons are located in the cerebral cortex (cortex ) which is approx. 24 cm thick and divided into different cortical fields, each having a specific task to Figure 2.1: Illustration of the central nervous
system with spinal cord and brain.
14
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
dkriesel.com
2.1 The vertebrate nervous system and errors are continually corrected. For this purpose, the cerebellum has direct sensory information about muscle lengths as well as acoustic and visual information. Furthermore, it also receives messages about more abstract motor signals coming from the cerebrum. In the human brain the cerebellum is considerably smaller than the cerebrum, but this is rather an exception. In many vertebrates this ratio is less pronounced. If we take a look at vertebrate evolution, we will notice that the cerebellum is not "too small" but the cerebum is "too large" (at least, it is the most highly developed structure in the vertebrate brain). The two remaining brain areas should also be briefly discussed: the diencephalon and the brainstem.
Figure 2.2: Illustration of the brain. The colored areas of the brain are discussed in the text. The more we turn from abstract information processing to direct reflexive processing, the darker the areas of the brain are colored.
fulfill. Primary cortical fields are responsible for processing qualitative information, such as the management of differ2.1.4 The diencephalon controls ent perceptions (e.g. the visual cortex fundamental physiological is responsible for the management of viprocesses sion). Association cortical fields, however, perform more abstract association and thinking processes; they also contain The interbrain (diencephalon ) includes our memory. parts of which only the thalamus will be briefly discussed: This part of the diencephalon mediates between sensory and 2.1.3 The cerebellum controls and motor signals and the cerebrum. Particucoordinates motor functions larly, the thalamus decides which part of the information is transferred to the cereThe cerebellum is located below the cere- brum, so that especially less important brum, therefore it is closer to the spinal sensory perceptions can be suppressed at cord. Accordingly, it serves less abstract short notice to avoid overloads. Another functions with higher priority: Here, large part of the diencephalon is the hypothaparts of motor coordination are performed, lamus, which controls a number of proi.e., balance and movements are controlled cesses within the body. The diencephalon
thalamus filters incoming data
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
15
Chapter 2 Biological neural networks
dkriesel.com
is also heavily involved in the human cir- All parts of the nervous system have one cadian rhythm ("internal clock") and the thing in common: information processing. This is accomplished by huge accumulasensation of pain. tions of billions of very similar cells, whose structure is very simple but which communicate continuously. Large groups of 2.1.5 The brainstem connects the brain with the spinal cord and these cells send coordinated signals and thus reach the enormous information procontrols reflexes. cessing capacity we are familiar with from our brain. We will now leave the level of In comparison with the diencephalon the brain areas and continue with the cellular brainstem or the (truncus cerebri ) relevel of the body - the level of neurons. spectively is phylogenetically much older. Roughly speaking, it is the "extended spinal cord" and thus the connection between brain and spinal cord. The brain- 2.2 Neurons are information stem can also be divided into different arprocessing cells eas, some of which will be exemplarily introduced in this chapter. The functions will be discussed from abstract functions Before specifying the functions and protowards more fundamental ones. One im- cesses within a neuron, we will give a portant component is the pons (=bridge), rough description of neuron functions: A a kind of transit station for many nerve sig- neuron is nothing more than a switch with nals from brain to body and vice versa. information input and output. The switch will be activated if there are enough stimIf the pons is damaged (e.g. by a cere- uli of other neurons hitting the informabral infarct), then the result could be the tion input. Then, at the information outlocked-in syndrome – a condition in put, a pulse is sent to, for example, other which a patient is "walled-in" within his neurons. own body. He is conscious and aware with no loss of cognitive function, but cannot move or communicate by any means. 2.2.1 Components of a neuron Only his senses of sight, hearing, smell and taste are generally working perfectly normal. Locked-in patients may often be able Now we want to take a look at the comto communicate with others by blinking or ponents of a neuron (Fig. 2.3 on the facing page). In doing so, we will follow the moving their eyes. way the electrical information takes within Furthermore, the brainstem is responsible the neuron. The dendrites of a neuron for many fundamental reflexes, such as the receive the information by special connections, the synapses. blinking reflex or coughing.
16
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
e. On the presynaptic side of the synaptic cleft the electrical signal is converted into a chemical signal. 2. You might think that.3: Illustration of a biological neuron with the components discussed in this text. The neurotransmitters are degraded very fast. coming from the presynaptic side.2 The neuron Figure 2. a process induced by chemical cues released there (the so-called neurotransmitters). These neurotransmitters cross the synaptic cleft and transfer the information into the nucleus of the cell (this is a very simple explanation. so we will discuss how this happens: It is not an electrical. is directly transferred to the postsynaptic nucleus of the cell. the synapses. relevant to shortening reactions that must be "hard coded" within a living organism. but a chemical process. where it is reconverted into electrical information. but later on we will see how this exactly works). electrical synapse: simple The electrical synapse is the simpler variant. nevertheless. the electrical coupling of source and target does not take place. Such connections can usually be found at the dendrites of a neuron. An electrical signal received by the synapse. the coupling is interrupted by the synaptic cleft. Thus. which is. unadjustable connection between the signal transmitter and the signal receiver.com 2. i.dkriesel. strong. so that it is possible to re- D.1 Synapses weight the individual parts of information Incoming signals from other neurons or cells are transferred to a neuron by special connections. sometimes also directly at the soma. We distinguish between electrical and chemical synapses.1. for example. there is a direct. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 17 . This cleft electrically separates the presynaptic side from the postsynaptic one. Here. The chemical synapse is the more distinctive variant. the information has to flow.2.
utmost advantages: 2. Some 2. As soon as the acarea.com cemical synapse is more complex but also more powerful lease very precise information pulses here. too. which 2. the soma accucannot flash over to the presynaptic mulates these signals. over time they can form a stronger or The axon is electrically isolated in order weaker connection. however. slender extension of the soma.3 In the soma the weighted information is accumulated One-way connection: A chemical synapse is a one-way connection. to achieve a better conduction of the electrical signal (we will return to this point later on) and it leads to dendrites. and others that slow down such stimulation. Due to the fact that there is no direct After the cell nucleus (soma ) has reelectrical connection between the ceived a plenty of activating (=stimulatpre. The amount of branching dendrites is also In spite of the more complex function.2. information other neurons. the cell nucleus Adjustability: There is a large number of of the neuron activates an electrical pulse different neurotransmitters that can which then is transmitted to the neurons also be released in various quantities connected to the current one. There are neurotransmitters that stimulate the postsynaptic cell nucleus. many different sources. in a synaptic cleft. ing.1. for example.compared with the electrical synapse .and postsynaptic area.1.Chapter 2 Biological neural networks dkriesel. An axon can. and one of the central points by means of the axon.g. that here the an extreme case. too. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . the chemical synapse has . cumulated signal exceeds a certain value (called threshold value).4 The axon transfers outgoing pulses synapses transfer a strongly stimulating signal.1. The adjustability varies The pulse is transferred to other neurons a lot. 18 D.2 Dendrites collect all parts of transfer the information to. an axon can stretch up synapses are variable.called dendrite tree.2. transfer nucleus of the neuron (which is called information to other kinds of cells in order soma ) and receive electrical signals from to control them. electrical ing) and inhibiting (=diminishing) signals pulses in the postsynaptic area by synapses or dendrites. which are then transferred into the nucleus of the cell. The axon is a in the examination of the learning long. That is. to one meter (e.2. some only weakly stimulating ones. within the spinal cord). In ability of the brain is. So now we are back at the beginning of our description of the neuron Dendrites branch like trees from the cell elements.
e. there is of course the central question of how to maintain these concentration gradients: Normally. Concentration gradient: As described above the ions try to be as uniformly distributed as possible. Thus. we now want to take a small step from biology towards technology.. i. potential in the resting state of the neu- D. we will find certain kinds of ions more often or less often than on the inside. To maintain the potential. we assume that no electrical signals are received from the outside. In the membrane (=envelope) of the neuron the charge is different from the charge on the outside.e.. This difference in charge is a central concept that is important to understand the processes within the neuron. whose concentration varies within and outside of the neuron.dkriesel. the difference in charge. The difference is called membrane potential.2 The neuron ron. But another group of negative ions. a simplified introduction of the electrochemical information processing should be provided. In this case. The membrane potential. but not for others. the neuron actively maintains its membrane potential to be able to process information. and therefore it slowly diffuses out through the neuron’s membrane. If the concentration of an ion is higher on the inside of the neuron than on the outside. the membrane potential is −70 mV. i.2. various mechanisms are in progress at the same time: 2.2. diffusion predominates and therefore each ion is eager to decrease concentration gradients and to spread out evenly. the inside of the Let us first take a look at the membrane neuron becomes negatively charged. In doing so. Since we have learned that this potential depends on the concentration gradients of various ions. is created by several kinds of charged atoms (ions). which is permeable to some ions. so finally there would be no membrane potential anymore. it will try to diffuse to the outside and vice versa. a potential. 2. Thus.1 Neurons maintain electrical membrane potential One fundamental aspect is the fact that compared to their environment the neurons show a difference in electrical charge. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 19 .2. If this happens. collectively called A− . remains within the neuron since the membrane is not permeable to them.com 2. This descent or ascent of concentration is called a concentration gradient.2 Electrochemical processes in the neuron and its components After having pursued the path of an electrical signal from the dendrites via the synapses to the nucleus of the cell and from there via the axon into other dendrites. If we penetrate the membrane from the inside outwards. The positively charged ion K+ (potassium) occurs very frequently within the neuron but less frequently outside of the neuron. the membrane potential will move towards 0 mV. How does this work? The secret is the membrane itself.
there is less sodium within the the fact that the membrane is impermeneuron than outside the neuron. Due to the low diffusion of sodium into the cell the intracellular sodium concentration increases. diffuses strongly out of the cell.sodium slowly. the sodium tential is −70 mV as observed. The intracellular charge is now very strong. although it tries to get into the cell positive ions: K+ wants to get back along the concentration gradient and into the cell. and a membrane potenback into it. ron receives and transmits signals. reach Potassium. But we want to achieve a resting membrane potential of −70 mV. The result is another gradient. sodium is positively charged tively pumped against the concentration but the interior of the cell has negative and electrical gradients. Now that we charge. The Above we have learned that sodium and sodium shifts the intracellular equilibrium potassium can diffuse through the memfrom negative to less negative. But even with these two ions a standstill with all gradients being balanced out could still be achieved. dkriesel. 20 D.ATP ) actively transports ions against the ent acts contrary to the concentration direction they actually want to take! gradient. for which the mem. positive K ions disappear. therefore it attracts Sodium is actively pumped out of the cell. compared brane . however. On the able to some ions and other ions are acother hand. All in all is driven into the cell all the more: On the the membrane potential is maintained by one hand.2. But at the same time the inside 2. which is a second reason for the know that each neuron has a membrane potential we want to observe how a neusodium wanting to get into the cell.2.2 The neuron is activated by changes in the membrane of the cell becomes less negative.Chapter 2 Biological neural networks Negative A ions remain. Now the last piece of the puzzle gets into the game: a "pump" (or rather. and so the inside of the cell becomes more negative. slowly pours through the mem. there is another important maintains the concentration gradient for ion. but is actively pumped a steady state. the protein Electrical Gradient: The electrical gradi.For this reason the pump is also called ist some disturbances which prevent this. tial of −85 mV would develop. brane is not very permeable but which. they would eventually balance out. potassium faster. so that some sort of steady state equilibhowever.rium is created and finally the resting pobrane into the cell. As a result. If these two gradients were now left alone. The pump Furthermore. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . so that + potential K pours in more slowly (we can see that this is a complex mechanism where everything is influenced by everything). thus there seem to ex. Na+ (sodium). the electrical gradient.the sodium as well as for the potassium.com with its environment. sodium-potassium pump.
the action popotassium pump.which is the electrical sensory cells. the prox. The membrane fact that the potassium channels close potential is at −70 mV and actively more slowly. This is due to the are permeable. specialized forms of neurons. Additionally.com 2. the sodium and potassium can pour in.dkriesel. Remember: Sodium wants to pour into brane. There exist. Then creases the efflux of ions even more. are closed and the potassium channels are opened.4 on the next Hyperpolarization: Sodium as well as page): potassium channels are closed again.2 The neuron They move through channels within the Stimulus up to the threshold: A stimulus opens channels so that sodium membrane. the more negatively charged than the excells "listen" to the neuron. for which a light incidence pulse. (positively kept there by the neuron. response "if required". This massive instimuli can be received from other neurons flux of sodium drastically increases or have other causes. In addition to these perbecomes more positive. this signal is transmitted to the cells conThe interior of the cell is once again nected to the observed neuron.e. there also exist channels tential is initiated by the opening of that are not always open but which only many sodium channels. i. As a result. tive sodium ions. could be such a stimulus. If the incoming amount of light exceeds the threshold. to take a closer look at the different stages of the action potential (Fig. At first the membrane potential is Resting state: Only the permanently slightly more negative than the restopen sodium and potassium channels ing potential. The positively charged The said threshold (the threshold potenions want to leave the positive intetial ) lies at about −55 mV. which inan action potential.up to apample. the neucellular concentration is much higher ron is activated and an electrical signal. As soon as the rior of the cell. the action potential. the intrareceived stimuli reach this value. 2. the These controllable channels are opened as cell is dominated by a negative ensoon as the accumulated received stimulus vironment which attracts the posiexceeds a certain threshold. i. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 21 . Additionally. is initiated. Now we want terior. it also changes the membrane pothe cell because there is a lower intential.e. tracellular than extracellular concentration of sodium. than the extracellular one. For example.Depolarization: Sodium is pouring in. As soon as manently open channels responsible for the membrane potential exceeds the diffusion and balanced by the sodiumthreshold of −55 mV. for exthe membrane potential . The intracellular charge channels. Since the opening of these channels changes the concentration of ions within and outside of the mem. Repolarization: Now the sodium channels controllable channels are opened. D.. +30 mV .
Chapter 2 Biological neural networks dkriesel. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .com Figure 2. 22 D.4: Initiation of action potential over time.
a transfer that is impossible at those parts of the axon which are situated between two nodes (internodes) and therefore insulated by the myelin sheath. the so-called nodes of Ranvier. slender extension of the soma. It is obvious that at such a node the axon is less insulated. Then the resulting pulse is transmitted by the axon. the action po1 Schwann cells as well as oligodendrocytes are vari.2.dkriesel. 180 meters per second. and mostly even several nodes are active at the same time here. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 23 . After a refractory period of 1 − 2 ms the resting state is re-established so that the neuron can react to newly applied stimuli with an action potential.2 The neuron Now you may assume that these less insulated nodes are a disadvantage of the axon .however.3 In the axon a pulse is conducted in a saltatory way We have already learned that the axon is used to transmit the action potential across long distances (remember: You will find an illustration of a neuron including an axon in Fig. 2. In simple terms. they are not. At a distance of 0. Thus. One action potential initiates the next one.1 − 2mm there are gaps between these cells. etc.tentials are not only generated by informaeties of the glial cells.3 on page 17). This mass transfer permits the generation of signals similar to the generation of the action potential within the soma. Obviously. 2. 2.com charged) potassium effuses because of its lower extracellular concentration. However. neurons (glia = glue). provide energy. the more often a neuron can fire per time. since the action potential to be transferred would fade too much until it reaches the next node. The axon is a long. mass can be transferred between the intracellular and extracellular area. Axons with large internodes (2 mm) achieve a signal dispersion of approx. The cells receiving the action potential are attached to the end of the axon – often connected by dendrites and synapses. The action potential is transferred as follows: It does not continuously travel along the axon but jumps from node to node. The pulse "jumping" from node to node is responsible for the name of this pulse conductor: saltatory conductor.2. The said gaps appear where one insulate cell ends and the next one begins. There are about 50 times tion received by the dendrites from other more glial cells than neurons: They surround the neurons. too: to constantly amplify the signal. In vertebrates it is normally coated by a myelin sheath that consists of Schwann cells (in the PNS) or oligodendrocytes (in the CNS) 1 . The shorter this break is. D. a series of depolarization travels along the nodes of Ranvier. the internodes cannot grow indefinitely. So the nodes have a task. At the nodes. which insulate the axon very well from electrical activity. the pulse will move faster if its jumps are larger. As already indicated above. insulate them from each other. the refractory period is a mandatory break a neuron has to take in order to regenerate.
for example. There can be individual receptor cells or cells forming complex sensory organs (e. the stimulus intensity is proportional to the amplitude of the action potential. which is responsible for transferring the stimulus. Action potentials can also be generated by sensory information an organism receives from its environment through its sensory cells.g. They can receive stimuli within the body (by means of the interoceptors) as well as stimuli outside of the body (by means of the exteroceptors). which is. this is an amplitude modulation. This process is a frequency modulation. which allows to better perceive the increase and decrease of a stimulus. an encoding of the stimulus. They do not receive electrical signals via dendrites but the existence of the stimulus being specific for the receptor cell ensures that the ion channels open and an action potential is developed. This is working because of the fact that these sensory cells are actually modified neurons. a gateway to the cerebral cortex and therefore can reject sensory impressions according to current relevance and thus prevent an abundance of information to be managed.com 2. The stimulus in turn controls the frequency of the action potential of the receiving neuron.3 Receptor cells are modified neurons 2. Specialized receptor cells are able to perceive specific stimulus energies such as light. Therefore. as we have already learned. These pulses control the amount of the related neurotransmitter. it will be interesting to look at how the information is processed. the signals are amplified either during transduction or by means of the stimulus-conducting apparatus. Here. Usually. After having outlined how information is received from the environment.Chapter 2 Biological neural networks dkriesel. The resulting action potential can be processed by other neurons and is then transmitted into the thalamus. however. the stimulus energy itself is too weak to directly cause nerve signals. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . This process of transforming stimulus energy into changes in the membrane potential is called sensory transduction. eyes or ears). Technically. 24 D. the sense of smell).3. temperature and sound or the existence of certain molecules (like. Secondary receptors. continuously transmit pulses. A good example for this is the sense of pain.1 There are different receptor cells for various types of perceptions Primary receptors transmit their pulses directly to the nervous system.
On the lowest level.e. Firstly. Other sensors change their sensitivity according to the situation: There are taste receptors which respond more or less to the same stimulus according to the nutritional condition of the organism. the information is not only received and transferred but directly processed.3 Receptor cells this subject is to prevent the transmission of "continuous stimuli" to the central nervous system because of sensory adaptation : Due to continuous stimulation many receptor cells automatically become insensitive to stimuli. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 25 .2 Information is processed on every level of the nervous system There is no reason to believe that all received information is transmitted to the brain and processed there. are situated much lower in the hierarchy. doesn’t matter as well. The information processing is entirely decentralized. The filtering of information with respect to the current relevance executed by the midbrain is a very important method of information processing. which serves – as we have already learned – as a gateway to the cerebral cortex. and that the brain ensures that it is "output" in the form of motor pulses (the only thing an organism can actually do within its environment is to move). an overload is prevented and secondly. for example in the form of amplification: The external and the internal ear have a specific shape to amplify the sound. too. On closer examination. One of the main aspects of D. receptor cells are not a direct mapping of specific stimulus energy onto action potentials but depend on the past.com 2. which leads us again from the abstract to the fundamental in our hierarchy of information processing. Now let us continue with the lowest level. information processing can already be executed by a preceding signal carrying apparatus. The midbrain and the thalamus. If a jet fighter is starting next to you. It is certain that information is processed in the cerebrum. we want to take a look at some examples. i. at the receptor cells. But even the thalamus does not receive any preprocessed stimuli from the outside. this is necessary.3. Thus. small 2. In order to illustrate this principle. the sensory cells. Even before a stimulus reaches the receptor cells. the fact that the intensity measurement of intensive signals will be less precise. since the sound pressure of the signals for which the ear is constructed can vary over a wide exponential range. Here.dkriesel. which is the most developed natural information processing structure. which also allows – in association with the sensory cells of the sense of hearing – the sensory stimulus only to increase logarithmically with the intensity of the heard signal. a logarithmic measurement is an advantage.
pound eye from the outside. organs often found in compound eye (Fig. movies with 25 images per second appear as a fluent motion). i.. which projects a sharp image onto the sensory cells behind. The different wavelengths of this electromagnetic radiation are perceived by the human eye as different colors. the single lens eye.com changes in the noise level can be ig. the spatial resolution. the eye. we insects and crustaceans. individual eyes. exist much longer than the human. Consequently.1 Compound eyes and pinhole eyes only provide high temporal nored. sensory organs have been developed which can detect such electromagnetic radiation and the wavelength range of the radiation perceivable by the human eye is called visible range or simply light. Since the individual eyes can be distinguished. we will briefly describe "usual" light Let us first take a look at the so-called sensing organs. found in octopus species and work – as you can guess – similar to a pinhole camera. Pinhole eyes are. The visible range of the electromagnetic radiation is different for each organism. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .Chapter 2 Biological neural networks dkriesel. however. the spatial resolution is much higher than in the compound eye.5 on the next nature. But compound eyes have advantages. too. The compound will discuss the information processing in eye consists of a great number of small.3 An outline of common light sensing organs For many organisms it turned out to be extremely useful to be able to perceive electromagnetic radiation in certain regions of the spectrum. of compound eyes must be very low and the image is blurred.3. the individual eyes are clearly visible and arranged in a hexagonal pattern.e.. from an evolutionary point of view. But due to the very small opening for light entry the resulting image is less bright. For the third light sensing organ page). Certain compound eyes process more than 300 images per second (to the human eye.3. A pinhole eye has a very small opening for light entry. others can even perceive additional wavelength ranges (e. low temporal resolution 26 D. low spatial resolution pinhole camera: high spat. or spatial resolution Just to get a feeling for sensory organs and information processing in the organism. If we look at the com- 2. which is.e.g. i. Some organisms cannot see the colors (=wavelength ranges) we can see. common in described below. for example.3. Each individual eye has its own nerve fiber which is connected to the insect brain. Compound eye: high temp. for example.2. it is obvious that the number of pixels. 2. in the UV range). especially for fast-flying insects. Thus. Before we begin with the human being – in order to get a broader knowledge of the sense of sight– we briefly want to look at two organs of sight which.
3 Receptor cells 2. 2 There are different kinds of bipolar cells. This means that here the information has already been summaintensity. which the image.2 Single lens eyes combine the ties). high-resolution image of the environment at high or variable light bipolar cell.5: Compound eye of a robber fly Single lense eye: high temp. as well. Finally. We want to briefly discuss the different steps of this information processing and in doing so. the receptive field. but they are more they are sensitive to such an extent complex that only one single photon falling on the retina can cause an action poThe light sensing organ common in vertetential. we follow the way of the information carried by the light: Figure 2. The resulttransmit their signals to one single ing image is a sharp. These receptors are the real advantages of the other two light-receiving part of the retina and eye types.com 2. but to discuss all of them would go too far. the now transformed complex.3. the size of the pupil can transmit their information to one ganbe adapted to the lighting conditions (by glion cell. which expands of photoreceptors that affect the ganor contracts the pupil). the larger the field of perin pupil dilation require to actively focus ception. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 27 . Various bipolar cells can to the pinhole eye.3 The retina does not only receive information but is also responsible for information processing The light signals falling on the eye are received by the retina and directly preprocessed by several layers of informationprocessing cells. Therefore. the single lens eye covers the ganglions – and the less contains an additional adjustable lens.3.3. But in contrast ganglion cells. and spat. On the other hand it is more rized. D.3. These differences glion cell. Then several photoreceptors brates is the single lense eye. (retina ). The higher the number means of the iris muscle. resolution Photoreceptors receive the light signal und cause action potentials (there are different receptors for different color components and light intensi2.dkriesel. Similar to the pinhole eye the light signal travels from several bipolight enters through an opening (pupil ) lar cells 2 into and is projected onto a layer of sensory cells in the eye.
the bodily functions are work. has a considThese first steps of transmitting visual inerable sensory system because of comformation to the brain show that informapound eyes. Now we want to take a look at [RD05]): the 302 neurons are required by the nervous horizontal and amacrine cells. blurred in the peripheral field of vision. Amacrine cells can further intensify certain With 105 neurons the nervous system of stimuli by distributing information a fly can be constructed. we have learned about the information processing in An overview of different organisms and the retina only as a top-down struc. is based upon this massive division of Of course. dimensional space. A fly can from bipolar cells to several ganglion evade an object in real-time in threecells or by inhibiting ganglions. So the information is living organisms at already reduced directly in the retina different stages of and the overall image is. use of different attractants and odors. vibrissae. which cells are not connected from the serves as a popular model organism front backwards but laterally. information is received and.com sharp is the image in the area of this 2. on the other a fly has considerable differential and hand. nerves at the tion is processed from the first moment the end of its legs and much more. We all system’s power and resistance to errors know that a fly is not easy to catch. it can land upon the ceiling upside down. Nematodes live in the soil allow the light signals to influence and feed on bacteria. Due to the than compressing and blurring. Thus. outlines and bright points. it has a cognitive capacity similar This ensures the clear perception of to a chimpanzee or even a human. for examdevelopment ple.4 The amount of neurons in ganglion cell. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .their neural capacity (in large part from ture. is processed in parallel within milintegral calculus in high dimensions lions of information-processing cells. So far. If you reand at the same time inhibit more gard such an ant state as an individdistant bipolar cells and receptors. themselves laterally directly during the information processing in the 104 neurons make an ant (To simplify matters we neglect the fact that some retina – a much more powerful ant species also can have more or less method of information processing efficient nervous systems). they are able to social behavior and form huge states excite other nearby photoreceptors with millions of individuals. They in biology. 28 D. ual. The implemented "in hardware". When the horizontal cells are excited ants are able to engage in complex by a photoreceptor.Chapter 2 Biological neural networks dkriesel. These system of a nematode worm.
With 2 · 10 neurons there are nervous systems having more neurons than erable probability. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 29 . is able to speak.Our state-of-the-art computers are not ing. the human nervous system. Rats have an exchimpanzee. 1. prey while flying. elegant. an octopus can be positioned within the same magnitude. patient carnivores that can show a variety of behaviors. capabilities. companion of man for should be ignored here. describe a separate.4 The amount of neurons in living organisms also controlled by neurons. it can swim and has as well as the knowledge of other huevolved complex behavior. by means of his eyes while jumping in three-dimensional space and and 11 catch it with its tongue with consid. ages. an animal which is denounced as being extremely intelligent and are often used to participate in a variety of intelligence tests representative for For 6 · 109 neurons you already get a the animal world. some processing power of a fly. the human has considerable cognitive positioned within the same dimension. A frog mans to develop advanced technolocan continuously target the said fly gies and manifold social structures. It uses acoustic signals to localize able to keep up with the aforementioned self-camouflaging insects (e. one of the animals being traordinary sense of smell and orienvery similar to the human. but these 1. The brain of a frog can be 1011 neurons make a human. Honeybees build colonies and have 3 · 108 neurons can be found in a cat. to abThe frog has a complex build with stract. amazing capabilities in the field of which is about twice as much as in aerial reconnaissance and navigation. a dog. We know that cats are very 4 · 106 neurons result in a mouse. Only very few people know that. tation.8 · 106 neurons we have enough ular companion of man: cerebral matter to create a honeybee. exact up to several centimeters. room.g. Usually.6 · 108 neurons are required by the brain of a dog. D. for example. Now take a look at another popWith 0. By the way. by only using their sense of hear. to remember and to use tools many functions. The bat can should mention elephants and certain navigate in total darkness through a whale species.com 2. in labyrinth orientation the octopus is vastly superior to the rat.dkriesel. and they also show social behavior.5 · 107 neurons are sufficient for a rat. Recent research moths have a certain wing structure results suggest that the processes in nerthat reflects less sound waves and the vous systems might be vastly more powecho will be small) and also eats its erful than people thought until not long ago: Michaeva et al. Here we 5 · 107 neurons make a bat. and here the world of vertebrates already begins.
a scalar. have to cross the synaptic cleft where the signal is changed again by variable chem. The set of such weights reptransmit their signal via the axon. This means that after itself emits a pulse or not – thus. In the receiving neuron inputs are summarized to a pulse acthe various inputs that have been postcording to the chemical change. They are multiplied by rons are linked to each other in a weighted a number (the weight) – they are way and when stimulated they electrically weighted.5 Transition to technical ron only consists of one component. 30 D. neurons: neural networks Several scalar outputs in turn form the vectorial input of another neuron. Posterity will show if they are right. which we will get to lated by the cumulated input.Accumulating the inputs: In biology. too. the neuron know later on. Vectorial input: The input of technical Adjustable weights: The weights weighting the inputs are variable. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . Scalar output: The output of a neuron is a scalar. Our brief summary tor. which means that the neu2. but they first original and technical adaptation. instead of a vecthe cumulated input. i.Chapter 2 Biological neural networks synapse-integrated information way of information processing [MBW+ 10]. the outaccumulation we continue with only put is non-linear and not proportional to one value. In nature a neuron receives pulses of 103 to 104 other neurons on average. I want to briefly remains. the ical processes. summarize the conclusions relevant for the technical part: Synapses change input: In technical neural networks the inputs are preproWe have learned that the biological neucessed. cal side this is often realized by the Depending on how the neuron is stimuweighted sum. similar to neurons consists of many components. corresponds exactly with the few elements of biological neural networks we want to Non-linear characteristic: The input of take over into the technical approximaour technical neurons is also not protion: portional to the output. processed in the synaptic cleft are summathey are accumulated – on the technirized or accumulated to one single pulse.com therefore it is a vector.e.. From resents the information storage of a the axon they are not directly transferred neural network – in both biological to the succeeding neurons. dkriesel. are a caricature of biology This particularly means that somewhere in the neuron the various input How do we change from biological neural components have to be summarized in networks to the technical ones? Through such a way that only one component radical simplification.
the chemical processes at the synaptic cleft. After this transition we now want to specify more precisely our neuron model and add some odds and ends. It is estimated that a human brain consists of approx.5 Technical neurons as caricature of biology bits of information. 1011 nerve cells.dkriesel. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 31 . So our current. with components xi . For this exercise we assume 103 synapses per neuron. Naïvely calculated: How much storage capacity does the brain have? Note: The information which neuron is connected to which other neuron is also important. These are multiplied by the appropriate weights wi and accumulated: wi x i . This adds a great dynamic to the network because a large part of the "knowledge" of a neural network is saved in the weights and in the form and power of the chemical processes in a synaptic cleft. only casually formulated and very simple neuron model receives a vectorial input x.com 2. i The aforementioned term is called weighted sum. Let us further assume that a single synapse could save 4 D. each of which has about 103 to 104 synapses. Exercises Exercise 4. Afterwards we will take a look at how the weights can be adjusted. Then the nonlinear mapping f defines the scalar output y : y=f i wi x i .
.
weighted connections between those neurons. If in the following chapters several mathematical variables (e. All other time steps are referred to analogously. for example. the neurons. the next time step as (t + 1). the notation will be.Chapter 3 Components of artificial neural networks Formal definitions and colloquial explanations of the components that realize the technical adaptations of biological neural networks. discrete time steps 3. Time is divided into discrete time steps: Definition 3. of course. certain point in time. Initial descriptions of how to combine these components into a neural network. Here. respectively. netj or oi ) refer to a From a biological point of view this is. 3. The current time (present time) is referred to as (t).2 Components of neural networks (t) A technical neural network consists of simple processing units. netj (t − 1) or oi (t).g. After this chapter you will be able to read the individual chapters of this work without having to know the preceding ones (although this would be useful). This chapter contains the formal definitions for most of the neural network components used later in the text. and directed. the strength of a connection (or the connecting weight ) be- 33 . the preceding one as (t − 1). but it significantly simplifies the implementation. not very plausible (in the human brain a neuron does not wait for another one).1 (The concept of time).1 The concept of time in neural networks In some definitions of this text we use the term time or the number of cycles of the neural network.
The definition of connections has already been included in the definition of the neural network. 3. here again. network = neurons + weighted connection wi. which is according to fig. Looking at a neuron j .2 (Neural network). Indeed. in this case the numeric neural network is a sorted triple 0 marks a non-existing connection.Chapter 3 Components of artificial neural networks (fundamental) dkriesel. where w((i. e. an instance of the class NeuralNetworkDescriptor is created in the first place. optionally.e. 3. weights method W So the weights can be implemented in a square weight matrix W or. Depending on the facing page in top-down direction): the point of view it is either undefined or 0 for connections that do not exist in the network. SNIPE: Connection can be set using the NeuralNetwork.1 on ron j . j ∈ N} whose elements are called connections between neuron i and The neurons and connections comprise the neuron j . where N is the set of neurons and ton diagram 2 .j 1 .setSynapse. the descriptor object is used to instantiate an arbitrary number of NeuralNetwork objects. 3. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . To get started with Snipe programming. The descriptor object roughly outlines a class of neural networks.1 Connections carry information SNIPE: In Snipe. it defines the number of neuron layers in a neural network. i.2. 2 Note that. nection begins. the weight of following the path of the data within a the connection between neuron i and neu. The function w : V → R defines following components and variables (I’m the weights. In a second step.com n. A target. the documentations of exactly these two classes are – in that order – the right thing to read. But in this text I try to use the notation I found more frequently and in the more significant citations.g. V. that is processed by neurons Data are transferred between neurons via connections with the connecting weight being either excitatory or inhibitory. because it is enables to create and maintain general parameters of even very large sets of similar (but not neccessarily equal) networks.2. which neuron is the Definition 3. and the column number of the matrix indicating. we will usually find in a weight vector W with the row numa lot of neurons with a connection to j . is shortened to wi. be interchanged in wi.j tween two neurons i and j is referred to as ber of the matrix indicating where the conwi.2 The propagation function converts vector inputs to scalar network inputs 34 D. w) with two sets N . V a set {(i. as well. The published literature is not consistent here. V and a funcmatrix representation is also called Hintion w. j )). a consistent standard does not exist.j .neuron.j . in some of the cited literature axes and rows could be interchanged. This (N. j )|i. The presented layout involving descriptor and dependent neural networks is very reasonable from the implementation point of view. Here. 1 Note: In some of the cited literature i and j could which transfer their output to j .
Definition 3. . verarbeitet Eingaben zur Netzeingabe) Eingaben anderer Neuronen Netzeingabe (Erzeugt aus Netzeingabe und alter dkriesel. n} : ∃wiz . SNIPE: The propagation function in Snipe was implemented using the weighted sum. . .3 (Propagation function and network input). to a certain extent. oin of other neurons i1 . . in (which are connected to j ). Then the network input of j .com Aktivierung die neue Aktivierung) Aktivierung Aktivierungsfunktion 3.Propagierungsfunktion (oft gewichtete Summe. . i2 . and transforms them in consideration of the connecting weights wi.j into the network input netj that can be further processed by the activation function.2 Components of neural networks Ausgabe zu anderen For aNeuronen neuron j the propagation func- Ausgabefunktion (Erzeugt aus Aktivierung die Ausgabe. The activation function of a neuron implies the threshold value. is calculated by the propagation function fprop as follows: netj = fprop (oi1 . . Thus. ist oft Identität) tion receives the outputs oi1 .j ) (3. i2 . .2) Figure 3. 3. . such that ∀z ∈ {1. . the network input is the result of the propagation function.3 The activation is the "switching status" of a neuron Based on the model of nature every neuron is. called netj . . . . win . oin .j . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 35 . . . . in } be the set of neurons. . . transforms outputs of other neurons to net input) Network Input Activation function (Transforms net input and sometimes old activation to new activation) Activation Output function (often identity function. Let I = {i1 .1: Data processing of a neuron.j ) (3. .j . . at all times active. and the summation of the results: netj = i∈ I Data Output to other Neurons (oi · wi.1) manages inputs Data Input of other Neurons Propagation function (often weighted sum. . .2. .j . excited or whatever you will call it. wi1 . . transforms activation to output for other neurons) Here the weighted sum is very popular: The multiplication of the output of each neuron i by wi. . The D.
it can be defined as follows: dkriesel. with the threshold value Θ playing an important role. for instance Θj as Θj (t) (but for reasons of clarity. Definition 3. but generally the definition is the following: highest point of sensation Θ Definition 3. as well as the previous activation state aj (t − 1) into a new activation state aj (t). (3. fact 3. Let j be a neuron. Let j be a neuron. for example by a learning procedure. The activation function is also called transfer function.com How active is a neuron? 3. Unlike the other variables within the neural network (particularly unlike the ones defined so far) the activation function is often defined globally for all neurons or at least for a set of neurons and only the threshold values are different for each neuron.tivation function is defined as tent of the neuron’s activity and results from the activation function.4 Neurons get activated if the network input exceeds their treshold value Near the threshold value. is Activation). The acexplicitly assigned to j . So it can in particular become necessary to relate the threshold value to the time and to write. in short activation. indicates the ex. the activation function of a neuron reacts particularly sensitive.2. Θj ).Chapter 3 Components of artificial neural networks (fundamental) reactions of the neurons to the input values depend on this activation state. We should also keep in mind that the threshold values can be changed. 36 D.6 (Activation function and activation state aj . Its formal definition is included in the following definition of the activation function.5 The activation function determines the activation of a neuron dependent on network input and treshold value At a certain time – as we have already learned – the activation aj of a neuron j depends on the previous 3 activation state of the neuron and the external input. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . The Definition 3. But generally. The threshold value Θj is uniquely assigned to j and 3 The previous activation is not always relevant for marks the position of the maximum gradithe current – we will see examples for both varient value of the activation function. The threshold value is also mostly included in the definition of the activation function.4 (Activation state / activation in general).3) SNIPE: It is possible to get and set activation states of neurons by using the methods getActivation or setActivation in the class NeuralNetwork. The activation state indicates the extent of a neuron’s activation and is often shortly referred to as activation. calculates activation It transforms the network input netj . From the biological point of view the threshold value represents the threshold at which a neuron starts firing. aj (t − 1). aj (t) = fact (netj (t).5 (Threshold value in general). as already mentioned. I omitted this here).2. ants. Let j be a neuron.
Thus. it can be calculated 200 times faster because it just needs two multiplications and one addition. is impossible (as we will see later). It is possible to define individual behaviors per neuron layer.2 on the next page). Objects that inherit from this interface can be passed to a NeuralNetworkDescriptor instance. The fast hyperbolic tangent approximation is located within the class TangensHyperbolicusAnguita. the function changes from one value to another. The interface NeuronBehavior allows for implementation of custom behaviors. it has some other advantages that will be mentioned later.96016. At the price of delivering a slightly smaller range of values than the hyperbolic tangent ([−0.2) which maps to (−1. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 37 . but otherwise remains constant. 3.com SNIPE: In Snipe.5) The smaller this parameter. The Fermi function can be expanded by a temperature parameter T into the form D. Thinking about how to make neural network propagations faster. or even incorporate internal states and dynamics.96016] instead of [−1. This implies that the function is not differentiable at the threshold and for the rest the derivative is 0. which can only take on two values (also referred to as Heaviside function ). which also contains some of the activation functions introduced in the next section. What’s more.4) T which maps to the range of values of (0. 3. 3. 1).2. backpropagation learning. the more does it compress the function on the x axis. SNIPE: The activation functions introduced here are implemented within the classes Fermi and TangensHyperbolicus. 0. Also very popular is the Fermi function or logistic function (fig. activation functions are generalized to neuron behaviors. 1) and the hyperbolic tangent (fig. they "engineered" an approximation to the hyperbolic tangent.2) 1 . Incidentally.dkriesel. Both functions are differentiable. Consequently. for example. Corresponding parts of Snipe can be found in the package neuronbehavior. 1 + e −x (3. they quickly identified the approximation of the e-function used in the hyperbolic tangent as one of the causes of slowness. both of which are located in the package neuronbehavior. just using two parabola pieces and two half-lines. 1]). who have been tired of the slowness of the workstations back in 1993. Such behaviors can represent just normal activation functions. there exist activation functions which are not explicitly defined but depend on the input according to a random distribution (stochastic activation function ). 3. Due to this fact. [APZ93]. A alternative to the hypberbolic tangent that is really worth mentioning was suggested by Anguita et al. 3.6 Common activation functions The simplest activation function is the binary threshold function (fig. dependent on what CPU one uses.2 Components of neural networks 1 1+e −x T . (3. If the input is above a certain threshold. one can arbitrarily approximate the Heaviside function.
8 Learning strategies adjust a network to fit our needs Since we will address this subject later in detail and at first want to get to know the principles of neural network structures. the output function is defined globally.e.4 0. Fermi function.5 −1 −4 −2 0 x 2 4 Fermi Function with Temperature Parameter 1 0.Chapter 3 Components of artificial neural networks (fundamental) dkriesel.6 f(x) 0. Often this function is the identity. from top to bottom: Heaviside or binary threshold function.6) informs other neurons calculates the output value oj of the neuron j from its activation state aj . The output function fout (aj ) = oj (3. 3. the activation aj is directly output4 : fout (aj ) = aj .2 −0.7) fout Hyperbolic Tangent 1 0. 38 D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . we will use the identity as output function within this text. 1 2. Generally.8 0.4 tanh(x) 0. too. Let j be a neuron. I will only provide a brief and general definition here: 4 Other definitions of output functions may be useful if the range of values of the activation function is not sufficient.2. the temperature parameters of the modified Fermi func1 tions are. so oj = aj (3.5 f(x) 0 −0.6 0.6 −0.com Heaviside Function 1 3. 1 1 10 und 25 .8 −1 −4 −2 0 x 2 4 Unless explicitly specified differently. ordered ascending by steepness. i.2 0 −4 −2 0 x 2 4 Definition 3. Figure 3.2 0 −0. The original Fermi function is represented by dark colors. hyperbolic tangent.4 −0.2: Various popular activation functions.2.8 0.7 An output function may be used to process the activation once again The output function of a neuron j calculates the values which are transferred to the other neurons connected to j . The Fermi function was expanded by a temperature parameter.7 (Output function). More formally: 0. 5.
network of layers D. 3. Snipe defines different kinds of are only permitted to neurons of the folsynapses depending on their source and lowing layer. i.The neuron layers of a feedforward netserted the small arrow in the upper-left work (fig. To prevent naming conand output arrows. output layer and one or more processing SNIPE: Snipe is designed for realization layers which are invisible from the outside of arbitrary network topologies. which were added for flicts the output neurons are often referred reasons of clarity. Feedforward In this text feedforward networks (fig. so that the network produces a desired output for a given input.9 (Feedforward network). with feedforward networks in which every In the Hinton diagram the dotted weights neuron i is connected to all neurons of the are represented by light grey fields. 3. that’s why the neurons are also renetwork. In fig.Definition 3. The 3. Any kind of synapse can separately be allowed or forbidden for a set of networks using the setAllowed methods in a NeuralNetworkDescriptor instance. rons and the column neurons. Hinton diagram. I want to give an overview of ferred to as hidden neurons ) and one outthe usual topologies (= designs) of neural put layer.3 on map and its Hinton diagram so that the the next page the connections permitted reader can immediately see the character. 3.3 on the following page) are the networks we will first explore (even if we will use different topologies later). We will often be confronted istics and apply them to other networks.dkriesel.neuron in one layer has only directed consisting of these elements. 3. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 39 .e. In a feedforward network each networks. to construct networks con.8 (General learning rule). In this (also called hidden layers). one cell. their target. cannot be found in the to as Ω.3 Network topologies Definition 3. I have in. Every topology nections to the neurons of the next layer described in this text is illustrated by a (towards the output layer). In order to clarify that the connections are between the line neu. the next layer (these layers are called comsolid ones by dark grey fields.for a feedforward network are represented by solid lines.3.1 Feedforward networks consist The learning strategy is an algorithm of layers and connections that can be used to change and thereby towards each following layer train the neural network.com 3. n hidden proAfter we have become acquainted with the cessing layers (invisible from the outcomposition of the elements of a neural side.3 on the following page) are clearly separated: One input layer.3 Network topologies neurons are grouped in the following layers: One input layer. Connections respect. The input pletely linked ).
3. neurons inhibit and therefore strengthen themselves in order to reach their activation limits.Chapter 3 Components of artificial neural networks (fundamental) dkriesel. Characteristic for the Hinton diagram of completely linked feedforward networks is the formation of blocks above the diagonal.1 Direct recurrences start and end at the same neuron Some networks allow for neurons to be connected to themselves. three hidden neurons and two output neurons.4 on the next page): connections that skip one or more levels. 3. 40 D. As a result.1 Shortcut connections skip layers Some feedforward networks permit the socalled shortcut connections (fig.2. These connections may only be directed towards the output layer. i ei ee } }} i i e } } i i ee } ee }} iiiiii } } } 2 ~i ~ 2 B t i GFED @ABC @ABC GFED Ω2 Ω1 3. 3.10 (Feedforward network i1 i i2 e iii} e i } eee } i i e } with shortcut connections). Similar to the ee iiiii }} ee }} i i e e } } i } ii ee }} eee feedforward network.3. 3.2 Recurrent networks have influence on themselves Recurrence is defined as the process of a neuron influencing itself by any means or by any connection.1. too. Shortcuts skip layers GFED @ABC @ABC GFED Definition 3. Therefore in the figures I omitted all markings that concern this matter and only numbered the neurons. but the connections e2 }}iiiiiii B 2 may not only be directed towards the next ~} ~}} i t i @ABC GFED GFED @ABC @ABC GFED h1 e h2 e iii} h3 layer but also towards any other subsei i ee e } i i ee iii }}} ee }} i e i quent layer.com 3. Recurrent networks do not always have explicitly defined input or output neurons.5 on the facing page).3: A feedforward network with three layers: two input neurons. which is called direct recurrence (or sometimes selfrecurrence (fig.3. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . i1 i2 h1 h2 h3 Ω1 Ω2 i1 i2 h1 h2 h3 Ω1 Ω2 Figure 3.
com 89:. neurons influence themselves D.3 Network topologies 89:. ?>=< 1 v Ð uv ?>=< 89:. 6 3. Definition 3. with the weights of these connections being referred to as wj. which are represented by solid lines.11 (Direct recurrence). On the right side of the feedforward blocks new connections have been added to the Hinton diagram.5: A network similar to a feedforward network with directly recurrent neurons. 3 0 Ð uv ?>=< 89:. ?>=< 2 v 0 v A ?>=< 89:.dkriesel. 0 Ðv ?>=< 89:.4: A feedforward network with shortcut connections. Now we expand the feedforward network by connecting a neuron j to itself. 5 GFED @ABC i1 ~t @ABC GFED h1 2 ~t GFED @ABC Ω1 s 2 ~ GFED @ABC h2 GFED @ABC i2 2 B GFED @ABC 7 h3 2 ~ C B GFED @ABC Ω 2 1 2 3 4 5 6 7 1 2 3 4 5 6 7 i1 i2 h1 h2 h3 Ω1 Ω2 i1 i2 h1 h2 h3 Ω1 Ω2 Figure 3. 4 0 Ðv A ?>=< 89:.j . Figure 3. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 41 . The direct recurrences are represented by solid lines and exactly correspond to the diagonal in the Hinton diagram matrix. In other words: the diagonal of the weight matrix W may be different from 0.
diagram are now occupied. now with additional connections between neurons and their preceding layer being allowed.3 Completely linked networks allow any possible connection Completely linked networks permit connections between all neurons. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . they will be called indirect recurrences. 6 0 Ð 89:.7 on the facing page). Then a neuron j can use indirect forwards connections to influence itself. The fields that are symDefinition 3.3. each neuron often inhibits the other neurons of the layer and strengthens itself. for example. 3. 5 VP ?>=< 0 Ð A ?>=< 89:.12 (Indirect recurrence). below the diagonal of W is different from 0.6). A metric to the feedforward blocks in the Hinton laterally recurrent network permits con. Again our network is based on a feedforward network. 3. 3. Here. Definition 3.3 Lateral recurrences connect neurons within one layer Connections between neurons within one layer are called lateral recurrences (fig. 3 g 0 Ðu ?>=< 89:. The indirect recurrences are represented by solid lines.13 (Lateral recurrence).2. Therefore. 1 g V ?>=< Ðu ?>=< 89:. As we can see. except for direct 42 D. dkriesel. 3.3. 7 1 2 3 4 5 6 7 1 2 3 4 5 6 7 Figure 3. As a result only the strongest neuron becomes active (winner-takes-all scheme ).com 89:. too.2.3.Chapter 3 Components of artificial neural networks (fundamental) 3.2 Indirect recurrences can influence their starting neuron only by making detours If connections are allowed towards the input layer. by influencing the neurons of the next layer and the neurons of this next layer influencing j (fig.6: A network similar to a feedforward network with indirectly recurrent neurons. 2 VP ?>=< 0 A 89:. 4 V ?>=< 89:. connections to the preceding layers can exist here. nections within one layer.
jn can also be realized as connecting weight of a continuously firing neuron : For this purpose an additional bias neuron whose output value Figure 3. . . which will be introduced in chapter 10. j2 . A popular example are the selforganizing maps. But threshold values Θj1 . 89:. direct recurrences normally cannot be applied here and clearly defined layers do not longer exist. 3 jk 0 Ðu ?>=< 89:. 2 4 0 CB A ?>=< 89:. ?>=< 1 k Ðu ?>=< 89:. the matrix W may be unequal to 0 everywhere. 3. Thus. D. k C ?>=< 89:.com 3.7: A network similar to a feedforward network with laterally recurrent neurons. . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 43 . .8 on the next page). Here. . 7 Definition 3. From the biological point of view this sounds most plausible. Thus. but it is complicated to access the activation function at runtime in order to train the threshold value. every neuron is always allowed to be connected to every other neuron – but as a result every neuron can become an input neuron. but the diagonal is left uncovered. Θjn for neurons j1 . 6 k 0 Ð C ?>=< 89:. . Furthermore. The direct recurrences are represented by solid lines. 5 0 Ð C A ?>=< 89:. except along its diagonal. .4 The bias neuron recurrences. filled squares are concentrated around the diagonal in the height of the feedforward blocks. recurrences only exist within the layer. the threshold value is an activation function parameter of a neuron. the connections must be symmetric (fig. In the Hinton diagram.14 (Complete interconnection). In this case. 1 2 3 4 5 6 7 1 2 3 4 5 6 7 3.dkriesel. . Therefore.4 The bias neuron is a technical trick to consider threshold values as connection weights By now we know that in many network paradigms neurons have a threshold value that indicates when a neuron becomes active.
.jn with −Θj1 . generating connections between the said bias neuron and the neurons j1 . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . j i 3b 4 j j d5 b d b j j b j bb bb jjjj bb bjj jjjb bb bb j j j j b0 j b0 Ðj Ð u jjj 89:. It is used to represent neuron biases as connection weights. i. 3. These new connections get the weights −Θj1 . . rences. . . . . By inserting a bias neuron whose output value is always 1. it is now included in the propagation funcFigure 3. A bias neuron is a neuron whose output value is always 1 and which is represented by ?>=< 89:.j1 .15. . . . . j2 . .e. . i. . Now the threshold values are implemented as connection weights (fig. Then the threshold value of the neurons j1 . .8: A completely linked network with tion. j2 . jn be neurons with threshold values Θj1 . −Θjn . jn is set to 0. = Θjn = 0 and 1 2 3 4 5 6 7 1 2 3 4 5 6 7 bias neuron replaces thresh. i o 1 2 jjjj bb bb d y b d y b j j j j b bb j j b j j bbb jjjjj bbb b0 b0 jj Ðj Ð G A ?>=< u o jjj G o ?>=< 89:. which enables any weighttraining algorithm to train the biases at the same time.e. . jn and weighting these connections wBIAS.Chapter 3 Components of artificial neural networks (fundamental) dkriesel. . . In other words: Instead of including the threshold value in the activation function. . j2 . . ?>=< RS 89:. wBIAS. . mally: Let j1 . In the Hinton diagram only the diagonal it is part of the network input. 89:. . ?>=< G A ?>=< 89:. . .9 on page 46) and can directly be trained together with the connection weights. . .com is always 1 is integrated in the network and connected to the neurons j1 . we can set Θj1 = . Definition 3. . . GS ?>=< 89:. Θjn . value with weights 44 D. . jn . More foris left blank. which considerably facilitates the learning process. they get the negative threshold values. Or even shorter: The threshold value symmetric connections and without direct recuris subtracted from the network input. . −Θjn . . . . . . 6 o 7 @ABC GFED BIAS . j2 .
x|| WVUT PQRS Gauß 3.6 Orders of activation @ABC GFED Σ ONML HIJK Σ WVUT PQRS L|H Undoubtedly.6. is to illustrate neurons according to their type of data processing. let alone with a great appear in the following text. the advantage of the bias Σ Σ Σ PQRS @ABC GFED WVUT PQRS ONML HIJK BIAS neuron is the fact that it is much easier WVUT fact Tanh Fermi to implement it in the network.1 Synchronous activation All neurons change their values synchronously. One disadvantage is that the representation of the network already becomes quite ugly with Figure 3.6 Take care of the order in which neuron activations are calculated For a neural network it is very important in which order the individual neurons receive and process the input and output the results. D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 45 . 3. By the way. a bias neuron is often referred to as on neuron. but it is – if to be implemented in hardware – only useful on certain parallel computers and especially not for feedforward networks. activation and output. From now on.10 for some examples without further explanation – the different types of neurons are explained as soon as we need them.dkriesel. and pass them on. Here.10: Different types of neurons that will only a few neurons. This order of activation is the most generic and can be used with networks of arbitrary topology. 3. i. a bias neuron was implemented instead of neuron-individual biases.e. the bias neuron is omitted for clarity in the following illustrations. which we will use several times in the following. ||c.5 Representing neurons We have already seen that we can either write its name or its threshold value into a neuron. they simultaneously calculate network inputs.com receive an equivalent neural network whose threshold values are realized by connection weights. Synchronous activation corresponds closest to its biological counterpart. The neuron index of the bias neuron is 0. Another useful representation. 3. SNIPE: In Snipe. number of them. but we know that it exists and that the threshold values can simply be treated as weights because of it. we distinguish two model classes: 3. See fig.
6. BIAS − Θ 1 0 e e e e −Θe −Θ3 2 e e e2 Ð B 0 89:. one without bias neuron on the left. some of which I want to introduce in the following: easier to implement 3. 3.Apparently. SNIPE: When implementing in software.16 (Synchronous activation). and after that calculating all activations. not at all. ai and oi are updated. this order of activation is not ues simultaneously but at different points always useful.com GFED @ABC Θ1 f ff || ff || ff | | ff | | ~| 2 @ABC GFED @ABC GFED Θ2 Θ3 GFED @ABC G ?>=< 89:. because Snipe has to be able to realize arbitrary network topologies. activation by means of the activation function and output by means of the output function.2 Asynchronous activation Here. All neurons of a network calculate network inputs at the same time by means of the propagation function.17 (Random order of activation). After that the activation cycle is complete. For n neurons a cycle is the n-fold execution of this step.Chapter 3 Components of artificial neural networks (fundamental) dkriesel. biologically plausible Definition 3. I omitted the weights of the already existing connections (represented by dotted lines on the right side). one could model this very general activation order by every time step calculating and caching every single network input. With random order of activation a neuron i is randomly chosen and its neti . ?>=< 89:. the connecting weights at the connections. however. of time. 46 D. ?>=< 0 0 Figure 3.1 Random order Definition 3. the neurons do not change their val. This is exactly how it is done in Snipe. some neurons are repeatedly updated during one cycle. The neuron threshold values can be found in the neurons. and others. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . Obviously. For this.6. Furthermore.2. there exist different orders. one with bias neuron on the right.9: Two equivalent neural networks.
the activation is calculated right after the net input. but in random order. it will cause the data propagation to be carried out in a slightly different way.2 Random permutation With random permutation each neuron is chosen exactly once. the order is generally useless and. can be taken as a starting point. implementing. Therefore. Once fastprop is enabled. a permutation of the neurons is calculated randomly and therefore defines the order of activation.dkriesel. The neuron numbers are ascending from input to output layer. for every neuron. then the inner neurons and finally the output neurons.2. The order during implementation is defined by the network topology.6.4 Fixed orders of activation and according to a fixed order. followed by all activations. it is very timeconsuming to compute a new permutation for every cycle. Definition 3.18 (Random permutation).19 (Topological activation). secondly. This may save us a lot of time: Given a synchronous activation order. networks. for which we are calculating the activations. fixed orders of activation This procedure can only be considered for can be defined as well. Initially. non-recurrent. The neuron values are calculated in ascending neuron index order. for instance. when non-cyclic. we just need one single propagation.3 Topological order 3. Then the neurons are successively processed in this order. a feedforward network with n layers of neurons would need n full propagation cycles in order to enable input data to have influence on the output of the network.2. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 47 .6. However. feedforward D.2. a fixed order of activation is preferred. Given the topological activation order. all net inputs are calculated first. In the standard mode. the neuron activations at time t + 1.e. not every network topology allows for finding a special activation order that enables saving time. With topological order of activation the neurons are updated during one cycle 3. 3. This order of activation is as well used rarely because firstly. if already existing. For all orders either the previous neuron activations at time t or. Obviously.6. which provides us with the perfect topological activation order for feedforward networks. A Hopfield network (chapter 8) is a topology nominally having a random or a randomly permuted order of activation.com 3. But note that in practice. i. often very useful Definition 3. during one cycle. In the fastprop mode. in feedforward networks (for which the procedure is very reasonable) the input neurons would be updated first. Thus. for the previously mentioned reasons.6 Orders of activation since otherwise there is no order of activation. SNIPE: Those who want to use Snipe for implementing feedforward networks may save some calculation time by using the feature fastprop (mentioned within the documentation of the class NeuralNetworkDescriptor.
. . y2 .this in relation to the representation and work with n input neurons needs n inputs implementation of the network. x2 . . that their derivatives can be exnetwork by using the components of the inpressed by the respective functions themput vector as network inputs of the input selves so that the two statements neurons. . 1. They are considered as in. . let us take a look at the fact that. x2 . .7 Communication with the outside world: input and output of data in and from neural networks Finally. Exercises n y Exercise 5. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . . . 3. They are regarded as output vector y = (y1 . many types of neural networks permit the input of data.Chapter 3 Components of artificial neural networks (fundamental) networks it is very popular to determine the order of activation once according to the topology and to use this order without further verification at runtime. and returns the output vector in the same way. yn ).20 (Input vector). for example. m 3. . the propagate method is used. . Data is put into a neural tanh(x). the output dimension is referred to as m. xn ) and y = (y1 . x Now we have defined and closely examined the basic components of neural networks – without having seen a network in action. xn . SNIPE: In order to propagate data through a NeuralNetwork-instance. As a simplification we summarize the input and output components for n input or output neurons within the vectors x = (x1 . Would it be useful (from your point of view) to insert one bias neuron in each layer of a layer-based network. regard the feedforward network shown in fig. . of course.com outputs y1 . Show for the Fermi function consequence.result of the network change? put vector x = (x1 . . x2 and outputs y1 . Data is output by a neural network by the output neurons adopting the components of the output vector in their output values. the input dimension is ref (x) as well as for the hyperbolic tangent ferred to as n. But this is not necessarily useful for networks that are capable to change their topology. such as a feedforward network? Discuss Definition 3. . Let us. A net. f (x) = f (x) · (1 − f (x)) and Definition 3. dkriesel. y2 . ym ). which means that it also has two numerical inputs x1 . Thus. . . . Then these data are processed and can produce output. As a Exercise 6. . . .3 on page 40: It has two input neurons and two output neurons. . . y2 . But first we will continue with theoretical explanations and generally describe how a neural network could learn. . A network with m output neurons provides m 2. Will the x1 .21 (Output vector). ym . . y2 . xn ). x2 . It receives the input vector as array of doubles. . tanh (x) = 1 − tanh2 (x) 48 D.
dkriesel. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 49 . 3.7 Input and output of data D.com are true.
.
Chapter 4 Fundamentals on learning and training samples Approaches and thoughts of how to teach machines. after sufficient training. 51 .g. or 7. the most interesting characteristic of neural networks is their capability to familiarize with problems by means of training and. there will always be rons. a neural network changes when its components are changing. 2. 4. 6. developing new neurons.1 There are different paradigms of learning Learning is a comprehensive term. to be able to solve unknown problems of the same class. In principle. deleting existing neurons (and so. a neural network could learn by 1. Should neural networks be corrected? Should they only be encouraged? Or should they even learn without any help? Thoughts about what we want to change during the learning procedure and how we will change it. I want to propose some basic principles about the learning procedure in this chapter. changing the threshold values of neu- 4. the question of how to implement it. developing new connections. A neural network could learn from many things but. 5. as we have learned above. about the measurement of errors and when we have learned enough. 3. of From what do we learn? course. of course. A learning system changes itself in order to adapt to e. varying one or more of the three neu- ron functions (remember: activation function. Before introducing specific learning procedures. deleting existing connections. This approach is referred to as generalization. Theoretically. changing connecting weights. propagation function and output function). As written above. environmental changes. existing connections).
we assume the change in weight to be the most common procedure. since we acnetwork.com Thus.2 (Unsupervised learning). Thus. the network tries by itself to detect similarities and to generate pattern classes. 52 D. The possibilities to develop or paradigms of learning by presenting the delete neurons do not only provide well differences between their regarding trainadjusted weights during the training of a ing sets. respectively activation functions per layer. neural network. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .1. Only the input patterns are given. Therefore it is not very popular and I will omit this I will now introduce the three essential topic here. they attract a growing interest and are often realized by using 4. it is planned to cally most plausible method. deletion of connections can be realized by additionally taking care that a connection is no longer trained when it is set to 0. which we use to train our neuto implement. we let our neural network learn by modifying the connecting weights according to rules that can be formulated as algorithms. But. not very intuitive and not ral net. and addition and removal of both connections and neurons. to identify similar patterns and to classify SNIPE: Methods of the class them into similar categories. but no learning aides cept that a large part of learning possibilities can already be covered by changes in weight.1 Unsupervised learning provides input patterns to the evolutionary procedures.Unsupervised learning is the biologiter of this text (however. they are also not the subject mat. Methods in NeuralNetworkDescriptor enable the change of neuron behaviors. we can develop further connections by setting a non-existing connection (with the value 0 in the connection matrix) to a value different from 0. The training set only consists of input patterns. Therefore a learning procedure is always an algorithm that can easily be implemented by means of a programming language. Furthermore. As for the modification of threshold values I refer to the possibility of implementing them as weights (section 3. A training set (named P ) is a set of training The change of neuron functions is difficult patterns.Chapter 4 Fundamentals on learning and training samples (fundamental) As mentioned above. Moreover. we perform any of the first four of the learning paradigms by just training synaptic weights. exactly biologically motivated. Let a training set be defined as follows: Learning by changes in weight Definition 4. P Definition 4. but also optimize the network topology. Later in the text I will assume that the definition of the term desired output which is worth learning is known (and I will define formally what a training pattern is) and that we have a training set of learning samples. the network tries training). but is not extend the text towards those aspects of suitable for all problems. Thus. NeuralNetwork allow for changes in connection weights. dkriesel.4).1 (Training set).
Intuitively it is clear that this procedure should This learning procedure is not always biobe more effective than unsupervised learn. how right or wrong it was. it generalises.3 (Reinforcement learning). the network. put and output patterns independently after the training.2 Reinforcement learning results to unknown. which defines turned. for each training set that is fed into the net. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 53 . for instance. where mathematical formalisation of learning and the network weights can be changed is discussed. Forward propagation of the input by the network. work the output.are corresponding to the following steps: Entering the input pattern (activation of input neurons).in this text .com 4. The training set consists of input patterns network can In reinforcement learning the network with correct results so that the 1 receive a precise error vector can be rereceives a logical or a real value after completion of a sequence. which . generation of the output. The training set consists of input patterns.fective and therefore very practicable.4 (Supervised learning). The objeclar example of Kohonen’s self-organising tive is to change the weights to the effect that the network cannot only associate inmaps (chapter 10). correct results in the form of the precise activation of all output neurons.1. whether it behaves well or bad network receives reward or punishment 4. whether the result is right or wrong.1.Corrections are applied. At first we want to look at the the supervised learning procedures in general.3 Supervised learning methods provide training patterns together with appropriate desired outputs learning scheme network receives correct results for samples In supervised learning the training set consists of input patterns as well as their Corrections of the network are calculated based on the error vector.logically plausible. but can provide plausible 4. similar input patterns. but it is extremely efing since the network receives specific crit. Definition 4. Thus. methods provide feedback to i. D.according to their difference.2. possibly. era for problem-solving. after completion of a sequence a value is returned to the network indicating whether the result was right or wrong and. can directly 1 The term error vector will be defined in section be compared with the correct solution and 4. Comparing the output with the desired output (teaching input ). provides error vector (difference vector).e. Definition 4.1 Paradigms of learning Here I want to refer again to the popu.dkriesel.
e. The network learns directly from the errors of each training sample. the total error is calculated by means of a error function operation or simply accumulated see also section 4.2 Training patterns and teaching input Before we get to know our first learning rule. we need to introduce the teaching input.5 Questions you should answer before learning The application of such schemes certainly requires preliminary thoughts about some questions.com 4. and each network topology individually. answer them in the course of this text: Where does the learning input come from and in what form? desired output 54 D. whether it will reach an optimal state after a finite time or if it.1. no easy answers! 4. How must the weights be modified to allow fast and reliable learning? How can the success of a learning process be measured in an objective way? Is it possible to determine the "best" learning procedure? Is it possible to predict if a learning procedure terminates. if possible. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . Definition 4.4 Offline or online learning? It must be noted that learning can be offline (a set of training samples is presented. Offline training procedures are also called batch training procedures since a batch of results is corrected all at once. these output values are referred 4. Both procedures have advantages and disadvantages.1. i. In (this) case of supervised learning we assume a training set consisting of training patterns and the corresponding correct output values we want to see at the output neurons after the training.Chapter 4 Fundamentals on learning and training samples (fundamental) dkriesel. which will be discussed in the learning procedures section if necessary.5 (Offline learning).e. While the network has not finished training. the errors are accumube generally answered but that they have lated and it learns for all patterns at the to be discussed for each learning procedure same time. Such a training section of a whole batch of training samples including the related change in weight values is called epoch. for example. which I want to introduce now as a check list and. Several training patterns are entered into the We will see that all these questions cannot network at once.4) or online (after every sample presented the weights are changed). as long as it is generating wrong outputs. i. then the weights are changed. will oscillate between different states? How can the learned patterns be stored in the network? Is it possible to avoid that newly learned patterns destroy previously learned associations (the so-called stability/plasticity dilemma)? Definition 4.6 (Online learning).
as already mentioned. It contains a finite number of or. or to the er- Ep error vector Ep is the difference between the teaching input t and the actural output y . tj is the teaching input. Ωn the difference between output vector and teachDefinition 4.com 4.pending on whether you are learning ofdered pairs(p. Analogously to the vec. . D. . In the literature as well as in Now I want to briefly summarize the vecthis text they are called synonymously pat. . Thus. t always refers to a specific traintraining purposes because we know ing pattern p and is. Decalled P . Ω2 . tn of training sample p is nothing more than the neurons can also be combined into a an input vector.dkriesel. pn whose t1 − y1 . . training pattern into the network we retn − yn ceive an output that can be compared with the teaching input.Definition 4. input vector x. . the difference vector refers corresponding desired output.output vector y . to as teaching input. A ing input under a training input p training pattern is an input vector p with the components p1 . The class TrainingSampleLesson allows for storage of training patterns and teaching inputs. which is the desired is referred to as error vector. . Basically.8 (Teaching input). desired output is known. Let j the neural network. t) of training patterns with fline or online. training samples etc. By entering the . . which can be entered into Definition 4. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 55 . than the desired output vector to the SNIPE: Classes that are relevant training sample. which means it is the correct or de. for a neuron j with training data. t2 . eral output neurons Ω1 . and that for each neuas well as simple preprocessing of the ron individually. Ep = . p2 . the incorrect output oj .7 (Training patterns).9 (Error vector). . . The for training data are located in the package training. to a specific training pattern. . . patterns. sometimes output.2 Training patterns and teaching input p t desired output ror of a set of training patterns which is Training patterns are often simply called normalized in a certain way. Depending on be an output neuron. For sevsired output for a training pattern p.tors we have yet defined. the tor p the teaching inputs t1 . The set of training patterns is it is also called difference vector. We only use it for vector t. There is the terns. that is why they are referred to as p. the corresponding contained in the set P of the training patteaching input t which is nothing more terns. . The teaching inthe type of network being used the put tj is the desired and correct value j neural network will output an should output after the input of a certain training pattern.
top). One advice concerning notation: We referred to the output values of a neuron i as oi . and otherwise will output 0 .e. Suppose that we want the network to train a mapping R2 → B1 and therefor use the training samples from fig.Chapter 4 Fundamentals on learning and training samples (fundamental) So. whether it can use our training samples to quite exactly produce the right output but to provide wrong answers for all other problems of the same class. what x and y are for the general network operation are p and t for the network training .com Important! 4. too.1: Visualization of training results of the same training set on networks with a capacity being too high (top). But the output values of a network are referred to as yΩ . it has sufficient storage capacity to concentrate on the six training Figure 4. In this respect yΩ = oΩ is true. Thus.3 Using training samples We have seen how we can learn in principle and which steps are required to do so. finally.1: Then there could be a chance that. the output of an output neuron Ω is called oΩ .1. 4. but they are outputs of output neurons. these network outputs are only neuron outputs. After successful learning it is particularly interesting whether the network has only memorized – i. 56 D.and during training we try to bring y as close to t as possible. dkriesel. 4. Thus. the network will exactly mark the colored areas around the training samples with the output 1 (fig. Certainly. correct (middle) or too low (bottom). Now we should take a look at the selection of training data and the learning curve. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .
this rough presentation of input data does not correspond to the good generalization By training less patterns. Thus.3 Using training samples samples with the output 1. on the other hand. Always the same sequence of patterns. But this text is not about 100% 4. solve both problems. the training set into one training set really used to train . bottom) – ful training. 4.1 It is useful to divide the set of exact reproduction of given samples but about successful generalization and aptraining samples proximation of a whole function – for which it can definitely be useful to train An often proposed solution for these probless information into the network. A random permutation would spect to a given ratio.com 4. explicitly for the training. this is the standard method). that these data are included an oversized network with too much free in the training. there is no guarantee that the patterns are learned equally well (however.dkriesel. we have to withhold information from the network find the balance (fig. – provided that there are enough training samples. but it is – as already mentioned – very time-consuming to calBut note: If the verification data provide culate such a permutation. provokes that the patterns will be memoSNIPE: The method splitLesson within rized when using recurrent networks (later. and one verification set to test our 4. loring the network to the verification data.3. The usual division relations are.2 Order of pattern representation progress You can find different strategies to choose the order of pattern presentation: If patterns are presented in random sequence. We can finish the training when the network provides good results on the training data as well as on the verification data. we obviously performance we desire. the class TrainingSampleLesson allows for we will learn more about this type of netsplitting a TrainingSampleLesson with reworks). Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 57 . for instance. D. and risk to worsen the learning performance.3. middle). The solution is a third set of validation data used only On the other hand a network could have for validation after a supposably successinsufficient capacity (fig. poor results.1. do not modify the network structure until these data provide good reSNIPE: The method shuffleSamples located in the class TrainingSampleLesson sults – otherwise you run the risk of taipermutes a lesson. 70% for training data and 30% for verification data (randomly chosen). This implies This means. 4.1. even if they are not used storage capacity. lems is to divide.
which can be determined in various ways. The total error Err is based on all training samples.e. For this. The root mean square of two vectors t and y is defined as Errp = Ω∈O (tΩ norm to compare − yΩ )2 |O | .2) Depending on our method of error measurement our learning curve certainly 58 D.course of a whole epoch. surement methods and sample problems The Euclidean distance (generalization of are discussed (this is why there will be a the theorem of Pythagoras) is useful for simmilar suggestion during the discussion lower dimensions where we can still visual. which means it is gener. it is possible to use other types of error meaated online.4) Definition 4. For example.1) that means it is generated offline. To get used to further error Additionally. The motivation to create a learning curve is that such a curve can indicate whether the network is progressing or not. Definition 4.measurement methods. In this report. squared error with a prefactor. (4. The Analogously we can generate a total RMS specific error Errp is based on a single and a total Euclidean distance in the training sample.12 (Root mean square). (4.10 (Specific error).of exemplary problems). represent a distance measure between the correct and the current output of the network. surement. the root mean square (ab. Definition 4. Of course.com 4. both error meadistance are often used. Err Errp Definition 4.13 (Total error). (tΩ − yΩ )2 . too: Err = p∈ P Errp (4. the total error in the course of one training epoch is interesting and useful.3) As for offline learning.Chapter 4 Fundamentals on learning and training samples (fundamental) dkriesel. I suggest to have a breviated: RMS ) and the Euclidean look into the technical report of Prechelt [Pre94]. we can take the same pattern-specific. i. the root mean square is commonly used since it considers extreme outliers to a greater extent. ize its usefulness.11 (Euclidean distance).4 Learning curve and error measurement The learning curve indicates the progress of the error. the error should be normalized. which we are also going to use to derive the backpropagation of error (let Ω be output neurons and O the set of output neurons): Errp = 1 (tΩ − yΩ )2 2 Ω∈O Generally. The Euclidean distance between two vectors t and y is defined as Errp = Ω∈O SNIPE: There are several static methods representing different methods of error measurement implemented in the class ErrorMeasurement. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . (4.
the shape of the learning curve can provide an indication: If the learning curve of the verification samples is suddenly and rapidly rising while the learning curve of the verification objectivity 4.metaphorically speaking .com changes. for example. the representation of the learning curve can be illustrated by means of a logarithmic scale (fig. in any case. but was the first to find it.1 When do we stop learning? Now.4 Learning curve and error measurement depends on a more objective view on the comparison of several learning curves. the problems being not too difficult and the logarithmic representation of Err you can see . we reach the limit of the 64-bit resolution of our computer and our network has actually learned the optimum of what it is capable of learning. When the network eventually begins to memorize the samples. As we can also see in fig. too.4. i. Thus. 4. however. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 59 . the training is stopped when the user in front of the learning computer "thinks" the error was small enough. be overtaken by another curve: This can indicate that either the learning rate of the worse curve was too high or the worse curve itself simply got stuck in a local minimum. Remember: Larger error values are worse than the small ones. note: Many people only generate a learning curve in respect of the training data (and then they are surprised that only a few things will work) – but for reasons of objectivity and clarity it should not be forgotten to plot the verification data on a second learning curve. 4. On the other hand. 4. is boosted. A perfect learning curve looks like a negative exponential function.dkriesel. Typical learning curves can show a few flat areas as well.2.2 on the following page). there is no easy answer and thus I can once again only give you something to think about. which is no sign of a malfunctioning learning process. D. when the network always reaches nearly the same final error-rate for different random initializations – so repeated initialization and training will provide a more objective result. the big question is: When do we stop learning? Generally. it can be possible that a curve descending fast in the beginning can. too. which generally provides values that are slightly worse and with stronger oscillation. they can show some steps. that means it is proportional to e−t (fig. second diagram from the bottom) – with the said scaling combination a descending line implies an exponential descent of the error. Confidence in the results. But with good generalization the curve can decrease. a well-suited representation can make any slightly decreasing learning curve look good – so just be cautious when reading the literature. which. But. Indeed.e.a descending line that often forms "spikes" at the bottom – here.2. With the network doing a good job. 4. after a longer time of learning.
Note the alternating logarithmic and linear scalings! Also note the small "inaccurate spikes" visible in the sharp bend of the curve in the first and second diagram from bottom.0002 0.com 0.2: All four illustrations show the same (idealized.Chapter 4 Fundamentals on learning and training samples (fundamental) dkriesel.0002 0.00012 0.00015 0.0001 5e−005 0 0 1 1e−005 1e−010 Fehler Fehler 1e−015 1e−020 1e−025 1e−030 1e−035 0 100 200 300 400 500 600 700 800 900 1000 Epoche 100 200 300 400 500 600 700 800 900 1000 Epoche 0. 60 D.00018 0. because very smooth) learning curve.00016 0.0001 8e−005 6e−005 4e−005 2e−005 0 1 1 1e−005 1e−010 1e−015 1e−020 1e−025 1e−030 1e−035 1 10 Epoche 100 1000 10 Epoche 100 1000 Fehler Figure 4.00014 0.00025 0. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) Fehler .
. x2 . the direction to which a ball would roll from the starting point). The gradient operator ∇ is referred to as nabla operator. . x2 . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 61 . but principally there is no limit to the number of dimensions. . the longer the steps). g directs from any point of f towards the steepest ascent from this point. for example. the negative gradient −g exactly points towards the steepest descent. xn ) = ∇f (x1 . this could indicate memorizing and a generalization getting poorer and poorer.5 Gradient optimization notation is defined as procedures g (x1 . the overall notation of the the gradient g of the point (x. If we came into a valley. we move slowly on a flat plateau. . Therefore. Due to clarity the illustration (fig. . . . At this point it could be decided whether the network has already learned well enough at the next point of the two curves. ∇ gradient is multi-dim. 4. y ) of a twodimensional function f being g (x. with the size of the steps being proportional to |g | (the steeper the descent. Let g be a gradient. . similar to our ball moving within a round bowl. . Gradient descent procedures are generally used where we want to maximize or minimize n-dimensional functions. involves this mathematical basis and thus inherits the advantages and disadvantages of the gradient descent. In order to establish the mathematical basis for some of the following learning procedures I want to explain briefly what is meant by gradient descent : the backpropagation of error learning procedure.jump over it or we would return into the valley across the opposite hillside in order to come closer and closer to the deepest point of the valley by walking back and forth. xn ). and on a steep ascent we run downhill rapidly. Then g is a vector with n If-Then conclusions. the gradient is a generalization of the derivative for multidimensional functions. . derivative Once again I want to remind you that they are all acting as indicators and not to draw Definition 4. xn ).com data is continuously falling.14 (Gradient). Gradient descent means to going downhill in small steps from any starting point of our function towards the gradient g (which means.5 Gradient optimization procedures of its norm |g |. 4. y ) = ∇f (x. .dkriesel. The gradient is a vector g that is defined for any differentiable point of a function. Thus. that points from this point exactly towards the steepest ascent and indicates the gradient in this direction by means D. y ). components that is defined for any point of a (differential) n-dimensional function f (x1 . we would .3 on the next page) shows only two dimensions. x2 .depending on the size of our steps . and maybe the final point of learning is to be applied here (this procedure is called early stopping ). with |g | corresponding to the degree of this ascent. . Accordingly. vividly speaking. The gradient operator 4.
4 on the facing page). the faster the steps).ac.1 Gradient procedures incorporate several problems As already implied in section 4.e.5. . One problem. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . 4. with the step width being proportional to |g | (the steeper the descent. Let f be an n-dimensional function and s = (s1 .fhs-hagenberg. 4.1 Often.at/staff/sdreisei/Teaching/WS2001-2002/ PatternClassification/graddescent. s2 . i. 4. We move forward in the opposite direction of g .com Figure 4. on the right the steps over the contour lines are shown in 2D. let us have a look on their potential disadvantages so we can keep them in mind a bit. . i.5.3: Visualization of the gradient descent on a two-dimensional error function.e. Anyway.15 (Gradient descent). Gradient descent procedures are not an errorless optimization procedure at all (as we will see in the following sections) – however. get stuck within a local minimum (part a of fig.5. On the left the area is shown in 3D. they work still well on many problems. Gradient descent means going from f (s) against the direction of g . gradient descents converge against suboptimal minima Every gradient descent procedure can. Here it is obvious how a movement is made in the opposite direction of g towards the minimum of the function and continuously slows down proportionally to |g |. with the steepest descent towards the lowest point. . which makes them an optimization paradigm that is frequently used.pdf We go towards the gradient Definition 4. .Chapter 4 Fundamentals on learning and training samples (fundamental) dkriesel.1. sn ) the given starting point. towards −g with steps of the size of |g | towards smaller and smaller values of f . the gradient descent (and therefore the backpropagation) is promising but not foolproof. is that the result does not always reveal if an error has occurred. gradient descent with errors 62 D. Source:. for example.
1.2 Flat plataeus on the error surface may cause training slowness 4. 4.dkriesel.4: Possible errors during a gradient descent: a) Detecting bad minima.5.4).4). d) Leaving good minima.4 Steep canyons in the error surface may cause oscillations When passing a flat plateau. A hypothetically possible gradient one can even result in oscillation (part c of fig. not occur very often so that we can think about the possibilities b and d. 4. D.5 Gradient optimization procedures Figure 4. 4. b) Quasi-standstill with small gradient. if an acceptable minimum is found. In reality. c) Oscillation in canyons. one cannot know if the optimal minimum is reached and considers a training successOn the other hand the gradient is very ful. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 63 . 4.5.com 4. and there afterwards is no universal solution. large at a steep slope so that large steps can be made and a good minimum can possibly be missed (part d of fig.5. This problem is increasing proportionally 4.1. for instance.1. In nature. the gradient also becomes negligibly small because there is hardly a descent (part b A sudden alternation from one very strong of fig.3 Even if good minima are reached. which requires many further negative gradient to a very strong positive steps. they may be left to the size of the error surface. such an error does of 0 would completely stop the descent.4).
Another favourite example for singlelayer perceptrons are the boolean functions AND and OR. close to n = 4.1: Illustration of the parity function with three inputs. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . of course) be the hyperbolic tangent.6. We need a hidden neuron layer. depending on whether the function XOR outputs 1 or 0 . The reader may create a score tathe limits of the hyperbolic tangent (or ble for the 2-bit parity function.6.6 Exemplary problems allow for testing self-coded learning strategies We looked at learning from the formal point of view – not much yet but a little.com Ω 1 0 0 1 0 1 1 0 4. Therefore it is wiser to enter the teaching As a training sample for a function let inputs 0.and exactly here is where the first beginner’s mistake occurs. we need at least two neurons in the inner layer.Chapter 4 Fundamentals on learning and training samples (fundamental) dkriesel. n = 3 (shown in table 4.0 or −1.2 The parity function The parity function maps a set of bits to 1 or 0.1 Boolean functions A popular example is the one that did not work in the nineteen-sixties: the XOR function (B2 → B1 ). which have to be learned: 4.1).5 on the facing page) with the those values instead of 1 and −1. Thus. Basically. 4.e. we conspicuous? need very large network inputs. Let the activation function in all layers (except in the input layer.6. which we have discussed in detail. but the learning effort rapidly increases from For outputs close to 1 or -1. Trivially. The only chance to reach these network inputs are large weights. What is in case of the Fermi function 0 or 1). i. 4. It is characterized by easy learnability up to approx. i1 0 0 0 0 1 1 1 1 i2 0 0 1 1 0 0 1 1 i3 0 1 0 1 0 1 0 1 4.3 The 2-spiral problem The learning process is largely extended. Now it is time to look at a few exemplary problem you can later use to test implemented networks and learning rules. Table 4.9 as desired outputs or us take two spirals coiled into each other to be satisfied when the network outputs (fig. we now expect the outputs 1. function certainly representing a mapping 64 D.9 or −0.0. depending on whether an even number of input bits is set to 1 or not. this is the function Bn → B1 .
com 4. mathematically speaking. The difficulty increases proportionally to the size of the function: While a 3×3 field is easy to learn.6) with one colored field representing 1 and all the rest of them representing 0. the larger fields are more difficult (here we eventually use methods that are more 4.6. The 2-spiral problem is very similar to the checkerboard problem. 4. the other spiral to 0. Here. suitable for this kind of problems than the MLP).dkriesel.6 Exemplary problems Figure 4. but we put some obstacles in its way by using our sigmoid functions so that D. I just want to introduce as an example one last trivial case: the identity. The network has to understand the mapping itself.5 The identity function By using linear activation functions the identity mapping from R1 to R1 (of course only within the parameters of the used activation function) is no problem for the network. One of the spirals is assigned to the output value 1.4 The checkerboard problem We again create a two-dimensional function of the form R2 → B1 and specify checkered training samples (fig. memorizing does not help. too. only that.6.6: Illustration of training samples for the checkerboard problem R2 → B1 . This example can be solved by means of an MLP. 4. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 65 .5: Illustration of the training samples of the 2-spiral problem Figure 4. the first problem is using polar coordinates instead of Cartesian coordinates.
16 (Hebbian rule). Why am I speaking twice about activation. as well as. weights go ad infinitum 66 D. Hebb postulated his rule long before the specification of technical neurons.1)2 . The changes in weight ∆wi. ∆wi. but in the formula I am using oi and aj .7 The Hebbian learning rule is the basis for most other learning rules In 1949. 4. lems. i.Chapter 4 Fundamentals on learning and training samples (fundamental) dkriesel. 0) the weights will either increase or remain constant. "If neuron j receives an input from neuron i and if both neurons are strongly active at the same time. Hebb formulated the Hebbian rule [Heb49] which is the basis for most of the more complicated learning rules we will discuss in this text.j are simply added to the weight wi. the weights are decreased when the activation of the predecessor neuron dissents from the one of the successor neuron. also has been named in the sections about error measurement procedures.. We distinguish between the original form and the more general form. 4. Besides. the learning rate. otherwise they are increased.j ∼ ηoi aj (4. from i to j . Just try it for the fun with ∆wi. This can be compensated by using the activations (-1.4. Considering that this learning rule was preferred in binary activations.com ∆wi.6 There are lots of other exemplary problems the activation aj of the successor neuron j .6.3. 2 But that is no longer the "original version" of the the rule is: Hebbian rule. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . I want to recommend the technical which will be discussed in section report written by prechelt [Pre94] which 5.7. Donald O. it is clear that with the possible activations (1. the output oi of the predecessor neuron i.1 Original rule early form of the rule Definition 4.j being the change in weight of it.j 4. the strength of the connection between i and j ). Sooner or later they would go ad infinitum. then increase the weight wi. it is time to hava a look at our first following factors: mathematical learning rule. the output of neuron of neuron i and the activation of neuron j ? Remember that the identity is often used as output function and therefore ai and oi of a neuron are often the same. i.e. which is proportional to the Now. which is a kind of principle for other learning rules. since they can only be corrected "upwards" when an error occurs." Mathematically speaking. Thus.j . For lots and lots of further exemplary proba constant η .5) it would be difficult for the network to learn the identity.e.e.j (i.
Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 67 .dkriesel.j = η · h(oi . 4) Hebbian Rule only specifies the proporp4 = (6. 3) eral). more genp2 = (3. The generalized form of the p3 = (4. 3.17 (Hebbian rule. h receives the output of the predecessor cell oi as well as the weight from predecessor to successor wi. 2) Definition 4. p6 = (0. 6) ∆wi. 0) tionality of the change in weight to the product of two undefined functions. tj ) Thus. but p5 = (0. p1 = (2. tj ) and h(oi . rule.7 Hebbian rule 4. wi. 0. 6. 0. 0) with defined input values.6) D. we will now return to the path of specialization we discussed before equation 4. 4.2 Generalized form Exercises Most of the learning rules discussed before Exercise 7. Therefore.7. 2. After we have had a short picture of what a learning rule could look like and of our thoughts about learning itself.com 4.j ) as well as the constant learning rate η results in the change in weight. the product of the functions g (aj . As already mentioned g and h are not specified in this general definition. we will be introduced to our first network paradigm including the learning procedure.j while g expects the actual and desired activation of the successor aj and tj (here t stands for the aforementioned teaching input ). (4. Calculate the average value are a specialization of the mathematically µ and the standard deviation σ for the folmore general form [MR86] of the Hebbian lowing data points. As you can see. wi.6.j ) · g (aj .
.
Part II Supervised learning network paradigms 69 .
.
But 71 . this is not the the following layer and is called input easiest way to achieve Boolean logic. but the want to illustrate that perceptrons can weights of all other layers are allowed to be be used as simple logical components and changed. any Boolean retina are pattern detectors. depending on the threshold value Θ of the output neuron. Initially. Derivation of learning procedures and discussion of their problems. If we talk about a neural network. As already mentioned in the history of neural networks. the binary activation function represents an IF query which can also be negated by means of negative weights. 1}). but most of the time the term complish true logical information processis used to describe a feedforward network ing.1 on the next page).function can be realized by means of pertially use a binary perceptron with every ceptrons being connected in series or inoutput neuron having exactly two possi. This network has a layer of scanner neurons (retina ) Whether this method is reasonable is anwith statically weighted connections to other matter – of course. Description of a perceptron. the perceptron was described by Frank Rosenblatt in 1958 [Ros58]. All neurons subordinate to the that. with shortcut connections. {0.g. I just layer (fig. Perceptrons are multilayer networks without recurrence and with fixed input and output layers. There is no established definition for a per. a binary threshold function is used as activation function. 5.terconnected in a sophisticated way. Here we ini. theoretically speaking. Rosenblatt defined the already discussed weighted sum and a non-linear activation function as components of the perceptron. its limits and extensions that should avoid the limitations. In a way.Chapter 5 The perceptron. Thus. backpropagation and its variants A classic among the neural networks. 1} or {−1.The perceptron can thus be used to acceptron. ble output values (e. then in the majority of cases we speak about a percepton or a variation of it.
vn Ω Abbildung 5. Kriesel – Ein kleiner Uberblick u ¨ber Neuronale Netze (EPSILON-DE) 72 D. Die durchgezogene Gewichtsschicht in bottom den unteren Abbildungen ist trainierThe solid-drawn weight layer in the two illustrations on the can beiden be trained. Left side: bar. Right side.com | 4 { 4 5 { 5 | AGFED C AGFED DC AGFED GFEDu sr @ABC @ABC @ABC @ABCu s GFED @ABCu yyy dd ~ yyy ooo ~~ ooooo yyy ddd ~ yyy dd o ~ yyy dd ~~~ooooo yy9 1 ~ wooo Σ WVUT PQRS L|H @ABC GFED @ABC @ABC GFED GFED @ABC @ABC GFED i3 i2 g i i1 GFED i4 nn 5 gg { n n { n gg { n gg {{ nnn gg {{nnnnn {n n g3 { { } n @ ?>=< 89:. nen Ansichten. with the name of each neuron Unten: Ohne eingezeichnete feste Gewichtsschicht. The fixed-weight layer will noim longer be taken into in the unserer Konvention. Right side. lower part: Without indicated fixed-weight layer.1: Architecture a perceptron with one layer ofSchicht variable connections in different views. Oben: Am Beispiel der Informationsabtastung im with Auge. Wir werden die feste Gewichtschicht weiteren Verlauf der account Arbeit nicht mehr course of this work. betrachten. upper part: Drawing of the same example indicated fixed-weight layer using the Mitte: Skizze desselben mit eingezeichneter fester Gewichtsschicht unter Verwendung der definierdefined designs of the functional descriptions for neurons. 70 ¨ D. ten funktionsbeschreibenden Designs f¨ ur Neurone.Kapitel 5 Das Perceptron dkriesel. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . backpropagation and its variants dkriesel.com Chapter 5 The perceptron. mit Benennung der einzelnen Neuronen nach corresponding to our convention. Example of scanning information in the eye.1: of Aufbau eines Perceptrons mit einer variabler Verbindungen in verschiedeFigure 5.
Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 73 .1. Information processing neurons somehow process the input information. Then the activation function of the neuron is the binary threshold function. because this layer only forwards the input values. Therefore the input neuron is repre@ABC . Before providing the definition of the perceptron.3 (Perceptron). A binary neuron sums up all inputs by using the weighted sum as propagation function. Definition 5. input neuron only forwards data Definition 5. 5. I therefore suggest keeping my definition in the back of your mind and just take it for granted in the course of this work. It exactly forwards the information received.e.1 on the facing page) is1 a feedforward network containing a retina that is used only for data acquisition and which has fixed-weighted connections with the first neuron layer (input layer). D. since they do not process information in any case. A feedforward network often contains shortcuts which does not exactly correspond to the original description and therefore is not included in the definition. sented by the symbol GFED Now that we know the components of a perceptron we should be able to define it. The first layer of the perceptron consists of the input neurons defined above. One neuron layer is completely linked with the following layer. do not represent the identity function. Definition 5. So. The perceptron (fig. This leads us to the complete depiction of information processing neurons. 5. are similarly represented by Σ WVUT PQRS Tanh Σ WVUT PQRS Fermi Σ ONML HIJK . As a matter of fact the first neuron layer is often understood (simplified and sufficient for this method) as input layer. i. Other neurons that use retina is unconsidered the weighted sum as propagation function but the activation functions hyperbolic tangent or Fermi function. which should be indicated by the symbol . An input neuron is an identity neuron. or with a separately defined activation function fact .1 (Input neuron).com we will see that this is not possible without connecting them serially. fact These neurons are also referred to as Fermi neurons or Tanh neuron. the depiction of a perceptron starts with the input neurons. The fixed-weight layer is followed by at least one trainable weight layer. it represents the identity function. L|H Σ PQRS namely WVUT L|H . The retina itself and the static weights behind it are no longer mentioned or displayed.dkriesel. which we want to illustrate by the sign Σ. We can see that the retina is not included in the lower part of fig. Thus. I want to define some types of neurons used in this chapter. which can be illustrated by .2 (Information processing neuron). 1 It may confuse some readers that I claim that there is no definition of a perceptron but then define the perceptron in the following section.
Important! 74 D. Ωn does not considerably change the concept of the perceptron (fig.3): A perceptron with several out. Ω2 .Ωwi1 .Ω wi2 . . connections with trainable weights go from the input layer to an output neuron Ω.1 on page 72).Chapter 5 The perceptron.2. which returns the information whether the pattern entered at the input neurons was recognized or not.Ω @ABC GFED i2 5. dkriesel. the bias neuron will no longer be included. all others are not. Although the weight wBIAS. . The network returns the output by means of the arrow leaving the network. Ω1 Ω2 Ω3 Certainly. The technical view of an SLP is n i n e } } i n i n n 2 ~} ~} B @ 2 ~~~ iii 9 2 n w n vn i tn @ABC GFED @ABC GFED @ABC GFED shown in fig. the existence of several output neurons Ω1 .@ABC GFED i i n i nn n i e n } } ee i dd ~ n i n n i e e } } ~ n n i n i dd e } nn ee} }ii nnn ~~ able weights and one layer of output neue } i } i} dd ei e } nn i n i en e } nnn ~~~ i n i n dd ee e } } i n rons Ω. .Figure 5. A singlelayer perceptron (SLP ) is a @ABC @ABC @ABC GFED GFED @ABC GFED i3 e i5 i1 d i4 i2 GFED perceptron having only one layer of vari. Definition 5.2: A singlelayer perceptron with two input neurons and one output neuron. and fastprop is activated. 1 trainable layer Figure 5.3: Singlelayer perceptron with several output neurons put neurons can also be regarded as several different perceptrons with the same input. In future. backpropagation and its variants SNIPE: The methods setSettingsTopologyFeedForward and the variation -WithShortcuts in a NeuralNetworkDescriptor-Instance apply settings to a descriptor. which are appropriate for feedforward networks or feedforward networks with shortcuts. Thus. 5.1 The singlelayer perceptron provides only one trainable weight layer Here. The respective kinds of connections are allowed.Ω is a normal weight and also treated like this. a singlelayer perception (abbreviated SLP) has only one level of trainable weights (fig. 5. As a reminder. The trainable layer of weights is situated in the center (labeled). 5. the bias neuron is again included here. ?>=< Ω wBIAS. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . .4 (Singlelayer perceptron).com @ABC GFED BIAS @ABC GFED i1 2 89:. I have represented it by a dotted line – which significantly increases the clarity of larger networks.
1 The singlelayer perceptron 5.1. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 75 . the threshold values are written into the neurons. Now we want to know how to train a singlelayer perceptron.5 1 During the exploration of linear separability of problems we will cover the fact that at least the singlelayer perceptron unforFigure 5. The activation function of the information processing neuron is the binary threshold function.com GFED @ABC ee ee GFED @ABC } } }} 1 1e ee } } e2 ~}} @ABC GFED 1. 1. It has been proven that the algorithm converges in finite time – so in finite time the perceptron can learn anything it can represent (perceptron convergence theorem. Compared with the aforementioned perceptron learning algorithm. being far away from The Boolean functions AND and OR shown in fig.dkriesel.1.4 are trivial examples that can easily be composed. We will therefore at first take a look at the perceptron learning algorithm and then we will look at the delta rule. The upper singlelayer perlems. 5. the lower one realizes an OR.1 Perceptron learning algorithm and convergence theorem The original perceptron learning algorithm with binary neuron activation function is described in alg. fact now differentiable D. 5. ceptron realizes an AND.2 The delta rule as a gradient based learning strategy for SLPs In the following we deviate from our binary threshold value as activation function because at least for backpropagation of error we need. 1e e ee }} ~}} 2 @ABC GFED 0. But please do not get your hopes up too soon! What the perceptron is capable to represent will be explored later.5 GFED @ABC ee ee @ABC GFED } } }} 5. This fact. a differentiable or even a semi-linear activation function.4: Two singlelayer perceptrons for tunately cannot represent a lot of probBoolean functions. For the now following delta rule (like backpropagation derived in [MR86]) it is not always necessary but useful. [Ros62]). the delta rule has the advantage to be suitable for non-binary activation functions and. however. will also be pointed out in the appropriate part of this work. Where available. as you will see.
Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .. The perceptron learning algorithm reduces the weights to output neurons that return 1 instead of 0.. 1: 2: 76 D. no correction of weights 6: else 7: if yΩ = 0 then 8: for all input neurons i do 9: wi... backpropagation and its variants dkriesel.Ω := wi. and in the inverse case increases weights.increase weight towards Ω by oi } 10: end for 11: end if 12: if yΩ = 1 then 13: for all input neurons i do 14: wi.Chapter 5 The perceptron.decrease weight towards Ω by oi } 15: end for 16: end if 17: end if 18: end for 19: end while Algorithm 1: Perceptron learning algorithm.com while ∃p ∈ P and error too large do Input p into the network. calculate output y {P set of training patterns} 3: for all output neurons Ω do 4: if yΩ = tΩ then 5: Output is okay.Ω + oi {.Ω := wi.Ω − oi {.
Ω2 . the gradient until a minimum is reached. as already detotal error Err as a function of the weights: fined. gradient sample p. the error vector Ep represents the difference (t − y ) under a certain training As already shown in section 4.1 The singlelayer perceptron the learning target. I am aware of this conflict but it should not bother us here. which we here regard as the vector W . Now our learning target will certainly be. . scent). . pending on how we change the weights. to automatically learn of the network is approximately the desired output t. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 77 . that for all training samples the output y 2 Following the tradition of the literature. the pairs (p. . that Suppose that we have a singlelayer perceptron with randomly set weights which we ∀p : y ≈ t or ∀p : Ep ≈ 0. The set of these training samThis means we first have to understand the ples is called P . I previously defined W as a weight matrix. The error function Err : W → R Err(W ) output neurons are referred to as regards the set2 of weights W as a vector and maps the values onto the normalized Ω1 . Definition 5.5 (Error function). for example.dkriesel. . for an output o and a teachSo we try to decrease or to minimize the ing input t an additional index p may be error by simply tweaking the weights – set in order to indicate that these values thus one receives information about how are pattern-specific. error as function Errp (W ) D. descent procedures calculate the gradient Furthermore.com 5. we defined that for a single pattern p. Err(W ) is defined on the set of all weights Another naming convention shall be that.of an arbitrary but finite-dimensional function (here: of the error function Err(W )) put neurons and and move down against the direction of I be the set of input neurons. Ω|O| . It is obvious that a specific error function can analogously be generated Additionally. t) of the training samThe total error increases or decreases deples p and the associated teaching input t.5.e. output error (normalized because otheri is the input and wise not all errors can be mapped onto one single e ∈ R to perform a gradient deo is the output of a neuron. Sometimes this will to change the weights (the change in all considerably enhance clarity. let O be the set of out. want to teach a function by means of training samples. formally it is true faster. i. It contains. I also want to remind you that x is the input vector and y is the output vector of a neural network.
Ω of how to change this weight. we tweak every single weight and observe how the error function changes. (5.2) Now the following question arises: How is our error function defined exactly? It is not good if many results are far away from the desired ones.Ω (5. I just ask the reader to be patient for a while. backpropagation and its variants 5 4 3 2 1 0 dkriesel. 2 Ω∈O (5. Generally. Thus. neural networks have more than two connections. we now rewrite the gradient of the error-function according to all weights as an usual partial derivative according to a single weight wi.4) To simplify further analysis.): ∆W = −η ∇Err(W ). It provides the error Errp that is specific for a training sample p over the output of all output neurons Ω: Errp (W ) = 1 (tp.com Thus. ∂ Err(W ) .Ω and obtain the value ∆wi.Ω = −η Figure 5.Ω (the only variable weights exists between the hidden and the output layer Ω). which complicates the search for the minimum.5: Exemplary error surface of a neural network with two trainable connections w1 und w2 . we calculate the squared difference of the components of the vectors t and y .e. but this would have made the illustration too complex. The squared distance between the output vector y and the teaching input t appears adequate to our needs. −2 −1 w1 0 1 2 −2 −1 0 1 w2 2 ∆wi. it is similarly bad if many results are close to the desired ones but there exists an extremely far outlying result. The summation of the specific errors Errp (W ) of all patterns p then yields the definition of the error Err and there- 78 D. and sum up these squares. (5. ∂wi.1) Due to this relation there is a proportionality constant η for which equality holds (η will soon get another meaning and a real practical use beyond the mere meaning of a proportionality constant.Chapter 5 The perceptron.Ω )2 . the error function should then provide large values – on the other hand. we derive the error function according to a weight wi. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . i. given the pattern p. And most of the time the error surface is too craggy.3) weights is referred to as ∆W ) by calculating the gradient ∇Err(W ) of the error function Err(W ): ∆W ∼ −∇Err(W ).Ω − yp.
since we do not need it for minimization. (5. This derivative corresponds to the sum of the derivatives of all specific errors Errp according to this weight (since the total error Err(W ) Once again I want to think about the question of how a neural network processes data. as this formula looks very similar to the Euclidean distance. 2 p∈P Ω∈O sum over all Ω ∂ Err(W ) ∂wi.9) = fact (oi1 · wi1 .5) ∆wi. the path of the neuron outputs oi1 and oi2 .Ω ). initially is the propagation function (here weighted sum).Ω + oi2 · wi2 . If we ignore the output function.8) (5. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 79 . this output results from many nested functions: oΩ = fact (netΩ ) (5.Ω p∈P (5. Now we want to continue deriving the delta rule for linear activation functions. and so on. Similarly. Basically.Ω − yp. Because the root function decreases with its argument.10) It is clear that we could break down the output into the single input neurons (this is unnecessary here.4 on the preceding page suddenly came from and why there is no root in the equation. the result of the function is sent through another one.com 5.Ω )2 . We have already discussed that we tweak the individual weights wi.7) (5. As we can see. ∂wi.Ω ∂ Errp (W ) = −η . which the neurons i1 and i2 entered into a neuron Ω. This is just done so that it cancels with a 2 in the course of our calculation. from which the network input is going to be received.1 The singlelayer perceptron fore the definition of the error function results from the sum of the specific erErr(W ): rors): Err(W ) = p∈ P sum over all p Errp (W ) (5.Ω = −η 1 = (tp. since they do not D. we can simply omit it for reasons of calculation and implementation efforts.Ω a bit and see how the error Err(W ) is changing – which corresponds to the derivative of the error function Err(W ) according to the very same weight wi. This is then sent through the activation function of the neuron Ω so that we receive the output of this neuron which is at the same time a component of the output vector y : netΩ → fact = fact (netΩ ) = oΩ = yΩ .6) The observant reader will certainly wonder 1 where the factor 2 in equation 5.dkriesel. it does not matter if the term to be minimized is divided by 2: Therefore I am al1 lowed to multiply by 2 .Ω . Both facts result from simple pragmatics: Our intention is to minimize the error. the data is only transferred through a function.
i wi. i. Thus.i and therefore: ∂ Errp (W ) = −δp. we want to calculate the derivatives of equation 5.Ω = yp.i ∂wi.16) We insert this in equation 5. This difference is also called δp.Ω · ∂op.Ω (which is the reason for the name delta rule): ∂op.Ω i∈I The resulting derivative ∂wi. ∂wi. ∂ i∈I (op.Ω ∂wi.Ω change when the weight from i to Ω is changed? However: From the very beginning the derivation has been intended as an offline rule by means of the question of how to add the errors of all patterns and how to learn them after all patterns have been represented.Ω page.Ω ) Let us take a look at the first multiplicative factor of the above equation 5.i wi.e.Chapter 5 The perceptron. op.17) The second multiplicative factor of equation 5. and only the summand op.13) op.Ω = −op.4 on page 78) clearly shows that this change is exactly the difference between teaching input and output (tp. (5.Ω · op.Ω is changing: ∂ ∂ Errp (W ) = −δp.Ω .i · δp.Ω ) ∂wi. as we will see later in this chapter.Ω .Ω ) · ∂wi.com Due to the requirement at the beginning of the derivation.14) (op.15) (5.i wi.Ω ) ∂wi. (5. the change of the error Errp with an output op. So how does op.8 on the previous ∂wi.Ω : ∆wi.Ω contains the variable wi. which results in our modification rule for a weight wi.Ω ∂wi.Ω ) to be derived consists of many summands.Ω = η · p∈P (5.Ω = · .Ω − op.12) (5. The closer the output is to the teaching input.Ω − op.Ω ).Ω : The examination of Errp (equation 5.Ω ∂wi. backpropagation and its variants process information in an SLP). we only have a linear activation function fact .Ω = op.Ω ∂op.Ω ) (remember: Since Ω is an output neuron.Ω ∂ Errp (W ) = −(tp.Ω i∈I (op. therefore we can just as well look at the change of the network input when wi. the implementation is far more time-consuming and. Although this approach is mathematically correct.Ω · ∂wi. partially 80 D.i · δp. Thus we can replace one by the other.Ω .8 on the preceding page and due to the nested functions we can apply the chain rule to factorize the derivative ∂ Errp (W ) in equation 5.Ω . ∂ Errp (W ) ∂ Errp (W ) ∂op.Ω can now be simplified: The function i∈I (op.Ω (5. (5.11 and of the following one is the derivative of the output specific to the pattern p of the neuron Ω according to the weight wi.Ω .Ω = −δp.i wi. according to which we derive.8 on the previous page.11 which represents the derivative of the specific error Errp (W ) according to the output. the smaller is the specific error. Thus.11) ∂ dkriesel.i wi. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .
we obtain to the difference between the current activation or output aΩ or oΩ and the corresponding teaching input tΩ . between tΩ and oΩ . Apparently the delta rule only applies for SLPs. analogously to the aforementioned derivation. and there is no teaching input for the inner processing layers of neurons.6 on the following page). i2 and one output neuron Ω proportional (fig. essarily related to a pattern p): ∆wi.Ω = η · oi · δΩ .1). Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 81 . If we determine.Ω = η · oi · (tΩ − oΩ ) = ηoi δΩ (5. 2 0 1 0 1 5. D. the output values on the right.6 (Delta rule).Table 5. (5.2 Linear separability Output 0 1 1 0 The "online-learning version" of the delta rule simply omits the summation and learning is realized immediately after the presentation of each pattern. this also sim. 1 0 0 1 1 In. We want to refer to this factor as δΩ . that the function h of the Hebbian theory (equation 4.6 on page 67) only provides the output oi of the predecessor neuron i and if the function g is the difference between the desired activation tΩ and the actual activation aΩ . since the formula is always related to the teaching input.input values are shown of the left.19) If we use the desired output (instead of the activation) as teaching input.2 A SLP is only capable of representing linearly separable data Let f be the XOR function which expects ∆wi.com needs a lot of compuational effort during training.1: Definition of the logical XOR.Ω = η · oi · (tΩ − aΩ ) = ηoi δΩ (5. 5. we will receive the delta rule. The plifies the notation (which is no longer nec. δ delta rule only for SLP 5. which is also referred to as "Delta ".dkriesel.20) two binary inputs and generates a binary output (for the precise definition see taand δΩ then corresponds to the difference ble 5. and therefore the output function of the output neurons does not represent an identity. In.18) This version of the delta rule shall be used for the following definition: Definition 5. also known as WidrowHoff rule : ∆wi. the change tion by means of an SLP with two input of all weights to an output neuron Ω is neurons i1 . Let us try to represent the XOR funcIn the case of the delta rule.
A and B show the corners belonging to the sets of the XOR function that are to equality 5.f i2 .22) positive wi2 .21) netΩ = oi1 wi1 .7: Linear separation of n = 2 inputs of the input neurons i1 and i2 by a 1-dimensional We assume a positive weight wi2 . For a (as required for inequation 5. a binary activation function with the threshold value Θ and the identity as output function.which is impossible.6: Sketch of a singlelayer perceptron that shall represent the XOR function .Chapter 5 The perceptron.Ω Ω ff || f2 | ~| 89:. (5.com GFED @ABC i1 f ff f GFED @ABC i2 | || | w wi1 .Ω + oi2 wi2 .Ω . ?>=< Ω XOR? Figure 5. Depending on i1 and i2 .7).Ω (ΘΩ − oi2 wi2 .21 is then equivalent to be separated.22 is a straight line through a coordinate system defined by the possible outputs oi1 und oi2 of the input neurons i1 and i2 (fig.22) With a constant threshold value ΘΩ . the right part of inequation 5.Ω ) (5. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . Here we use the weighted sum as propagation function. the in. backpropagation and its variants dkriesel.Ω the output neuron Ω fires for 82 D.straight line. 5.Ω ≥ ΘΩ o i1 ≥ 1 w i 1 . Ω has to output the value 1 if the following holds: Figure 5.
for more difficult tasks with more inputs we need something more powerful than SLP. 5. 0).com n 1 2 3 4 5 6 number of binary functions 4 16 256 65.8).8 · 1019 lin.8: Linear separation of n = 3 inputs from input neurons i1 .5% 40. (1. we have to turn and move the straight line so that input set A = {(0. SLP cannot do everything Unfortunately.e. Figure 5. and number and proportion of the functions thereof which can be linearly separated. i2 and i3 by 2-dimensional plane. the input parameters of n many input neurons can be represented in an ndimensional cube which is separated by an SLP through an (n − 1)-dimensional hyperplane (fig. Was89]. Only sets that can be separated by such a hyperplane. which are linearly separable.2: Number of functions concerning n binary inputs. 134 share 100% 87.2 Linear separability Table 5.6% 2. 1)} is separated from input set B = {(0. can be classified by an SLP. Thus.dkriesel. 572 5. few tasks are linearly separable D. tests for linear separability are difficult. The XOR problem itself is one of these tasks.9 on the next page). For a negative wi2 . obviously. Generally.3 · 109 1. Additionally. 028. 772 94. Wid89. impossible.7% 0. it seems that the percentage of the linearly separable problems rapidly decreases with increasing n (see table 5. Note that only the four corners of the unit square are possible inputs because the XOR function only knows binary inputs. 0)} – this is. separable ones 4 14 104 1. which limits the functionality of the SLP. 536 4. 1). since a perceptron that is supposed to represent the XOR function already needs a hidden layer (fig. (1.Ω it would fire for all input combinations lying below the straight line. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 83 .002% ≈ 0% 5.2). i. In accordance with [Zel94. input combinations lying above the generated straight line. In order to solve the XOR problem. 5.
A multilayer perceptron represents an universal function approximator. this proof is not constructive and therefore it is left to us to find the correct 5.10 on the facing page). plane (in a two-dimensional input space Perceptrons with more than one layer of by means of a straight line). Unfortunately.10 on the next page). Those can be added. ers. Another trainable weight layer proceeds analogously. 3". be. a singlelayer perceptron can divide the input space by means of a hyper.com part of fig. As 3-4-MLP.9: Neural network realizing the XOR with one layer of hidden neurons can arfunction.to as multilayer perceptrons (MLP ).g.regarded here) with neuron layer 1 being low straight line 2 and below straight line the input layer.7 (Multilayer perceptron).5 1 II II II−2 $ Ö GFED @ABC 0. we – metaphorically speaking . Generally.variably weighted connections are referred stage perceptron (two trainable weight lay. which is proven by the Theorem of Cybenko [Cyb89]. in the form "recognize and n + 1 neuron layers (the retina is dispatterns lying above straight line 1. Thus.Chapter 5 The perceptron. now with the convex polygons.3 A multilayer perceptron number of neurons and weights.5 dkriesel. A two.Since three-stage perceptrons can classify rons and "attached" another SLP (upper sets of any form by combining and sepa- XOR contains more trainable weight layers more planes 3-stage MLP is sufficient 84 D. 3 neurons in the hidden layer weight layers (called multilayer perceptron and 4 neurons in the output layer as a 5or MLP) is more powerful than an SLP.An n-layer or n-stage perceptron has vex polygons by further processing these thereby exactly n variable weight layers straight lines. 5. 5. e. with only finitely many discontinuities as well as their first derivatives. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . it can be mathematically proven that even a multilayer perceptron Figure 5. three neuron layers) can classify con. backpropagation and its variants GFED @ABC @ABC GFED ee II } } II ee }} 1 II 1ee } } II ee2 ~}} @ABC GFED 1II 1.Definition 5.took an SLP with several output neu. Threshold values (as far as they are bitrarily precisely approximate functions existing) are located within the neurons. we know. subtracted or somehow processed with other operations (lower part of fig. In the following we want to use a widespread abbreviated form for different multilayer perceptrons: We denote a twostage perceptron with 5 neurons in the inA perceptron with two or more trainable put layer.
D.dkriesel. With 2 trainable weight layers.10: We know that an SLP represents a straight line. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 85 . By using 3 trainable weight layers several polygons can be formed into arbitrary sets (below). Ω GFED @ABC @ABC GFED i1 d i2 d d dd ~ ~ dd ~ ~ dd ~ ~ dd ~ ~ dd ~ ~ d ~ ~ dd dd ~ ~~ ~~~ 2 ~ 2 ~ 9 w u A GFED t B GFED @ABC GFED GFED @ABC GFED @ABC @ABC GFED @ABC @ABC h1 h2 d h3 h4 h5 h6 ~ nnn n ~ ddd n ~~ dd nnn ~~ nnnnn dd ~ n d2 ~~~ n 9 GFED w nn t EBD GFED @ABC @ABC h7 drq h8 dd ~ dd ~~ ~ dd ~ dd ~~ ~ 1 ~ 89:.com 5. ?>=< Ω Figure 5. several straight lines can be combined to form convex polygons (above).3 The multilayer perceptron @ABC GFED @ABC i1 i2 jGFED ddd jjjj ddd j j j ddjjjj dd jjjjjjjddd ddd d1 d1 jjjj tj B j @ABC GFED @ABC GFED @ABC GFED h2 h1 o h3 o o o ooo ooo o o oooo wo 9 ?>=< 89:.
Some sources count the neuron layers. Be cautious when reading the literature: There are many different definitions of what is counted as a layer. i. Backpropagation is a gradient descent procedure (including all strengths and weaknesses of the gradient descent) with the error function Err(W ) receiving all n weights as arguments (fig. Some exclude (for some reason) the output neuron layer. On Err(W ) a point of small error or even a point of the smallest error is sought by means of the gradient descent.Chapter 5 The perceptron. which can be used to train multistage perceptrons with semi-linear 3 activation functions. And it is exactly 3 Semilinear functions are monotonous and differentiable – but generally they are not linear. the most information about the learning capabilities – and I will use it cosistently. I chose the definition that provides. being n-dimensional. In this work. some count the weight layers. in my opinion. but that doesn’t matter: We have seen that the Fermi function or the hyperbolic tangent can arbitrarily approximate the binary threshold function by means of a temperature parameter T .e.3: Representation of which perceptron can classify which types of sets with n being the number of trainable weight layers. backpropagation trains the weights of the neural network. another step will not be advantageous with respect to function representations.e.com 5. 5. Binary threshold functions and other non-differentiable functions are no longer supported. backprop or BP). no advantage dkriesel. rating arbitrarily many convex polygons. You can find a summary of which perceptrons can classify which types of sets in table 5.3. Some sources include the retina. We now want to face the challenge of training perceptrons with more than one weight layer. I want to derive and explain the backpropagation of error learning rule (abbreviated: backpropagation. in analogy to the delta rule. Remember: An n-stage perceptron has exactly n trainable weight layers. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . some the trainable weight layers. i. Once again I want to point out that this procedure had previously been published by Paul Werbos in [Wer74] but had consideraby less readers than in [MR86]. Table 5. backpropagation and its variants n 1 2 3 4 classifiable sets hyperplane convex polygon any set any set as well. 86 D. To a large extent I will follow the derivation according to [Zel94] and [MR86].5 on page 78) and assigning them to the output error. Thus.4 Backpropagation of error generalizes the delta rule to allow for MLP training Next.
h we want to calculate δ ? It is obvious to select an arbitrary inner neuron h having ∂ Err(wk. ()*+ 89:. D.h as a set of L successor neurons l. neti . for the delta rule and split functions by the weighted sum is included in the numermeans the chain rule. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 87 .4. ?>=< .i ) holds for any neuron i.-. As already indicated. L l Figure 5.dkriesel. /.23 is −δh . ()*+v 89:. k K vvv a ppp p vvv aaa p vvv aa ppp wk. but the prin. be defined as the already familiar oi . netp. the subsequent layer is L.. 5.h ) ∂ Err ∂ neth = (5. etc. ()*+a /.e.h vvv aa p 5. rons.11).i . this derivation in great detail. It is therefore irrelevant whether the predeThe first factor of equation 5.l xxx rrr ¡¡¡ r r xxx ¡ r ¡ r xx9 r Let us define in advance that the network ¡ r /.h . I will not discuss ator so that we can immediately derive it. 5. in the generalized δ ).-.. under the input pattern p we used for the training... cessor neurons are already the input neuwhich we will deal with later in this text. the preceding layer is K .i etc. The numerator of the second factor of the Now we perform the same derivation as equation includes the network input. all summands of the sum drop out cipal is similar to that of the delta rule (the apart from the summand containing wk. i. which =−δh are also inner neurons (see fig. Furthermore.23) · a set K of predecessor neurons k as well ∂wk. It is lying in layer H . Let the output function be the identity again. but Σ ONML HIJK h H r¡ fact xxxxx with a generalized delta r r x x rr ¡¡ wh. as with the derivation of the delta rule. we have to generalize the variable δ for every neuron.-. we use the same formula framework as with the delta rule (equation 5. ()*+ /. let op.Again.h ∂ neth ∂wk. ()*+xr /. Since this is a generalization of the delta rule.11: Illustration of the position of our neuron h within the neural network. ?>=< .20 on page 81).-.com the delta rule or its variable δi for a neuron i which is expanded from one trainable weight layer to several ones by backpropagation.4 Backpropagation of error generalization of δ input of the individual neurons i results from the weighted sum.1 The derivation is similar to p pp vva 80 wppp the one of the delta rule. thus oi = fact (netp. We initially derive the error function Err according to a weight First of all: Where is the neuron for which w . as already mentioned. k. ()*+С /.-. differences are.-.
h (5.31) As promised. If the aforementioned equations are 88 D. The reader might already have noticed that some intermediate results were shown in frames. Exactly those intermediate results were highlighted in that way. we immediately obneuron k becomes: tain equation 5.28) (5.31: ∂ ∂ neth = ∂wk.l (5.24) (5.27. 5.Chapter 5 The perceptron.com This summand is referred to as wk.12 on the facing page. We simply calculate the second factor in the following equation 5.h · ok . which ∂ Err(netl1 . Now we want to discuss these factors being added over the subsequent layer L. . we will now discuss the −δh of equation 5.34) − tion of the activation function according ∂ netl to the network input: ∂oh ∂fact (neth ) = ∂ neth ∂ neth = fact (neth ) (5. backpropagation and its variants dkriesel.27) clearly equals the deriva∂ Err = δl (5.23 on the previous page.l · oh ∂ netl = ∂oh ∂oh = wh. This is reflected in equation 5.30) are a factor in the change in weight of ∂oh ∂oh wk. we have to point out that the derivation of the error function according to the output of an inner neuron layer depends on the vector of all network inputs of the next following layer.31 contains two factors.29) Now we insert: ⇒− ∂ Err = δl wh. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .26) (5.35) Consider this an important passage! We now analogously derive the first factor in equation 5.27) The sum in equation 5. If According to the definition of the multiwe calculate the derivative.32) (5. .h . which is split up again according of the chain rule: δh = − ∂ Err ∂ neth ∂ Err ∂oh · =− ∂oh ∂ neth (5.33: ∂ h∈H wh. netl|L| ) ∂ Err − =− (5.h ok ∂wk.25) − ∂ Err ∂ Err ∂ netl = − · ∂oh ∂ netl ∂oh l∈L (5.l ∂oh l∈L (5.33) The derivation of the output according to The same applies for the first factor accordthe network input (the second factor in ing to the definition of our δ : equation 5. the output of dimensional chain rule.h = ok k∈K wk. Therefore.30: You can find a graphic version of the δ generalization including all splittings in fig. . .
12: Graphical representation of the equations (by equal signs) and chain rule splittings (by arrows) in the framework of the backpropagation derivation.l ·oh ∂oh wh.l Figure 5.4 Backpropagation of error δh ∂ Err −∂ neth ∂oh ∂ neth Err −∂ ∂oh fact (neth ) ∂ Err −∂ netl ∂ netl l∈L ∂oh δl ∂ h∈ H wh. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 89 . which are framed in the derivation.dkriesel.com 5. The leaves of the tree reflect the final results from the generalization of δ . D.
according to our training pattern p.h from k to h is changed proportionally according to the learning rate η .h = fact (netp.h of the successor neuron h. Input changed for the outer weight layer – of course only in case of h being an inner neuron (otherweise there would not be a subsequent layer L). then (5.h ). the gradient of the activation function at the position of the network input of the successor neuron fact (netp.h .h ) holds.k of the predecessor neuron k . the output op.com the difference between teaching input tp.h − yp.h = fact (netp. If h is an inner. the result is the generalization of the delta rule. the outcome of this will be the wanted change in weight ∆wk. called backpropagation of error : ∆wk. In this case. and this is the difference.36) (δl wh. I want to explicitly mention that backpropagation is now working on three layers. Thus. hidden) neuron: 1. the gradient of the activation function at the position of the network input of the successor neuron fact (netp. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .h ) · (tp. All in all.h = ηok δh with fact (neth ) · (th − yh ) (h outside) δh = fact (neth ) · l∈L (δl wh. the output layer with the successor neuron h and the preceding layer with the predecessor neuron k .h ) · l ∈L (δp. the output of the predecessor neuron op.k .l ) (h inside) (5.l ) Teach. l∈L (δp. Here. under our training pattern p the weight wk.37) δp.Chapter 5 The perceptron. backpropagation is working on two neuron layers.38) Thus.l · wh. δ is treated differently depending on whether h is an output or an inner (i. as well as. backpropagation for inner layers (5.e. neuron k is the predecessor of the connection to be changed with the weight wk. the neuron h is the successor of the connection to be changed and the neurons l are lying in the layer following the successor neuron.h to ∆wk. 2. hidden neuron.h = ηok δh with δh = fact (neth ) · l ∈L dkriesel.h and output yp. according to the weighted sum of the changes in weight to all neurons following h. If h is an output neuron. then δp. backpropagation and its variants combined with the highlighted intermediate results.h ) and 90 D. The case of h being an output neuron has already been discussed during the derivation of the delta rule. the weight wk.l ) (5.l · wh.h from k to h is proportionally changed according to the learning rate η .l ).39) In contrast to the delta rule.
The first part is obvious. backprop expands delta rule ∆wk. Here I describe the first (delta rule) and the second part of backpropagation (generalized delta rule on more layers) in one go. Since we only use it for one-stage perceptrons. Thus.2 Heading back: Boiling summarize formulas 5.com 5.l ) (h inside) out of backpropagation in order to augment the understanding of both rules. As is generally known. we only want to use linear activation functions so that fact (lightcolored) is constant. we redelta rule ceive the following final formula for backpropagation (the identifiers p are om.8 (Backpropagation).h = ηok δh with fact (neth ) · (th − yh ) (h outside) circumstance and develop the delta rule δh = fact (neth ) · l∈L (δl wh. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 91 .42) Furthermore.l ) (h inside) (5. Like many groundbreaking inventions.40) have seen that backpropagation is defined by SNIPE: An online variant of backpropagation is implemented in the method trainBackpropagationOfError within the class NeuralNetwork. the delta rule is a mited for reasons of clarity): special case of backpropagation for onestage perceptrons and linear activation functions – I want to briefly explain this ∆wk. the result is: ∆wk. and therefore we directly merge the constant derivative fact and (being constant for at least one lerning cycle) the learning rate η (also light-colored) in η . constants can be combined.dkriesel. recursive part.4 Backpropagation of error Definition 5.41) It is obvious that backpropagation initially processes the last weight layer directly by means of the teaching input and then works backwards from layer to layer while considering each preceding change in weights. the teaching input leaves traces in all weight layers. which may meet the requirements of the matter but not of the research. which you will soon see in the framework of a mathematical gimmick. D. The result is: ∆wk. Decades of development time and work lie between the first and the second.38 on the preceding backpropagation down to page and 5.h = ηok δh with δh = fact (neth ) · (th − oh ) (5.43) This exactly corresponds to the delta rule definition.4.h = ηok δh = ηok · (th − oh ) (5.As explained above. it was not until its development that it was recognized how plausible this invention was.h = ηok δh with fact (neth ) · (th − yh ) (h outside) δh = fact (neth ) · l∈L (δl wh. We (5.39 on the facing page. Thus. the second part of backpropagation (light-colored) is omitted without substitution. If we 5.
A common error (which also seems to be a ten as η .9.the learning rate gradually as mentioned face would be very uncontrolled. Here it quickly happens that the descent of the If the value of the chosen η is too large.3. Experience shows that good learning rate values are in the range 5. A smaller learning rate is more time-consuming. in any case.9 (Learning rate). very neat solution at first glance) is to continually decrease the learning rate.at this ascent. the movements across the error sur. can cost a huge. however. Addition. but the result is more precise.1 Variation of the learning rate over time During training. Thus. a large learning rate leads to good results. the selection of η is crucial for the behaviour of backpropagation and for learning procedures in general. narrow valleys ing. how fast will be learned? η Definition 5.com 5. for example. and to slowly decrease it down to 0.4. a above. the slower backpropagation is learning. The result is that we simply get stuck could simply be jumped over. during the learning process the learning rate needs to be decreased by one order of magnitude once or repeatedly. Thus. Thus. which.4. e. proportional to the learning rate η . 92 D. 0. small η is the desired input. it is a good idea to select a larger learning rate for the weight layers close to the input layer than for the weight layers close to the output layer.2 Different layers – Different learning rates of 0. often unacceptable amount of time. Thus. Speed and accuracy of a learning procedure can always be controlled by and are always proportional to a learning rate which is writ. backpropagation and its variants dkriesel.01 ≤ η ≤ 0.3 The selection of the learning rate has heavy influence on the learning process In the meantime we have often seen that the change in weight is. learning rate is larger than the ascent of the jumps on the error surface are also a hill of the error function we are climbtoo large and. but later it results in inaccurate learning.4. The selection of η significantly depends on the problem. 5. Solution: Rather reduce ally. the network and the training data.1. For simpler problems η can often be kept constant.9.g. so that it is barely possible to give practical advise.3.Chapter 5 The perceptron. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . But for instance it is popular to start with a relatively large η . The farer we move away from the output layer during the learning process. another stylistic device can be a variable learning rate : In the beginning.
5 Resilient backpropagation is an extension to backpropagation of error One learningrate per weight We have just raised two backpropagationspecific properties that can occasionally be a problem (in addition to those which are already caused by gradient descent itself): On the one hand.com 5. we incorporate evtin Riedmiller et al. this is really pagation learns. these learning rates added. the further the weights are tionally to the gradient of the error from the output layer. Rprop takes other ways propagation and Rprop. It remains static untion. Thus the change in weight is mary ideas behind Rprop (and their connot proportional to the gradient. whether this is always [RB93. I want to compare backuseful. the weight changes are not static but Much smoother learning ηi. Rprop pursues a completely different approach: there In contrast to backprop the weight update is no global learning rate.j automatic learning rate adjustment D. Marintuitive. Before actually dealing with formuthe automatically adjusted learning las. but are au.being implemented? tomatically set by Rprop itself. Rie94]. Here. it is sequences) to the already familiar backproonly influenced by the sign of the grapagation. the slower backprofunction. but let me anticipate that default a learning rate η . Third. also the problem of an increasingly slowed down learning throughout the layers is solved in an elegant way. At first glance. without explicas well: the amount of weight change itly declaring one version superior to the ∆wi. First.j has its own learning rate for the adjustment of the learning rate is ηi. and second. Until now we still do not know how exactly the ηi. weights are changed proporthe other hand.dkriesel. Here.j simply directly corresponds to other. It is at least silient backpropagation (short Rprop ) questionable.j . Now how exactly are these ideas are not chosen by the user. To account for the temporal change. 5.j (t). However. We have already explored the disadvantages of this approach. we have to correctly call it ηi. which is sethe resulting process looks considerlected by the user. For this reason. On Weight change: When using backpropagation. let us informally compare the two prirate ηi. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 93 .j . til it is manually changed.j are adapted at Learning rates: Backpropagation uses by run time. each step is replaced and an additional step weight wi. enhanced backery jagged feature of the error surface propagation and called their version reinto the weight changes. and applies to the ably less rugged than an error funcentire network. users of backpropagation can choose a bad learning rate. dient. This not only enables more focused learning.5 Resilient backpropagation are adapted for each time step of Rprop.
If the sign changes from g (t − 1) to g (t).j (t − 1). We have already noticed that the weightspecific learning rates directly serve as absolute values for the changes of the respective weights.10 −ηi. 5.j (t) = 5.Chapter 5 The perceptron.1 Weight changes are not proportional to the gradient Let us first consider the change in weight.j (t).j is added to it. This might decrease clarity at first glance.j (t). we consider only the sign of the gradient. we again have to consider the associated gradients g of two time steps: the gradient that has just passed (t − 1) and the current one (t). The corresponding terms are affixed with a (t) to show that everything happens at the same time step. Now. we obtain a new ηi. The gradient hence no longer determines the strength. Finally. nothing happens at all.com (Weight change in if g (t) > 0 if g (t) < 0 (5. we have skipped a local minimum in the gradient.j and (W ) obtain gradients ∂ Err ∂wi.j .2 Many dynamically adjusted learning rates instead of one static To adjust the learning rate ηi. that the search needs to be more accurate. ∆wi. As with the derivation of backpropagation.j .j . Again. Hence. only the sign of the gradient matters. we must decrease the weight wi.j . which is between 1 and 0. we shorten the gra(W ) dient to: g = ∂ Err ∂wi. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . and we now must ask ourselves: What can happen to the sign over two time steps? It can stay the same.44) otherwise. If the gradient is exactly 0. backpropagation and its variants dkriesel. 5. but is nevertheless important because we will soon look at another formula that operates on different time steps. the weight needs to be increased. the last update was too large and ηi. So ηi.5. In this case we know that in the last time step (t − 1) something went wrong – gradient determines only direction of the updates η↓ 94 D. If the sign of the gradient is negative.j . Let us now create a formula from this colloquial description. Instead.j itive. +ηi.5. the big difference: rather than multiplicatively incorporating the absolute value of the gradient into the weight change. So the weight is reduced by ηi.j (t) by multiplying the old ηi. Definition Rprop). but only the direction of the weight change. (W ) If the sign of the gradient ∂ Err is pos∂wi. and it can flip. One can say.j (t−1) with a constant η ↓ . In mathematical terms.j (t) has to be reduced as compared to the previous ηi. we will deal with the remaining details like initialization and some specific constants. we derive the error function Err(W ) by the individual weights wi. There remains the question of where the sign comes from – this is a point at which the gradient comes into play. 0 We now know how the weights are changed – now remains the question how the learning rates are adjusted. once we have understood the overall system.
if the sign remains the same. Rprop only learns offline Caution: This also implies that Rprop is exclusively designed for offline. The authors of the Rprop paper explain in an obvious way that this value – as long as it is positive and without an exorbitantly high absolute value – does not need to be dealt with very critically.e. weakened)? Here we obtain our new ηi.j (t − 1). How large are η ↑ and η ↓ (i.com 5. one 1. What are the upper and lower bounds rates in Rprop). without further mathematical justification. If the gradients do not have a certain continuity. namely However. ηi.j (0) = 0. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 95 .5 Resilient backpropagation η↑ hence we additionally reset the weight up. How to choose ηi.j (5.j (t) = η ηi.j at time step (t) to details to use Rprop in 0. how are which is greater than 1. the learning process slows down to the lowest rates (and remains there). A few minor issues remain unanswered. and that is exactly what we need here. one changes – loosely speaking – the error function with each new epoch. how can perform a (careful!) increase of ηi.11 (Adaptation of learning 3. The initial value for the learning rates should be somewhere in the order of the initialization of the weights. One can set this parameter to lower values in order to allow only very cautious updates.j (0) (i.45) ↑ η ηi. which is why it is used there frequently.j can be changed only by multiplication. We now answer these questions with a quick motivation. 0 would be a rather suboptimal initialization :-) ηmin ηmax D. however. It lacks. so that it not applied at all (not shown practice in the following formula). a value of 50 which is used throughout most of the literature. since it is based on only one training pattern. Small update steps should be allowed in any case. When learning online.1 has proven to be a good choice. the weight-specific learning rates initialized)?4 Definition 5.e.5.j (t − 1) with a constant η ↑ 2. i.j set? g (t − 1)g (t) > 0 ↓ ηi.j (t − 1).5. This may be often well applicable in backpropagation and it is very often even faster than the offline version.3 We are still missing a few date for the weight wi. a clear mathematical motivation. 4 Protipp: since the ηi. so we set ηmin = 10−6 .j (t) by multiplying the old ηi. ηmin and ηmax for ηi. Equally uncritical is ηmax .j to much are learning rates reinforced or get past shallow areas of the error function. g (t − 1)g (t) < 0 η (t − 1) otherwise. for which they recommend.dkriesel. as it will be quickly overridden by the automatic adaptation anyway.
Let us start with η ↓ : If this value is used. by always adding a fraction of the previous change to every new change in weight: (∆p wi.6 Backpropagation has often been extended and altered besides Rprop Backpropagation has often been extended. which is why the canonical choice η ↓ = 0. Here we cannot generalize the principle of binary search and simply use the value 2.j )now = ηop. I would recommend testing the more widespread backpropagation (with both offline and online learning) and the less common Rprop equivalently. Furthermore. not dealt with in this work. from which we do not know where exactly it lies on the skipped track.what prevents us from immediately stopping at the edge of the slope to the plateau? Exactly .e. Many of these extensions can simply be implemented as optional features of backpropagation in order to have a larger scope for testing. So we need to halve the learning rate.j +α·(∆p wi.0. deep networks. we assume it was in the middle of the skipped track.our momentum. 5. a value of η ↑ = 1. For such networks it is crucial to prefer Rprop over the original backpropagation. With backpropagation the momentum term [RHW86b] is responsible for the fact that a kind of moment of inertia (momentum ) is added to every step size (fig.i δp. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .6. 5. which is. Slight changes of this value have not significantly affected the rate of convergence.com SNIPE: In Snipe resilient backpropagation is supported via the method trainResilientBackpropagation of the class NeuralNetwork. learns very slowly at weights wich are far from the output layer. Rprop is very good for deep networks 96 D. as already indicated.5 is being selected. dkriesel. i. With advancing computational capabilities of computers one can observe a more and more widespread distribution of networks that consist of a big number of layers. learning rates shall be increased with caution.1 Adding momentum to learning Let us assume to descent a steep slope on skis . you can also use an additional improvement to resilient propagation. If the value of η ↑ is used.j )previous . Analogous to the procedure of binary search.2 has proven to be promising. 5. where the target object is often skipped as well. Independent of the particular problems. backpropagation and its variants Now we have left only the parameters η ↑ and η ↓ . This fact allowed for setting this value as a constant as well. There are getters and setters for the different parameters of Rprop.Chapter 5 The perceptron. For problems with a smaller number of layers. otherwise the learning rate update will end up consisting almost exclusively of changes in direction. however. we have skipped a minimum. In the following I want to briefly describe some of them. because backprop.13 on the next page).
which is continued successively.6 perbolic tangent as well as with the Fermi on page 37.6 Further variations and extensions to backpropagation Of course. then the previous cycle is identified by (t − 1).12 (Momentum term). and finally lands in the minimum. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 97 . neurons get stuck It is an interesting observation. introduced in section 3.j (t − 1) (5. ∆wi. This results in the fact that it becomes very difficult to move neurons away from the limits of the activation (flat spots ). the effect of inertia can be varied via the prefactor α.46) Figure 5. as already defined by the concept of time.j (t) = ηoi δj + α · ∆wi. who would hardly stop immediately at the edge to the We accelerate on plateaus (avoiding quasi. when referring to the current cycle as (t).1). Despite its nice one-dimensional appearance.9. this notation is only used for a better understanding. the momentum enables the positive effect that our skier swings back and forth several times in a minimum. And now we come to the formal definition of the momentum term: moment of inertia Definition 5.Anguita et al.dkriesel. This problem can be dealt with by modifying the derivative. function the derivative outside of the close proximity of Θ is nearly 0. that success has also been achieved by using deriva5.2.13: We want to execute the gradient α standstill on plateaus) and slow down on craggy surfaces (preventing oscillations). which could extremely extend the learning time. the otherwise very rare error of leaving good minima unfortunately occurs more frequently because of the momentum term – which means that this is again no optimal solution (but we are by now accustomed to this condition). common values are between 0.g. which is called flat spot elimination or – more colloquial – fudging. 0. In the outer regions of it’s (as D. Generally.6 und 0. Moreover. Additionally.2 Flat spot elimination prevents tives defined as constants [Fah88].plateau. The variation of backpropagation by means of the momentum term is defined as follows: descent like a skier crossing a slope. for example by adding a constant (e.com 5.6. A nice neurons from getting stuck example making use of this effect is the fast hyperbolic tangent approximation by It must be pointed out that with the hy.
Of course. those require much more computational ef1 ErrWD = Err + β · (w)2 (5. As a result the tives only rarely improve the estimations. the procedures reduce synaptic weights cannot become infinitely the number of learning epochs. this Damage learning procedure is a second-order procedure. punishment Hessian matrices. too ErrWD keep weights small β prune the network 98 D. but signifi.ple pragmatics.5 Cutting networks down: Pruning and Optimal Brain directly jump to this point. we use further derivatives (i. network is keeping the weights small durThus.5. the second multi-dimensional derivative of the error does not only increase proportionally to function.e.4 Weight decay: Punishment of tive.j .strong as well. than backpropagation. it makes use of a small constant.e.com well approximated and accelerated) deriva. backpropagation and its variants dkriesel.to 0.If we have executed the weight decay long proximated by a parabola (certainly it is enough and notice that for a neuron in not always possible to directly say whether the input layer all successor weights are this is the case).6.3 The second derivative can be used. Thus. Additionally. The factor β controls the dure [Fah88] uses the second derivative of strength of punishment: Values from 0. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .02 are often used here. we can remove the neuron. cay Second order backpropagation also usErrWD ese the second gradient. So in the end these shows weaker fluctuations. 2 w∈W In general. due to these cantly increase the computational effort of small weights. less training cycles are needed but ing learning. since the functions are multidimensional) for higher order meth. The prefactor 1 2 again resulted from simThe quickpropagation learning proce.47) fort. large weights The weight decay according to Paul Werbos [Wer88] is a modification that extends the error by a term punishing large weights. We analytically determine the vertex (i.001 the error propagation and locally under.e. to obtain more precise estimates the actual error but also proportionally to of the correct ∆wi.the square of the weights. 0 or close to 0.6. allowing easier procedures often need more learning time and more controlled learning. Even higher deriva. So the error under weight deAccording to David Parker [Par87].Chapter 5 The perceptron.6. the error function often the individual epochs. As expected. i. this does not work with error surfaces that cannot locally be ap. stands the error function to be a parabola. the lowest point) of the said parabola and 5. 5.This approach is inspired by nature where ods.
Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 99 . we need – as we have already overview of neural networks. but since my aim is to offer an Additionally. as already mentioned.dkriesel. but more are also used Let us begin with the trivial circumstance that a network should have one layer of input neurons and one layer of output neuThere are many other variations of back. it would be useful to consider how to implement such a network. realize this knowledge.7. If a weight is strongly needed to minimize the error. If this is not the case.6. the second term will win. which results in at least two layers.1 Number of layers: Two or three may often do the job. I just want learned during the examination of linear to mention the variations above as a moti. considers the difference between output and teaching input. the other one tries to "press" a weight towards 0. I now advise you to deal 5 Note: We have not indicated the number of neuwith some of the exemplary problems from rons in the hidden layer. to feedforward networks with backpropagamathematically prove that this MLP with tion learning procedures. Neurons which only have zero weights can be pruned again in the end. the first term will win. I only want to describe it briefly: The mean error per output neuron is composed of two competing terms.7 Initial configuration of a multilayer perceptron hence losing this neuron and some weights and thereby reduce the possibility that the network will memorize. as we have seen. hypothetical possibility. Representability means this work.problem by means of a perceptron but also cate this experience in the framework of the learnability. in principle.likely). 5. one hidden neuron layer is already capable We have gotten to know backpropagation of approximating arbitrary functions with 5 and feedforward topology – now we have any accuracy – but it is necessary not to learn how to build a neural network. arable (which is. D. It only to discuss the representability of a is of course impossible to fully communi. This procedure is called pruning.rons. To obtain at least some of that a perceptron can. While one term. Such a method to detect and delete unnecessary weights and neurons is referred to as optimal brain damage [lCDS90]. as usual. if our problem is not linearly sepvation to read on.com 5. we only mentioned the 4.7 Getting started – Initial configuration of a multilayer perceptron After having discussed the backpropagation of error learning procedure and knowing how to train an existing network.separability – at least one hidden layer of neurons. very For some of these extensions it is obvi. ous that they cannot only be applied to It is possible. 5. prop and whole books only about this subject.
Chapter 5 The perceptron. experience shows that two new networks with more neurons until the hidden neuron layers (or three trainable result significantly improves and. by the problem statement) principally corresponds to the number of free parameters For tasks of function approximation it of the problem to be represented. while a linear activation funcor a too imprecise problem representation. GenerThe number of neurons (apart from input ally. a promising way is to try it with one hidden layer at first and if that fails. the activation function is the same for and output layer. The first question to be asked is whether we actually want to use the same acti5.3 Selecting an activation function Another very important parameter for the way of information processing of a neural network is the selection of an activation function. the most useful approach is to initially train with we are also able to teach it.14 on Since we have already discussed the netpage 102) as activation function of the hidwork capacity with respect to memorizing den neurons. the output layer dard solution for the question of how many still processes information. particuweight layers) can be very useful to solve larly. Contrary necessary. since many problems can be affected (bottom-up approach ). The latter is it is clear that our goal is to have as few absolutely necessary so that we do not genfree parameters as possible but as many as erate a limited output intervall. one should consider more layers. 5. to the input layer which uses linear actiBut we also know that there is no stan. 5. where the number of in.7. retry with two layers. because it has 100 D. Only if that fails. One should keep in mind that any additional layer generates additional subminima of the error function in which we can get stuck.com a mapping . The activation function for input neurons is fixed to the identity function. given the increasing calculation power of current computers. only a few neurons and to repeatedly train In this respect. the generalization performance is not a problem.7.but learnability means that neurons should be used. backpropagation and its variants dkriesel. Thus.vation functions as well. has been found reasonable to use the hyperbolic tangent (left part of fig. deep networks with a lot of layers are also used with success. since they do not process information.all hidden neurons as well as for the output put and output neurons is already defined neurons respectively.2 The number of neurons has vation function in the hidden layer and to be tested in the ouput layer – no one prevents us from choosing different functions. All these things considered. However. tion is used in the output. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . represented by a hidden layer but are very difficult to learn.
linear activation functions in the output can also cause huge learning steps and jumping over good minima in the error surface. . 5. The maximum Fermi function (right part of fig.com 5.5] not including 0 or values very close to 0. this network represents a function B8 → B8 . i8 . randomly chosen values The initialization of weights is not as trivial as one might think. . But generally. The simple solution of this problem is called symmetry breaking. unless problem and related the network is modified. with the ized randomly (if a synapse initialization is wanted). i2 . they will all change equally during training. The 6 Generally. .8 The 8-3-8 encoding problem and related problems range of random values could be the interval [−0.7. weights are initiallike with the hyperbolic tangent. method setSynapseInitialRange. However. . Thus.8 The 8-3-8 encoding values far from thei threshold value. This can be avoided by setting the learning rate to very small values in the output layer. here a lot of freedom is given for selecting an activation function.4 Weights should be initialized with small. In our MLP we have an input layer with eight neurons i1 . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 101 . which results in 8 training samples. which is the initialization of weights with small random values. the hyperbolic tangent is used in any case. the output interval will be a bit larger. If they are all initialized by the same value. If they are simply initialized with 0. an output layer with eight neurons Ω1 . random initial weights The 8-3-8 encoding problem is a classic among the multilayer perceptron test training problems. If from the start of learning. .5. This random initialization has a nice side effect: Chances are that the average of network inputs is close to 0. pattern recognition is understood as a special case of function approximation with a few discrete output possibilities. Ω8 and one hidden layer with three neurons. UnSNIPE: In Snipe. However. . Now the training task is that an input of a value 1 into the neuron ij should lead to an output of a value 1 from the neuron Ωj (only one neuron should be activated.dkriesel. 0. . problems 5. An unlimited output interval is not essen.allowing for strong learning impulses right tial for pattern recognition tasks6 .14 on absolute weight value of a synapse the following page) it is difficult to learn initialized at random can be set in something far from the threshold value a NeuralNetworkDescriptor using the (where its result is close to 0). Ω2 . threshold values. During the analysis of the trained network we will see that the network with the 3 D. the disadvantage of sigmoid functions is the fact that they hardly learn something for 5. there will be no change in weights at all. . a value that hits (in most activation functions) the region of the greatest derivative.
hidden neurons represents some kind of bidimensionality for encoder problems like nary encoding and that the above mapthe above.g.or an 8-2-8-encoding network? Yes.2 f(x) 0. The original Fermi function is thereby represented by dark colors. The Fermi function was expanded by a temperature parameter. backpropagation and its variants Hyperbolic Tangent 1 0. 5 . for example. Fig. 5.6 0. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . Write tables with all computational parameters of neural networks (e.2 −0. But is it possible to neuron. neuron is compensated by another one is Analogously. Perform the calculations for the four possible inputs of the networks and write down the values of these variables for each input. 5. 5.6 0. ordered ascending by steepness. 10 and 25 .8 1 dkriesel.8 −1 −4 −2 0 x 2 4 0 −4 −2 0 x 2 0.com Fermi Function with Temperature Parameter 4 Figure 5.). does not work.6 −0. our network is a ma.2 0 −0. 102 D.4 0.Chapter 5 The perceptron. 1 2 . But the encoding of the network is far more difficult to understand (fig.15 on the next page) and the training of the networks requires a lot more time.9 on page 84). since the network does not depend on binary encodings: Thus. there is certainly no compensatory improve the efficiency of this procedure? neuron. however.14: As a reminder the illustration of the hyperbolic tangent (left) and the Fermi function (right).8 0. a 1024-91024. activation etc.An 8-1-8 network. network input. Thus. chine in which the input is first encoded since the possibility that the output of one and afterwards decoded again. Do the same for the XOR network (fig. SNIPE: The static method getEncoderSampleLesson in the class TrainingSampleLesson allows for creating simple training sample lessons of arbitrary Exercises Exercise 8. we can train a 1024-10-1024 essential. and if there is only one hidden encoding problem.4 −0. the temperature parameter of the modified Fermi functions 1 1 1 are. ping is possible (assumed training time: ≈ 104 epochs). an 8-2-8 network is sufficient for our problem. even that is possible.4 on page 75 shows a small network for the boolean functions AND and OR. Could there be.4 tanh(x) 0.
−1). (7 + ε. 1. that are linearly separable and characterize them exactly. The illustration shows an exemplary separation of one point. List those that are not linearly sepa- Exercise 10. 3 + ε. 3 − ε. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 103 . 1). 0.4. bias neuron and binary threshold function as activation function divides the two-dimensional space into two regions by means of a straight line g .15: Illustration of the functionality of 8-2-8 network encoding. too. at what value. D. it is possible to find inner activation formations so that each point can be separated from the rest of the points by a straight line. −1]. 2. t) be defined by p = (p1 . Verify if the error 1 Err = Errp = (t − y )2 2 converges and if so. (0. Randomly initalize the weights in the interval [1. p2 . Exercise 11. As you can see. 0. A one-stage perceptron with two input neurons. −1. How does the error curve look like? Let the pattern (p. A simple 2-1 network shall be trained with one single pattern by means of backpropagation of error and η = 0.7) and tΩ = 0. (0 − ε. (7 − ε. 1). The marked points represent the vectors of the inner neuron activation associated to the samples.3. Analytically calculate a set of weight values for such a perceptron so that the following set P of the 6 patterns of the form (p1 . (2. p2 ) = (0. List all boolean functions B3 → B1 . 1).1.8 The 8-3-8 encoding problem and related problems Exercise 9. −2 − ε.dkriesel. tΩ ) with ε 1 is correctly classified. −2.com 5. rable and characterize them exactly. −1). −1)} Figure 5. P ={(0.
5.1). Calculate in a comprehensible way one vector ∆W of all changes in weight by means of the backpropagation of error procedure with η = 1. 0. For all other weights the initial value should be 0.com 104 D. backpropagation and its variants Exercise 12. For all weights with the target Ω the initial value of the weights should be 1. p2 . 0. tΩ ) = (2. Let a 2-2-1 MLP with bias neuron be given and let the pattern be defined by p = (p1 .Chapter 5 The perceptron. What is conspicuous about the changes? dkriesel. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .
neurons. This will define a so far unknown type of neuis inserted into a radial activation rons. Initially. The RBF networks are adding all input values and returning like MLPs . we want to discuss colloquially But in this case. each hidden neuron calculates a norm that mation processing itself and in the compurepresents the distance between the tational rules within the neurons outside input to the network and the so-called of the input layer. they have exactly three and then define some concepts concerning layers. Description of their functions and their learning process. Like perceptrons. the RBF networks are built in layers. in a moment we position of the neuron (center). 105 . Comparison with multilayer perceptrons. As propagation function.universal function approximathe sum. According to Poggio and Girosi [PG89] 6. Output neurons: In an RBF network the Like perceptrons. So. only one single layer of hidden RBF networks. i.Chapter 6 Radial basis functions RBF networks approximate functions by stretching and compressing Gaussian bells and then summing them spatially shifted. they do little more than processing. tors.e. network which was developed considerably later than that of perceptrons. Thus. the networks have a output neurons only contain the idenfeedforward structure and their layers are tity as activation function and one completely linked.1 Components and radial basis function networks (RBF netstructure of an RBF works) are a paradigm of neural networks. the input layer weighted sum as propagation funcagain does not participate in information tion. Hidden neurons are also called RBF neuDespite all things in common: What is the rons (as well as the layer in which difference between RBF networks and perthey are located is referred to as RBF ceptrons? The difference lies in the inforlayer). Here.
This scalar (which. The so.1 on page 73 of the input are unweighted. ||c. pletely linked with the following one. what can be realized tion fact . sented by I . ogy to the perceptrons – it is apparent that the closer the input vector is to the center such a definition can be generalized. A vector of an RBF neuron.2 Information processing of an RBF network RBF output neurons Ω use the weighted sum as propagation function fprop . shortcuts do not exist (fig. Gauß 3 layers. the inner neurons are called raand the input vector y . The connections between RBF Definition 6. the higher is its bias neuron is not used in RBF networks.layer and output layer are weighted. the input.1 on the next page) Definition 6. 6. called RBF neurons h have a propagation function fprop that determines the distance between the center ch of a neuron Therefore.5 (RBF network). the hidden layer scalar.– it is a feedforward topology.2 on page 108). i. 6.Chapter 6 Radial basis functions dkriesel.dial basis neurons because from their defresents the network input. Each layer is comthe activation of the neuron. This distance rep. the set of hidden neurons by Definition 6. They are represented by the symby such a network and what is its purpose. feedforward I. for exam- 106 D.e. RBF neurons put value (fig. Let us go over the RBF network from top to bottom: An RBF network receives the Definition 6. An input by means of the unweighted conRBF network has exactly three layers in nections. and the identity as activation funcNow the question is. Def.through a norm so that the result is a sisting of input neurons.4 (RBF output neuron). but – in analthe RBF neuron is located .inition follows directly that all input vecwork input is sent through a radial basis tors with the same distance from the cenfunction fact which returns the activation ter of a neuron also produce the same outor the output of the neuron. 6. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . The connecinition and representation is identical to tions between input layer and RBF layer the definition 5. Σ HIJK bol ONML . can (also called RBF layer) consisting of RBF only be positive due to the norm) is proneurons and the output layer consisting of cessed by a radial basis function.1 (RBF input neuron). The center ch of an RBF neuron original definition of an RBF network only h is the point in the input space where referred to an output neuron. Then the input vector is sent the following order: The input layer con.com input is linear again c Position in the input space Important! function which calculates and outputs RBF output neurons. by the way. The set of input neurons shall be repreactivation. H. Then the net. O only sums up Definition 6.H and the set of output neurons by O. In general. The ron).2 (Center of an RBF neu.3 (RBF neuron). they only transmit neuron.x|| PQRS are represented by the symbol WVUT .
. which coincide with the names of the MLP neurons: Input neurons are called i. . . h|H | Ω1 .1: An exemplary RBF network with two input neurons.dkriesel. h2 . . . . . H and O. i|I | h1 .x|| sh ||c. hidden neurons are called h and output neurons are called Ω. The associated sets are referred to as I . Ω|O| Figure 6. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 107 . Right of the illustration you can find the names of the neurons.com 6.x|| WVUT PQRS WVUT PQRS WVUT PQRS WVUT PQRS WVUT PQRS h h Gauß g Gauß g Gauß g Gauß m m h h m m h m { Gauß gg gg gg { mm {{ hhhhh m { mmm mmm {{{ gg g g { { h m h m h g g { { h mmm m hh{ gg g gg m { m gg {h {{ h m h mm m gg g { {{ { h m m h h g g { { { m m h h m m g3 g g h { { { h m mm h 3 }{ }{ mm }{ m B @ 3 thhhh @ONML Σ vm Σ vm Σ ONML HIJK HIJK ONML HIJK i1 . .x|| ||c. . . .x|| ||c. The connections to the hidden neurons are not weighted. i2 . D.x|| vll ||c. they only transmit the input.2 Information processing of an RBF network @ABC GFED GFED @ABC l ii ii lh hhh lh y y hhhh ii ii lllyyy h yy h l h l y ii i h l y y ii l hhh h l y y ii h l h h l y y i h l h y y ii ll ii4 hhh y h l h l y y |y 4 | h C @ hhh ||c. Ω2 . . five hidden neurons and three output neurons.
weights. It is apparent of the RBF layer or of the different Gaus. let us take as an example a simThe output values of the different neurons ple 1-4-1 RBF network. . . one can easily ues of the bells are multiplied by those see that any surface can be shaped by drag. and de facto provides different values. and therefore it has Gausand a fourth RBF neuron and therefore sian bells which are finally added within four differently located centers. even On the contrary. c2 . Additionally. the network includes the censpace. We will get to know methods and approches for this later. Each of the output neuron Ω. . . the height of the Gausif the Gaussian bell is the same. ters c1 . 108 D.that we will receive a one-dimensional outsian bells are added within the third layer: put which can be represented as a funcbasically. compressing and removing Gaussian bells and subsequently accumulating them. Here. .weights. . c4 of the four inner neurons Suppose that we have a second.2. the network architecture offers the possibility to freely define or train height and width of the Gaussian bells – due to which the network paradigm becomes even more versatile. Figure 6. h4 . .Chapter 6 Radial basis functions dkriesel. since the individual output vallated in the output layer.com ging. . a third h1 . 6.2: Let ch be the center of an RBF neuron h.1 Information processing in RBF neurons RBF neurons process information by using norms and radial basis functions input → distance → Gaussian bell → sum → output ple by a Gaussian bell (fig. Then the activation function fact h is radially symmetric around ch . Gaussian bells are added here. . 6. in relation to the whole input tion (fig. h2 . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . σ4 which tance from the input to its own center influence the width of the Gaussian bells. Furthermore. the parameters for the superposition of the Gaussian bells are in the weights of the connections between the RBF layer and the output layer. σ2 .possesses four values σ1 . The network also these neurons now measures another dis.4 on the facing page).3 on the next page) . At first. . . 6. . Since sian bell is influenced by the subsequent these values are finally simply accumu.
5 on the following page. In both cases σ = 0.or two-dimensional Gaussian bells. D.2 0 Gaussian in 2D Figure 6. the widths σ1 .4 1.2 0 −0. .8 0.3: Two individual one.6 h(r) 0.com 6.4. . . c2 .6 0. 3. 0. .4 holds and the centers of the Gaussian bells lie in the coordinate origin. The Gaussian bells have different heights.4 0. Their centers c1 . 4.4 −0. 0.4 0. 6. c4 are located at 0.5 1 1.5 −1 −0. .2 1 0.4: Four different Gaussian bells in one-dimensional space generated by means of RBF neurons are added by an output neuron of the RBF network. You can see a two-dimensional example in fig. The distance r to the center (0.8.dkriesel.2 Information processing of an RBF network h(r) Gaussian in 1D 1 0. .6 0. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 109 . widths and positions. 1. σ2 .6 −2 0 2 x 4 6 8 y Figure 6. . 1.2 −0.8 0. 0) is simply calculated according to the Pythagorean theorem: r = x2 + y 2 .2 0 −2 −1.8 0.2. 1. σ4 at 0.5 2 −1 x 0 1 −2 −1 0 y 1 2 1 0. .5 0 r 0.4 −2 0.
σ3 = 0.5 0.25 −0. −1.4. widths σ and centers c = (x. The heights w. 0).x|| WVUT PQRS WVUT PQRS WVUT PQRS Gauß e Gauß m m Gauß ee mmm }} m e } m e }} mmm eee }} mmmmm } ee @ 2 } ~ }mmm Σ vm ONML HIJK Sum of the 4 Gaussians 2 1.5).5 −1 −2 −1 x 0 1 −2 −1 0 y 1 Gaussian 4 2 1.com h(r) Gaussian 2 2 1.5 −1 −0.5 2 Figure 6. c4 = (−2.5 −1 −2 −1 x 0 1 −2 −1 0 y 1 2 2 ||c. 110 D.75 −1 −2 −1.5 1.5 1 0. σ1 = 0.15. w4 = 0.5.x|| ||c.x|| WVUT PQRS Gauß ||c. c3 = (−0.5 −1 −2 −1 x h(r) 2 0 1 −2 −1 0 1 y 2 h(r) Gaussian 3 2 1.75 0.5 −0.6.5. Once again r = x2 + y 2 applies for the distance.5 1 0.5 1 0.5 0 −0.5: Four different Gaussian bells in two-dimensional space generated by means of RBF neurons are added by an output neuron of the RBF network.5 1 0. c1 = (0.5 −1 −0.5 −1 −2 −1 x 0 1 −2 −1 0 y 1 dkriesel.5 1.4. −1).25 0 −0. c2 = (1.5 0 −0.75 1. w3 = 1. w2 = −1.5 2 −2 −1.5.5 0 −0.15). 0. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .5 1 1. σ4 = 1. y ) are: w1 = 1.Chapter 6 Radial basis functions h(r) Gaussian 1 2 1.x|| ||c.8.5 y 0 1 0.5 0 x 0.25 1 0.2.5 0 −0. σ2 = 0.
this distance has The output y of an RBF output neuron Ω to be passed through the activation func. As we can see. fact |H | with H being the set of hidden neurons.2. Strictly speaking.2 Information processing of an RBF network activation function fact . So I simply use the name fact for all activation functions and regard σ and c as variables that are defined for individual neurons but no directly included in the activation function. as already mentioned. (6. would only yield different factors there. adds them and extracts the root of the sum. . Here.1) (6. first by a normalization factor and then by the connections’ weights. We do not need this factor (especially because for our purpose the integral of the Gaussian bell must not always be 1) and therefore simply leave it out. we have different choices: Often the Euclidian norm is chosen to calculate the distance: rh = ||x − ch || = i∈ I (6.i )2 Remember: The input vector was referred to as x. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 111 . By the way. rh Now that we know the distance rh beprior to the training tween the input vector x and the center ch of the RBF neuron h. But as a result the explanation would be very confusing. From the definition of a norm directly follows that the distance can only be positive. Normally. One solution would be to number the activation functions like fact 1 .Ω results from combining the functions of tion. . fact 2 . Here we use. the Euclidean distance generates the squared differences of all vector components. avoid this factor because we are multiplying anyway with the subsequent weights and consecutive multiplications. however. that contains |P | D. . We can.com 6. functions that are monotonically decreasing over the interval [0. activation functions other than the Gaussian bell are possible.2) (xi − ch. an RBF neuron to a Gaussian bell: fact (rh ) = e −r 2 h 2σ 2 h 6. The reader will certainly notice that in the literature the Gaussian bell is often normalized by a multiplicative factor.Ω · fact (||x − ch ||) . . we hence only use the positive part of the activation function. ∞] are chosen.2 Some analytical thoughts yΩ = (6. the index i runs through the input neurons and thereby through the input vector components and the neuron center components. In two-dimensional space this corresponds to the Pythagorean theorem.4) It is obvious that both the center ch and Suppose that similar to the multilayer perthe width σh can be seen as part of the ceptron we have a set P . and hence the activation functions should not be referred to as fact simultaneously. Since we use a norm to calculate the distance between the input vector and the center of a neuron h.3) h∈H wh.dkriesel.
i. We are looking for the weights wh.Ω · fact (||p − ch ||) .com T =M ·G ⇔ ⇔ ⇔ where M M −1 (6.2. our problem can be seen as a system of equations since the only thing we want to change at the moment are the weights. . . (6. .7) M −1 · T = E · G −1 i. it performs a precise interpolation. . .e.1 Weights can simply be computed as solution of a system of equations Thus. −1 · M · G (6.e. Of course.Chapter 6 Radial basis functions training samples (p. This means. t). This demands a distinction of cases concerning the number of training samples |P | and the number of RBF neurons |H |: |P | = |H |: If the number of RBF neurons equals the number of patterns. the centers c1 . σk . that the network exactly meets the |P | existing nodes after having calculated the weights. Then we obtain |P | functions of the form yΩ = h∈H dkriesel. with this effort we are aiming at letting the output y for all training patterns p converge to the corresponding teaching input t. Mathematically speaking.Ω with |H | weights for one output neuron Ω. M is the |P | × |H | matrix of the outputs of all |H | RBF neurons to |P | samples (remember: |P | = |H |. To calculate such an equation we certainly do not need an RBF network.6) (6. Exact interpolation must not be mistaken for the memorizing ability mentioned with the MLPs: First.9) wh. one function for each training sample. the matrix is squared and we can therefore attempt to invert it). . i.2. . ck and the training samples p including the teaching input t are given. T is the vector of the teaching inputs for all training samples. Thus.5) ·T =M · T = G. Now let us assume that the widths σ1 . we are not talking about the training of RBF T M 6. we have |P | equations. G is the vector of the desired weights and E is a unit matrix with the same size as G. we can simply calculate the weights: In the case of |P | = |H | there is exactly one RBF neuron available per training sample. and therefore we can proceed to the next case.e.8) (6. |P | = |H |. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . the equation can be reduced to a matrix multiplication G E simply calculate weights 112 D. c2 . . σ2 .
In the aforementioned equations 6. |P | > |H |: But most interesting for further discussion is the case if there are significantly more training samples than RBF neurons. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 113 . this case normally does not occur very often. we The problem is that this time we cannot invert the |P | × |H | matrix M because it is not a square matrix (here.11 and the following ones please do not mistake the T in M T (of the transpose of the matrix M ) for the T of the vector of all teaching inputs. we again want to use the generalization capability of the neural network. it can be used similarly in this case1 . Certainly.15) Another reason for the use of the Moore-Penrose pseudo inverse is the fact that it minimizes the squared error (which is our goal): The estimate of the vector G in equation 6.10) networks at the moment. Thus. Second.13) (6. i. |P | = |H | is true).14) (6.15 corresponds to the Gauss-Markov model known from statistics. If we have more training samples than RBF neurons. to solve the system of equations. 1 Particularly. I do not want to go into detail of the reasons for these circumstances and applications of M + . (6. we must try to find a function that approximates our training set P as closely as possible: As with the MLP we try to reduce the sum of the squared error to a minimum. which is used to minimize the squared error. that means |P | > |H |.2 Information processing of an RBF network have to find the solution M of a matrix multiplication T = M · G.com 6. there is a huge variety of solutions which we do not need in such detail. |P | < |H |: The system of equations is under-determined. if we cannot exactly hit the points and therefore cannot just interpolate as in the aforementioned ideal case with |P | = |H |. there are more RBF neurons than training samples.12) (6. |P | < |H |. We get equations that are very similar to those in the case of |P | = |H |: ⇔ ⇔ ⇔ M ·T =M ·M ·G M ·T =E·G M ·T =G + + + T =M ·G + (6. So.e. We can select one set of weights out of many obviously possible ones.they can easily be found in literature for linear algebra. In this case. Here. we cannot assume that every training sample is exactly hit.dkriesel. it could be advantageous for us and might in fact be intended if the network exactly interpolates between the nodes. M + = M −1 is true if M is invertible.11) M+ Although the Moore-Penrose pseudo inverse is not the inverse of a matrix. How do we continue the calculation in the case of |P | > |H |? As above. we have to use the Moore-Penrose pseudo inverse M + which is defined by M + = (M T · M )−1 · M T (6. D.
which generally requires a lot of computational effort. because such extensive computations can be prone to many inaccuracies. whereas the matrix M + . wouldn’t it? M + complex and imprecise inexpensive output dimension for every new output neuron Ω.16) rough or even unrecognizable) of the desired output.2. without any difficulty.2. |P | |H |: You can. Here. What will happen if there are several output neurons.3 Computational effort and accuracy For realistic problems it normally applies that there are considerably more training samples than RBF neurons. i. always stays the same: So it is quite inexpensive – at least concerning the computational complexity – to add more output neurons.2 The generalization on several outputs is trivial and not quite computationally expensive We have found a mathematically exact way to directly calculate the weights. as usual. we could find the terms for the mathematically correct solution on the blackboard (after a very long time).3 Combinations of equation system and gradient strategies are useful for training Analogous to the MLP we perform a gradient descent to find the suitable weights by means of the already well known delta rule. the set of the output neurons Ω? In this case. which leads us to the real training methods – but otherwise it would be boring. but such calculations often seem to be imprecise 6. it does not change much: The additional output neurons have their own set of weights while we do not change the σ and c of the RBF layer.e.2. our Moore-Penrose pseudoinverse is. This means that we also get only approximations of the correct weights (maybe with a lot of accumulated numerical errors) and therefore only an approximation (maybe very (6. no guarantee that the output vector corresponds to the teaching vector. Thus. backpropagation is unnecessary since we only have to train one single retraining delta rule 114 D. i. 6. if you like. in an RBF network it is easy for given σ and c to realize a lot of output neurons since we only have to calculate the individual vector of weights GΩ = M + · TΩ dkriesel.2. with O being. even though the calculation is mathematically correct: Our computers can only provide us with (nonetheless very good) approximations of the pseudo-inverse matrices. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . we should use it nevertheless only as an initial value for our learning process. in spite of numeric stability. Furthermore.Chapter 6 Radial basis functions 6. as we have already indicated.e.com and very time-consuming (matrix inversions require a lot of computational effort). If we have enough computing power to analytically determine a weight vector. |O| > 1. Theoretically. use 106 training samples.
the answer is similar to the answer for the multilayer perceptron: Initially. (6.18) centers c and the widths σ of the Gaussian bells: Here again I explicitly want to mention that it is very popular to divide the training into two phases by analytically computing a set of weights and then refining it by training with the delta rule. fixed selection: Again centers and widths are selected fixedly. Conditional.com 6. this chapter but it can be found in you can be successful by using many methconnection with another network ods. the errors are once again accumubut certainly the most challenging lated and. However. As already indicated. 2 widths of 3 of the distance between the D. Then. topology (section 10. for a more precise approximaone.6.1 It is not always trivial to ing time. one often trains online (faster movement across the error surface).1). Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 115 . but we have previous knowledge about the functions to be approximated and comply with it. So let us now take a look at the possibility to In any case.17) racy of RBF networks can be increased by adapting the widths and positions of the Gaussian bells in the input space to the in which we now insert as follows: problem that needs to be approximated.Ω = η · (tΩ − yΩ ) · fact (||p − ch ||) (6. vary σ and c training in phases There is still the question whether to learn offline or online.Adaptive to the learning process: This is definitely the most elegant variant. similar to the MLPs.Ω = η · δΩ · oh . lution. after having approximated the so. the goal is to cover the invary σ and c.1 Fixed selection and the output layer can be optimized.3 Training of RBF networks weight layer – which requires less comput. in an RBF network not only the weights between the hidden 6.3. There are several methods to deal with the ∆wh. Here.1. Fixed selection: The centers and widths can be selected in a fixed manner and regardless of the training samples – this is what we have assumed until now. A realization of this tion. too.dkriesel.3. determine centers and widths We know that the delta rule is of RBF neurons It is obvious that the approximation accu∆wh. Here. one trains offline in a third learnapproach will not be discussed in ing phase.6. put space as evenly as possible.
7 on the facing page). There are different methods to determine which increases the computational effort clusters in an arbitrarily dimensional set exponentially with the dimension – and is of points. 6.6). does not cause any problems here).use clustering methods to determine them. fixed selection Suppose that our training samples are not evenly distributed across the input space. So this method would allow for every training pattern p to be directly in the center of a neuron (fig. Here it is method the widths are fixedly selected. are statistical factors according to which we should distribute the centers and sigmas (fig. and self-organizing maps are apologize this sloppy formulation.to tendimensional problems in RBF networks are already called "high-dimensional" (an MLP. One neural cluster2 It is apparent that a Gaussian bell is mathematically infinitely wide. two-dimensional input space by applying radial and so it can be determined whether there basis functions. "one third"2 (fig. This is This may seem to be very inelegant. However. It then seems obvious to arrange the centers and sigmas of the RBF neurons by means of the pattern distribution. Generally. 6.3. A more trivial alternative would be to set |H | centers on positions randomly selected from the set of patterns. 6.Chapter 6 Radial basis functions dkriesel.5).1. centers can be selected so that the Gaussian bells overlap by approx. 6.com responsible for the fact that six.2 Conditional. but not yet very elegant but a good solution in the field of function approximation we when time is an issue. the high input dimen. we can only 0.6: Example for an even coverage of a tical techniques such as a cluster analysis. The closer the bells are set the more precise but the more time-consuming the whole thing becomes. We will be introduced to some of them in excursus A. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . for this cannot avoid even coverage. So the training patterns can be analyzed by statisFigure 6. sion requires a great many RBF neurons. for example. therefore I ask the reader to ing method are the so-called ROLFs (section A. useless if the function to be approximated is precisely represented at some positions If we have reason to believe that the set but at other positions the return value is of training samples is clustered. input dimension very expensive 116 D.8 on the next page).
by applying radial basis functions.6. All these methods have nothing to do with the RBF networks themselves but are only used to generate some previous knowledge.dkriesel. of which we have previous knowledge. Using ROLFs. one can also receive indicators for useful radii of the RBF neurons. the centers of the neurons were randomly distributed throughout the training patterns. which can be seen at the single data point down to the left.com 6. This distribution can certainly lead to slightly unrepresentative results. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 117 .1). Therefore we will not discuss them in this chapter but independently in the indicated chapters. Figure 6.7: Example of an uneven coverage of a two-dimensional input space. Another approach is to use the approved methods: We could slightly move the positions of the centers and observe how our error function Err is changing – a gradient descent. also useful in connection with determining the position of RBF neurons (section 10.3 Training of RBF networks Figure 6.8: Example of an uneven coverage of a two-dimensional input space by applying radial basis functions. as already known from the MLPs. Learning vector quantisation (chapter 9) has also provided good results. The widths were fixedly selected. D.
by means of a clustering method) and then extended or reduced. as we already know. we will significantly if the σ are large. we have to exerAnd that is the crucial point: Naturally. Even if mathematics claim P that such methods are promising. only simple mechaerror depends on the values σ . But change a c or a σ .Chapter 6 Radial basis functions dkriesel. this adjustment is made by moving the centers c of the other neurons away from the new neuron and reducing their width σ a bit.neurons are considerably influenced by the new neuron because of the overlapping of tion. A certain number |H | of neurons as well as their centers ch and widths σh are previously selected (e. Of course. ∂ch 6. if we considerably if the distance between them is short. cise care in doing this: IF the σ are small.4 Growing RBF networks automatically adjust the neuron density In growing RBF networks.com In a similar manner we could look how the In the following text.The extension of the network is simple: We replace this maximum error with a new faces. calculated. This method is 118 D. the already exisiting change the appearance of the error func. dient descent. RBF networks generate very craggy er.is sought. RBF neuron. Then the current output vector y of the network is compared to the teaching input t and the weight vector G is improved by means of training. leads to problems with very craggy error sur. For more information.1 Neurons are added to places with large error values Since the derivation of these terms corre. Subsequently. So it is obvious that we will adjust the already existing RBF neurons when adding the new neuron.the vector of the weights G is analytically tion we do not want to discuss it here. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .g. to the derivation of backpropagation we I refer to [Fri94].the neurons will only influence each other ror surfaces because.4. Analogous nisms are sketched. a new neuron can be inserted if necessary.After generating this initial configuration sponds to the derivation of backpropaga. replace error with neuron 6. To put it simply. the number |H | of RBF neurons is not constant. the gra. the Gaussian bells. Then all specific errors Errp concerning the set P of the training samBut experience shows that no convincing ples are calculated and the maximum speresults are obtained by regarding how the cific error error behaves depending on the centers max(Errp ) and sigmas. derive ∂ Err(σh ch ) ∂σh and ∂ Err(σh ch ) .
tions. for neurons |H |max .3 Less important neurons are dimensional functional spaces since deleted the network could very quickly require huge memory storage and computational effort. with the MLP. it is very useful We will compare multilayer perceptrons to previously define a maximum number and RBF networks with respect to different aspects. one single neuron with a higher them. Such problems do not occur Gaussian bell would be appropriate.5 Comparing RBF networks and multilayer perceptrons D. A neuron is. selecting the unimportant for the network if there is ancenters c for RBF networks is (despite other neuron that has a similar function: the introduced approaches) still a maIt often occurs that two Gaussian bells exjor problem. quainted with and extensivley discussed two network paradigms for similar prob. Thus. Therefore we want to compare these 6. Center selection: However.4. 6. Please use any previous actly overlap and at such a position. a Which leads to the question whether it multilayer perceptron would cause is possible to continue learning when this less problems because its number of limit |H |max is reached. We only have with the input dimension. But to develop automated procedures in Output dimension: The advantage of order to find less relevant neurons is highly RBF networks is that the training is problem dependent and we want to leave not much influenced when the output this to the programmer. for example.4. dimension of the network is high.dkriesel.two paradigms and look at their advantages and disadvantages. to look for the "most unimportant" neuron and delete it.2 Limiting the number of neurons delete unimportant neurons Here it is mandatory to see that the network will not grow ad infinitum. Here. a learning procedure With RBF networks and multilayer persuch as backpropagation thereby will ceptrons we have already become acbe very time-consuming. The answer is: neuons does not grow exponentially this would not stop learning.Extrapolation: Advantage as well as disadvantage of RBF networks is the lack lems. for knowledge you have when applying instance. which can happen very fast.com 6.5 Comparing RBF networks and multilayer perceptrons particularly suited for function approxima. Input dimension: We must be careful with RBF networks in high6. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 119 . For an MLP.
but experience shows that MLPs are suitable for that matter). But one part of the output is heavily affected because a Gaussian bell is directly missing.Chapter 6 Radial basis functions of extrapolation capability: An RBF network returns the result 0 far away from the centers of the RBF layer. On the other hand. Thus. Important! 120 D. It will only worsen a little in total. The weights should be analytically determined by means of the Moore-Penrose pseudo inverse. For this. it is no so important if a weight or a neuron is missing. please indicate the used methods together with their complexity. unlike the MLP it cannot be used for extrapolation (whereby we could never know if the extrapolated values of the MLP are reasonable. On the one hand it does not extrapolate. Lesion tolerance: For the output of an MLP. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . The MLPs seem to have a considerably longer tradition and they are working too good to take the effort to read some pages of this work about RBF networks) :-). dkriesel. I recommend to look for such methods (and their complexity). which could be an advantage. Indicate the running time behavior regarding |P | and |O| as precisely as possible. An |I |-|H |-|O| RBF network with fixed widths and centers of the neurons should approximate a target function u. Note: There are methods for matrix multiplications and matrix inversions that are more efficient than the canonical methods. unlike the MLP the network is capable to use this 0 to tell us "I don’t know". t) of the function u are given. If a weight or a neuron is missing in an RBF network then large parts of the output remain practically uninfluenced. |P | training samples of the form (p. In addition to your complexity calculations. Spread: Here the MLP is "advantaged" since RBF networks are used considerably less often – which is not always understood by professionals (at least as far as low-dimensional input spaces are concerned).com Exercises Exercise 13. For better estimations. Let |P | > |H | be true. we can choose between a strong local error for lesion and a weak but global error.
I will briefly introduce two paradigms of recurrent networks and afterwards roughly outline their training. i. Additionally. it is. With a recurrent network an input x that is constant over time may lead to different results: On the one hand. Here. Thus. or at least not until a long time later.1 on the following Recurrent networks in themselves have a page) are returned. The aim of this chapter is larly want to refer to the literature cononly to briefly discuss how recurrences can cerning dynamical systems. recurrent networks are networks that are capable of influencing themselves by means of recurrences.g. the recurrent network will be reduced to an ordinary MLP. it could transform itself into a fixed state and at some time return a fixed output value y . it could never converge.Chapter 7 Recurrent perceptron-like networks Some thoughts about networks with internal states. Generally. such a recurrent network is capable to compute more than the ordinary MLP: If the recurrent weights are set to 0. There are many types of recurrent networks of nearly arbitrary form. we can expect great dynamic that is mathematically dif.If the network does not converge. the network could converge. for example. or attractors (fig. by including the network output in the following computation steps. As a result. On the other hand. so that it can no longer be recognized. possible to check if periodicals work state. state dynamics more capable than MLP Apparently. 121 . 7. e. y constantly changes. the recurrence generates different network-internal states so that different inputs can produce different outputs in the context of the net. That is the reason why I particuextensively.the complete variety of dynamical sysficult to conceive and has to be discussed tems.e. and as a consequence. and nearly all of them are referred to as recurrent neural networks. be structured and how network-internal states can be generated. for the few paradigms introduced here I use the name recurrent multilayer perceptrons.
there are weighted connections between each output neuron and one context neuron. In the originial definition of a Jordan network the context neurons are also recurrent to themselves via a connecting weight λ. 7. In this chapter the related paradigms of recurrent networks according to Jordan and Elman will be introduced. .1 (Context neuron). The stored values are returned to the actual network by means of complete links between the context neurons and the input layer. a context neuron just memorizes an output until it can be processed in the next time step. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . 7. Therefore. A context neuron k receives the output value of another neuron i at a time t and then reenters it into the network at a time (t + 1). Definition 7.1: The Roessler attractor 122 D. . But most applications omit this recurrence since the Jordan network is already very dynamic and difficult to analyze. even without these additional recurrences. There is one context neuron per output neuron (fig. .2 (Jordan network). k|K | . Definition 7. A Jordan network is a multilayer perceptron output neurons are buffered Figure 7.1 Jordan networks A Jordan network [Jor86] is a multilayer perceptron with a set K of so-called context neurons k1 . k2 .2 on the next page).com Further discussions could reveal what will happen if the input of recurrent networks is changed.Chapter 7 Recurrent perceptron-like networks (depends on chapter 5) dkriesel. . In principle.
dkriesel.com
7.2 Elman networks
GFED @ABC @ABC GFED i i1 e ii 2 ee iiii }} eee i }} i i ee e } } i } e } } ii i ee e ii i } }} i i e } } eee Ö e2 { ~}} x v } iiiiii ~} B 2 tii @ABC GFED GFED @ABC @ABC GFED h2 e h1 e iii} h3 i i e ee } i i ee iii }}} ee }} i e i ee ei } }} ii i e } } i i ee } }} iiii ee2 } } 2 ~i ~} B t iii @ABC GFED GFED @ABC Ω2 Ω1 @A
GFED @ABC k2 y
GFED @ABC k1 y
BC
Figure 7.2: Illustration of a Jordan network. The network output is buffered in the context neurons and with the next time step it is entered into the network together with the new input.
with one context neuron per output neuron. The set of context neurons is called K . The context neurons are completely linked toward the input layer of the network.
during the next time step (i.e. again a complete link on the way back). So the complete information processing part1 of the MLP exists a second time as a "context version" – which once again considerably increases dynamics and state variety.
nearly everything is buffered
Compared with Jordan networks the Elman networks often have the advantage to act more purposeful since every layer can The Elman networks (a variation of access its own context. the Jordan networks) [Elm90] have context neurons, too, but one layer of context Definition 7.3 (Elman network). An Elneurons per information processing neu- man network is an MLP with one conron layer (fig. 7.3 on the following page). text neuron per information processing Thus, the outputs of each hidden neuron neuron. The set of context neurons is or output neuron are led into the associ- called K . This means that there exists one ated context layer (again exactly one con- context layer per information processing
7.2 Elman networks
text neuron per neuron) and from there it is reentered into the complete neuron layer
1 Remember: The input layer does not process information.
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
123
Chapter 7 Recurrent perceptron-like networks (depends on chapter 5)
dkriesel.com
GFED @ABC @ABC GFED i1 d i ii 2 dd iiii ~~~ dddd i ~~ i d i ~ i diii dd ~ ~ d d iid ~~ ~~ ~~ iiiiiii ddd ~~ ddd ~ ~ zw v i ~~ ~ 2 ~ v u i B 2 i t tu i @ABC GFED @ABC GFED @ABC GFED h2 d h h1 d 3 i i dd dd ~ iiii ~~ ~~~ dd iiiiii dd ~ ~ dd dd iiii ~~ ~~ i i d dd ~ ~ i i ~ ii d1 wv ~ ~ 1 i ~ B t u iii GFED @ABC GFED @ABC Ω1 Ω2 S
ONML HIJK R kh1 S ONML HIJK kΩ
1
ONML HIJK kh
2
S
ONML HIJK kh
3
S
ONML HIJK kΩ
2
Figure 7.3: Illustration of an Elman network. The entire information processing part of the network exists, in a way, twice. The output of each neuron (except for the output of the input neurons) is buffered and reentered into the associated layer. For the reason of clarity I named the context neurons on the basis of their models in the actual network, but it is not mandatory to do so.
neuron layer with exactly the same num- 7.3 Training recurrent ber of context neurons. Every neuron has networks a weighted connection to exactly one context neuron while the context layer is comIn order to explain the training as comprepletely linked towards its original layer. hensible as possible, we have to agree on some simplifications that do not affect the learning principle itself. Now it is interesting to take a look at the training of recurrent networks since, for instance, ordinary backpropagation of error cannot work on recurrent networks. Once again, the style of the following part is rather informal, which means that I will not use any formal definitions. So for the training let us assume that in the beginning the context neurons are initiated with an input, since otherwise they would have an undefined input (this is no simplification but reality). Furthermore, we use a Jordan network without a hidden neuron layer for our training attempts so that the output neu-
124
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
dkriesel.com rons can directly provide input. This approach is a strong simplification because generally more complicated networks are used. But this does not change the learning principle.
7.3 Training recurrent networks
but forward-oriented network without recurrences. This enables training a recurrent network with any training strategy developed for non-recurrent ones. Here, the input is entered as teaching input into every "copy" of the input neurons. This can be done for a discrete number of time steps. These training paradigms are called 7.3.1 Unfolding in time unfolding in time [MP69]. After the unfolding a training by means of backpropaRemember our actual learning procedure gation of error is possible. for MLPs, the backpropagation of error, which backpropagates the delta values. But obviously, for one weight wi,j sevSo, in case of recurrent networks the eral changing values ∆wi,j are received, delta values would backpropagate cycli- which can be treated differently: accumucally through the network again and again, lation, averaging etc. A simple accumuwhich makes the training more difficult. lation could possibly result in enormous On the one hand we cannot know which changes per weight if all changes have the of the many generated delta values for a same sign. Hence, also the average is not weight should be selected for training, i.e. to be underestimated. We could also introwhich values are useful. On the other hand duce a discounting factor, which weakens we cannot definitely know when learning the influence of ∆wi,j of the past. should be stopped. The advantage of re- Unfolding in time is particularly useful if current networks are great state dynamics we receive the impression that the closer within the network; the disadvantage of past is more important for the network recurrent networks is that these dynamics than the one being further away. The are also granted to the training and there- reason for this is that backpropagation fore make it difficult. has only little influence in the layers farOne learning approach would be the attempt to unfold the temporal states of the network (fig. 7.4 on the next page): Recursions are deleted by putting a similar network above the context neurons, i.e. the context neurons are, as a manner of speaking, the output neurons of the attached network. More generally spoken, we have to backtrack the recurrences and place "‘earlier"’ instances of neurons in the network – thus creating a larger, ther away from the output (remember: the farther we are from the output layer, the smaller the influence of backpropagation).
attach the same network to each context layer
Disadvantages: the training of such an unfolded network will take a long time since a large number of layers could possibly be produced. A problem that is no longer negligible is the limited computational accuracy of ordinary computers, which is exhausted very fast because of so many
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
125
Chapter 7 Recurrent perceptron-like networks (depends on chapter 5)
dkriesel.com
GFED @ABC @ABC GFED @ABC GFED @ABC GFED @ABC GFED i1 y i i y 3 2 y i dd i n ky 2 n} ky 1 iii ee n n n n yyy i n n e dd }iiii nn }i yyy eee nnni} } i nn i nn d yyy d i n i d e } nnn n i n n i e } yyydd i n n i n } n e2 i i i } ~n y9 1 n i in w nn wi tn B 9 GFED @ABC GFED @ABC Ω1 Ω2 @A BC
. . .
. . .
. . .
. . .
. . .
()*+c ()*+ /.-, ()*+ /.-, ()*+ /.-, ()*+g /.-, o o/.-, j j g o oj cc jjjj o o gg o o jj ooo cc ooo j g j g o j c o g o ooo c o jjj g j o o j c g o j @ 3 wo j o o 1 j o w @ B ()*+ /.-, ()*+ /.-, ()*+g /.-, ()*+ /.-, ()*+tj j/.-, n j j n gg pp jjjj hh n p h n p h n ggg hh jj ppp nn jj j nn h g n pppp h jjj n j g h n j p j n g3 " # ! h3 j n j j wppp j vn @ GFED tjn B @GFED @ABC GFED @ABC GFED @ABC GFED @ABC @ABC i i i1 y k k y 2 3 y 1 2 i dd ee ii nn nn} iiii yyy ee dd }iii nnnn nnn}i n yyy n n d e } i i nnn d } yyy ee nnnn ii dd n e }}nnnn yyy iiii n n i d } e i i n n i 1 } ~n y9 B 9 2 ii n wi w n tn @ABC GFED @ABC GFED Ω2 Ω1
Figure 7.4: Illustration of the unfolding in time with a small exemplary recurrent MLP. Top: The recurrent MLP. Bottom: The unfolded network. For reasons of clarity, I only added names to the lowest part of the unfolded network. Dotted arrows leading into the network mark the inputs. Dotted arrows leading out of the network mark the outputs. Each "network copy" represents a time step of the network with the most recent time step being at the bottom.
126
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
especially with recurrent networks. so that this limit is reached). One reason for this is that they are not only unrestricted with respect to recurrences but they also have other advantages when the mutation mechanisms D. Disadvantage: with Elman networks a teaching input for non-output-neurons is not given. with several levels of context neurons this procedure could produce very large networks to be trained. 7.2 Teacher forcing Other procedures are the equivalent teacher forcing and open loop learning. 7. for example.3 Training recurrent networks are chosen suitably: So. So. With ordinary MLPs. They detach the recurrence during the learning process: We simply pretend that the recurrence does not exist and apply the teaching input to the context neurons during the training. however. evolutionary strategies are less popular since they certainly need a lot more time than a directed learning procedure such as backpropagation.4 Training with evolution Due to the already long lasting training time. teaching input applied at context neurons 7.3 Recurrent backpropagation Another popular procedure without limited time horizon is the recurrent backpropagation using methods of differential calculus to solve the problem [Pin87].3. backpropagation becomes possible. too. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 127 . evolutionary algorithms have proved to be of value. the smaller the influence of backpropagation. neurons and weights can be adjusted and the network topology can be optimized (of course the result of learning is not necessarily a Jordan or Elman network).dkriesel. 7.com nested computations (the farther we are from the output layer. Furthermore.3.3.
.
8. each particle applies a force to any other particle so that all particles adjust their movements in the energetically most favorable way.8. This natural mechanism is copied to adjust noisy inputs in order to match their real models. sists of a set K of completely linked neuall particles or neurons rotate and thereby rons with binary activation (since we only K 129 . a Hopfield network conthis state is known as activation. Hopfield and his physically motivated networks have contributed a lot to the renaissance of neural networks. encourage each other to continue this rotation. Thus.1 Hopfield networks are inspired by particles in a magnetic field The idea for the Hopfield networks originated from the behavior of particles in a magnetic field: Every particle "communi.Chapter 8 Hopfield networks In a magnetic field. all cates" (by means of magnetic forces) with neurons influence each every other particle (completely linked) other symmetrically with each particle trying to reach an energetically favorable state (i.2 In a hopfield network. Another supervised learning example of the wide range of neural networks was developed by John Hopfield: the socalled Hopfield networks [Hop82]. As a manner of speaking. we will recognize that the developed Hopfield network shows considerable dynamics. Hopfield had the idea to use the "spin" of the particles to process information: Why not letting the particles search minima on arbitrary functions? Even if we only use two of those spins. our neural network is a cloud of particles Based on the fact that the particles automatically detect the minima of the energy function. a minimum of the energy function ). i.e.e. As for the neurons Briefly speaking. a binary activation.
G ?>=< o GRS ?>=< ↓ ↑ ` jo i d↑ d `` kkk¢ k `` ¢ k k `` kkk ¢ ¢¢ `` ¢ ``kk ¢ ¢ `` ¢ kkkk `` ¢¢ k k `` ¢¢¢ kk ¢ k `0 Т¢ 0 Т G A ?>=< ukkkk 89:.1 (Hopfield network). Thus.Chapter 8 Hopfield networks 89:. 8. 8. we have binary string y ∈ {−1. ples) on its energy surface. o ↓ ↑ i kTG S ?>=< ¢d y ```kkkkkk¢¢d y ``` ¢ `` kkkk ¢¢ `` ¢ `` ` ¢¢ ¢ kkk k ¢ ¢ k k ` ``` `0 Т¢¢ ¢¢kkkkk Т A 0 k uk 89:.1: Illustration of an exemplary Hop. The activation function of the neurons is the binary threshold function with outputs ∈ {1. −1}. thing into the |K | neurons. i. i. matrix that has zeros on its diagonal alAdditionally. The arrows ↑ and ↓ mark the {−1. 89:.e. it will stand still. Thus.be understood as a binary string z ∈ field network.2 (State of a Hopfield network). binary "spin". It can be proven that a Hopfield network with a symmetric weight changing their state. a set of |K | particles.e. which means that a Hopfield network simply includes a set of neurons. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . Thus. the state of the network can Figure 8. The state of the network consists of the activation states of all neurons. ?>=< 89:. A Hopfield network consists of a set K of completely linked neurons without direct recurrences. Due to the completely linked neurons the layers cannot be separated.state string of the network that has found a minimum. use two spins). i. 1}|K | . namely the to think about how we can input some. that is in a state is automatically looking for a minimum.2. at some point the fact that we do not know any input. Then the output is a output or hidden neurons. Then the network is looking for the minimum to be taken (which we have previThe complete link provides a full square ously defined by the input of training sammatrix of weights between the neurons. the state of |K | neurons with two possible states ∈ {−1. we But when do we know that the minimum will soon recognize according to which has been found? This is simple. 89:. 1}|K | that initializes the neurons. Definition 8. Furthermore.1 Input and output of a Hopfield network are represented by neuron states completely linked set of neurons We have learned that a network. The meaning of the weights will be discussed in the following.com Definition 8. 1}|K | . ?>=< ↑ ↓ o dkriesel. 1} can be described by a string x ∈ {−1. with the weights being symmetric between the individual neurons and without any neuron being directly connected to itself (fig. ?>=< 89:.e. 1}|K | . input and output = network states always converges 130 D. An input pattern of a Hopfield network is exactly such a state: A binary string x ∈ {−1. too: when rules the neurons are spinning. the complete link leads to ways converges [CG88].1). are the network stops.
the output is the binary string y ∈ {−1. The in each time step.2. rons k occurs according to the scheme from −1 to 1 or vice versa. j ∈K Thus. Colloquially speaking: a neuron k calholds: culates the sum of wj. If the neuron i is in work (time t) results from the state of the state 1 and the neuron j is in state network at the previous time t − 1.k is pushed.j is negative.j is positive.neurons j . Another difference between Hopfield networks and other already known network topologies is the asynchronous update : A neuron k is randomly chosen every time. Depending on the sign of the sum the neuron takes state 1 or −1.1) xk (t) = fact other neurons and the associated weights. After the convergence of the network. a high positive weight will advise sum is the direction into which the neuron the two neurons that it is energeti. the harder the net. The weights as a whole apparently take Definition 8. the other neurons Once a network has been trained and initialized with some starting state.com 8. If wi. network. where the function fact weights can be positive.dkriesel. its behavior will be analoguous only that i and j are urged to be different.j be(fig. negative.k · xj (t − 1). for a weight wi. cally more favorable to be equal. their direction. We now want to discuss {−1. generally is the binary threshold function Colloquially speaking. the new state of the network will try.Zero weights lead to the two involved neurons not influencing each other.e.2 Significance of weights D. which then recalculates the activation. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 131 . the We have already said that the neurons change of state x of the individual neuk change their states. 1}|K | that initializes the state of the how the neurons follow this way. i. Thus. This −1. tents of the weight matrix and the rules for the state change of the neurons.3 (Input and output of the way from the current state of the neta Hopfield network).2 Structure and functionality Now let us take a closer look at the con. These spins oc cur dependent on the current states of the wj.2 on the next page) with threshold tween two neurons i and j the following 0. which If wi. A neuron i in state −1 would try to urge a neuron j into state 1.8. the weights are capable to control the complete change of the network. 8. it will try to force the indicates how strong and into which directwo neurons to become equal – the tion the neuron k is forced by the other larger they are.3 A neuron changes its state according to the influence of work state. 1}|K | generated from the new net. The input of a work towards the next minimum of the enHopfield network is binary string x ∈ ergy function. or 0.2.k · xj (t − 1) (8. 8.
we use a set P of training patterns p ∈ {1. one time step indicates Unlike many other network paradigms.j one after another. −1}|K | . The change of state of the neurons occurs asynchronously with the neuron to be updated being randomly chosen and the new state being generated by means of this rule: Figure 8.5 −1 −4 −2 0 x 2 4 8.2) This results in the weight matrix W .work by means of a training pattern and rons and force the entire network towards then process weights wi. the training of a Hopfield network is done by training each training pattern exactly once using the rule described in the following (Single Shot Learning ). so that at an function.k · xj (t − 1) . but we will understand the whole purpose later. The purpose is that the network work is often much easier to implement: shall automatically take the closest minThe neurons are simply processed one af.function.e. Heaviside Function 1 0. For ter the other and their activations are re.4 (Change in the state of a Hopfield network). changed neurons immediately influences the network. 132 D.imum when the input is presented. i. ColNow that we know how the weights influ. the new activation of the previously energy surface. do not look for the minima of an unknown Regardless of the aforementioned random error function but define minima on such a selection of the neuron.now this seems unusual.5 f(x) 0 −0. calculated until no more changes occur. we the change of a single neuron.2: Illustration of the binary threshold mentioned energy surface. pi · pj (8. representing the minima of our Thus. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . where pi and pj are the states of the neurons i and j under p ∈ P : wi. Definition 8.3 The weight matrix is generated directly out of the training patterns The aim is to generate minima on the random neuron calculates new activation As with many other network paradigms. input the network can converge to them.j = p∈P xk (t) = fact j ∈J wj. then there is the question of how to teach the weights to force the network towards a certain minimum.loquially speaking: We initialize the netence the changes in the states of the neu.Chapter 8 Hopfield networks dkriesel.com a minimum. a Hopfield net. Roughly speaking.
Afterwards. already p.3) also works with inputs that are close to a which in turn only applies to orthogo. letters or other characters in the field networks).5 (Learning rule for Hop. An autoassociator a exactly shows the aforementioned behavior: Firstly. this |P |MAX ≈ 0. For each of these weights we verify: Are the neurons i. this high value tells the neurons: 8. This was shown by precise (and time-consuming) mathematical anal. stored information will be destroyed. Here. Colloquially speaking. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 133 .139 · |K |. Thus. in the second case we add −1. the network will be able to of the weight matrix W are defined by a correctly recognize deformed or noisy letsingle processing of the learning rule ters with high probability (fig. exactly this known pattern is returned. At an input x the network will converge to the stored pattern that is closest to the input p. above. which we do not want to specify case. The individual elements form of pixels.j = pi · pj .4 Autoassociation and "Often. The primary fields of application of Hopwhere the diagonal of the matrix is covered field networks are pattern recognition with zeros.3 on the following page). such as the zip p∈P network restores damaged inputs D.139 · |K | training samples can be trained and at the same time maintain their function. nal patterns. the autoassociator is. the number of the maxia(p) = p. Finally. no more than |P |MAX ≈ and pattern completion.dkriesel.pattern: a(p + ε) = p. a Unfortunately. (8. j n the same state or do the states vary? In the first case we add 1 to the weight. it is energetically favorable to hold traditional application the same state". Secp is limited to ondly. namely in the state now. wi. the values of the weights use. If more patterns are entered. like those mentioned Due to this training we can store a certain fixed number of patterns p in the weight matrix. in a stable state.4 Autoassociation and traditional application 0. when a known pattern p is entered. are called autoassociators. in any yses. If the set of patterns P consists of. for exDefinition 8. Now we know the functionality of Hopfield This we repeat for each training pattern networks but nothing about their practical p ∈ P . wi. and that is the practical use. mum storable and reconstructible patterns with a being the associative mapping. The same applies to negative weights.com 8. Hopfield networks.ample. 8.j are high when i and j corresponded with many training patterns.
but rather tures has 10 × 12 = 120 binary pixels. Another variant is a dynamic energy surface: Here. the appearance of the energy surface depends on the current state and we receive a heteroassociator instead of an autoassociator. Today Hopfield networks are virtually no longer used.Chapter 8 Hopfield networks dkriesel. 8.5 Heteroassociation and analogies to neural data storage So far we have been introduced to Hopfield networks that converge from an arbitrary input into the closest minimum of a static energy surface.com code recognition on letters in the eighties. h 134 D. they have not become established in practice. onto another one. But soon the Hopfield networks were replaced by other systems in most of their fields of application. h is the heteroasso- a(p + ε) = p ciative mapping. neuron.is no longer true.3: Illustration of the convergence of an exemplary Hopfield network. for example by OCR systems in the field of letter recognition. In the Hopfield network each pixel corresponds to one h(p + ε) = q. the lower shows the convergence of a heavily noisy 3 to the corresponding training which means that a pattern is mapped sample. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . The upper illustration shows the training samples. For a heteroassociator Figure 8. Such heteroassociations are achieved by means of an asymmetric weight matrix V . Each of the pic.
The associative rule provokes that the network stabilizes a pattern. For two training samples p being predecessor and q being h(p + ε) = q successor of a heteroassociative transition h(q + ε) = r the weights of the heteroassociative matrix h(r + ε) = s V result from the learning rule .5 Heteroassociation and analogies to neural data storage Heteroassociations connected in series of Definition 8. Additionally.com 8. .heteroassociative matrix V but also by the already known autoassociative matrix erated from p: W. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 135 . remains D. h(z + ε) = p p. the neuron adaptation rule is changed so that competing terms are generated: One term autoassociating an existing pattern and one term trying to convert the very same pattern into its successor. p. vi. pletely accepted: Before a pattern is entirely completed. . since after having reached the heteroassociations last state z . .p=q with several heteroassociations being introduced into the network by a simple addiwhereby a single pattern is never com. as always.2 Stabilizing the never stop.dkriesel.q ∈P.5.q ∈P. The neuron states are. We generate the matrix V by means of elements v very similar to the autoassociative matrix with p being (per transition) This problem can be avoided by not only the training sample before the transition influencing the network by means of the and q being the training sample to be gen. .1 Generating the erated but that the next pattern is already heteroassociative matrix beginning before the generation of the previous pattern is finished. it would proceed to the first state p again.j = p i qj (8. → z → p. adapted during operation.j = p i qj . the heteroassociation already tries to generate the successor of this pattern. Additionally. the network would 8.p=q can provoke a fast cycle of states V v q netword is instable while changing states The diagonal of the matrix is again filled with zeros.tion. whereby the said limitation exists here. We have already mentioned the problem that the patterns are not completely gen8.5. Several transitions can be introduced into the matrix by a simple addition.6 (Learning rule for the hetthe form eroassociative matrix). too.4) p → q → r → s → . vi.
for example. you gener.6 Continuous Hopfield networks So far. ∆t stable change in states Here. But Hopfield also described a version of his networks with continuous activations [Hop84]. which realizes much by means of elling salesman problem [HT85].4 on the next page). twenty steps. but the place at which one memorized it the last time is perfectly known. 8. to recite the alphabet.k xk (t − ∆t) heteroassociation Another example is the phenomenon that one cannot remember a situation. during which the individual states are stable for a short while. If one returns to this place. we only have discussed Hopfield networks with binary activations. 8. the forgotten situation often comes back to mind. But ally will manage this better than (please today there are faster algorithms for hantry it immediately) to answer the follow.com Which letter in the alphabet follows the letter P ? (8. the network is stable for symmetric From a biological point of view the transi. the activation is no longer calculated by the binary threshold function but by the Fermi function with temperature parameters (fig.dling this problem and therefore the Hopfield network is no longer used here. 8. If ∆t is set to. Accordstate chains: When I would ask you. which we want to cover at least briefly: continuous Hopfield networks. the influence of the matrix V to be delayed. that continuous Hopthe Hopfield modell will achieve an ap. ing question: 136 D. dear ing to some verification trials [Zel94] this reader. and only after that it will work against it. then the asymmetric weight matrix will realize any change in the network only twenty steps later so that it initially works with the autoassociative matrix (since it still perceives the predecessor pattern of the current one). xi (t + 1) = j ∈K autoassociation dkriesel.statement can’t be kept up any more. is highly motivated: At least in the beginning of the nineties it was assumed that Hopfield also stated. Here.5) fact wi. the value ∆t causes. The result is a change in state. tion of stable states into other stable states too. goes on to the next pattern.Chapter 8 Hopfield networks there for a while.field networks can be applied to find acproximation of the state dynamics in the ceptable solutions for the NP-hard travbrain. descriptively speaking. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .3 Biological motivation of heterassociation Here.j xj (t) + k ∈K vi.weight matrices with zeros on the diagonal. since it only refers to a network being ∆t versions behind.5. and so on.
Compute the weights wi. −1.4: The already known Fermi function with different temperature parameter variations. 1. 1). −1. Exercises Exercise 14.com 8. −1). Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 137 .6 f(x) 0. (1. 1. −1. D. (−1.8 0.2 0 −4 −2 0 x 2 4 Figure 8.4 0. −1.j for a Hopfield network using the training set P ={(−1.dkriesel. −1. −1. 1)}. Indicate the storage requirements for a Hopfield network with |K | = 1000 neurons when the weights wi.6 Continuous Hopfield networks Fermi Function with Temperature Parameter 1 0. 1.j shall be stored as integers. −1. −1. Is it possible to limit the value range of the weights in order to save storage space? Exercise 15. −1.
.
. If this has been managed. 139 . These SOMs are described in the next chapter that already belongs to part III of this text. for instance.Chapter 9 Learning vector quantization Learning Vector Quantization is a learning procedure with the aim to represent the vector training sets divided into predefined classes as well as possible by using a few representative vectors. which contains the natural numbers. the sequence of real numbers R. for example. Slowly. The goal of this chapter is rather to analyze the underlying principle. Discrete means. part II of this text is nearing its end – and therefore I want to write a last chapter for this part that will be a smooth transition into the next one: A chapter about the learning vector quantization (abbreviated LVQ ) [Koh89] described by Teuvo Kohonen. since SOMs learn unsupervised. numbers between 1 and 2.1 About quantization In order to explore the learning vector quantization we should at first get a clearer picture of what quantization (which can also be referred to as discretization ) is. is continuous: It does not matter how close two selected numbers are. Everybody knows the sequence of discrete numbers N = {1. 9. 3.}. because the natural numbers do not include. Thus. . which can be characterized as being related to the self organizing feature maps. that this sequence consists of separated elements that are not interconnected. discrete = separated Previously. . I want to announce that there are different variations of LVQ. The elements of our example are exactly such numbers. which will be mentioned but not exactly represented. On the other hand. there will always be a number between them. 2. after the exploration of LVQ I want to bid farewell to supervised learning. vectors which were unkown until then could easily be assigned to one of these classes.
to a class. it could be assigned to the natural number 2. the codebook vectors build a voronoi diagram out of the set. Such separation of data into classes is interesting for many problems for which it is useful to explore only some characteristic representatives instead of the possibly huge set of all vectors – be it because it is Definition 9. Separa.ciently precise.to which class. input space reduced to vector representatives It must be noted that a sequence can be irregularly quantized. all decimal places of the real number 2.which means they may overlap. Furthermore.Chapter 9 Learning vector quantization Quantization means that a continuous space is divided into discrete sections: By deleting. 3). for example. A codebook vector is the representative of exactly those input space vectors lying closest to it. Such a vector is called codebook vector. where the set of these representatives should represent the entire input space as precisely as possible. these numbers will be digitized into the binary system (basis 2). the It is to be emphasized that we have to timeline for a week could be quantized into know in advance how many classes we working days and weekend. each element of the input space should be assigned to a vector as a representative.com into classes that reflect the input space as well as possible (fig. quantization. i.e. it is imporzation : In case of digitization we always tant that the classes must not be disjoint. Here it is obvious that any other number having a 2 in front of the comma would also be assigned to the natural number 2. Since closest vector wins 140 D. for example. i. If we enter. Thus. have and which training sample belongs A special case of quantization is digiti. 2 would be some kind of representative for all real numbers within the interval [2. Definition 9.71828. some numbers into the computer.e. tinuous space into a number system with respect to a certain basis.1 (Quantization).3 Using codebook vectors: the nearest one is the winner The use of a prepared set of codebook vectors is very simple: For an input vector y the class association is easily decided by considering which codebook vector is the closest – so.1 on the facing page). dkriesel. tions.2 (Digitization). 9.2 LVQ divides the input space into separate areas Now it is almost possible to describe by means of its name what LVQ should enable us to do: A set of representatives should be used to divide an input space 9. too: For instance. which divides the input space into the said discrete areas. Regular 9. talk about regular quantization of a con.less time-consuming or because it is suffition of a continuous space into discrete sec. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .
the × mark the codebook vectors. 9. . A codebook vector is clearly assigned to each class. we also have a set of classes C . we can say that the set of classes |C | contains many codebook vectors C1 .4 Adjusting codebook vectors As we have already indicated. DThe lines represent the class limit. C|C | .com 9. c) and D. Roughly speaking.dkriesel. Additionally. we already know that classes are predefined. it is the aim of the This leads to the structure of the training learning procedure that training samples samples: They are of the form (p.1: BExamples for quantization of a two-dimensional input space. each input vector is asso. too. i. . . 9. Thus. too.4 Adjusting codebook vectors Figure 9. we have a teaching input that tells the learning procedure whether the classification of the input pattern is right or wrong: In other words.e. Thus. We have (since learning is supervised) a set P of |P | training samples.1 The procedure of learning Learning works according to a simple scheme. C2 . tors to reflect the training data as precisely as possible.are used to cause a previously defined numciated to a class. . we have to know in advance the number of classes to be represented or the number of codebook vectors. each codebook vector can clearly be asso.ber of randomly initialized codebook vecciated to a class.4. the LVQ is a supervised learning procedure. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 141 .
Training sample: A training sample p of our training set P is selected and presented. the training sample to a class or a codebook vector. |C |} Ci (t + 1) = Ci (t) + ∆Ci . C|C | and our input p. . their codebook vectors there – and that’s it. . C2 . Distance measurement: We measure the distance ||p − C || between all codebook vectors C1 . . For the class affiliation ∆Ci = η (t) · h(p. Assignment is correct: The winner vector is the codebook vector of the class that includes p.e. Ci ) · (p − Ci ) (9. (9. I only want to briefly discuss the steps of the fundamental LVQ learning procedure: Initialization: We place our set of codebook vectors on random positions in the input space. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . With good reason: From here on. Therefore it moves away from p. the one with into different nuances. which means that it clearly assigns which we now want to break down.2) holds. But the function h(p." But we will see soon that our learning procedure can do a lot more. 142 D. Ci ) is the core of the rule: It implements a distinction of cases. . we could say about learning: ing rate allowing us to differentiate "Why a learning procedure? We calculate between large learning steps and fine the average of all class members and place tuning. the function provides positive values and the codebook vector moves towards p.com therefore contain the training input vector Learning process: The learning process takes place according to the rule p and its class affiliation c. . . Ci ∈ C be defined (called LVQ1. The last factor (p − Ci ) is obviously the direction toward which the codebook vector is moved. . i. We have already seen that the first factor η (t) is a time-dependent learnIntuitively. LVQ2. Assignment is wrong: The winner vector does not represent the class that includes p. LVQ3. .Chapter 9 Learning vector quantization dkriesel. Important! We can see that our definition of the funcWinner: The closest codebook vector tion h was not precise enough.1) c ∈ {1. In this case. dependent of how exactly h and the learning rate should min ||p − Ci ||. 2. the LVQ is divided wins.
etc).5 Connection to neural networks Until now. Now let us take a look at the unsupervised learning networks ! vectors = neurons? D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 143 . in nature it often occurs that in a group one neuron may fire (a winner neuron. I decided to place this brief chapter about learning vector quantization here so that this approach can be continued in the following chapter about self-organizing maps: We will classify further inputs by means of neurons distributed throughout the input space. here: a codebook vector) and. inhibits all other neurons. in spite of the learning process. They are not all based on the same principle described here. we do not know which input belongs to which class. The codebook vectors can be understood as neurons with a fixed position within the input space. similar to RBF networks. Indicate a quantization which equally distributes all vectors H ∈ H in the five-dimensional unit cube H into one of 1024 classes. the question was what LVQ has to do with neural networks. 9. in return.com OLVQ. 9. The differences are. only that this time.5 Connection to neural networks Exercises Exercise 16.dkriesel. and as announced I don’t want to discuss them any further. Additionally. Therefore I don’t give any formal definition regarding the aforementioned learning rule and LVQ. in the strength of the codebook vector movements. for instance.
.
Part III Unsupervised learning network paradigms 145 .
.
the feedforward networks. without a teacher.1 Structure of a organizing feature maps [Koh82.e. SOMs have – like our brain – the network. Unlike the other network paradigms we have already got to know. Koh98].the task to map a high-dimensional input (N dimensions) onto areas in a lowsupervised. i.10. Teuvo Kohonen developed in the Eighties his self.Chapter 10 Self-organizing feature maps A paradigm of unsupervised learning neural networks. it will be less interesting to know how strong a certain muscle is contracted but which muscle is activated. for SOMs it is unnecessary to ask what the neurons calculate. which are increasBased on this principle and exploring ingly used for calculations. variations and neural gas. Biologically. These are. Function. We only ask which neuron is active at the moment. A paradigm of neural networks where the output is the state of Typically. too. no output. Our brain responds to external input by changes in state. its output. for example. learning procedure. but active neuron 147 . which learns completely un. SOMs are considerably more related to biology than. one question will arise: How does our brain store and recall the impressions it receives every day. this is very motivated: If in biology the neurons are connected to certain muscles. Thus. And while already considering this subject we realize that there is no output in this sense at all. the question of how biological neural networks organize themselves. which maps an input space by its fixed topology and thus independently looks for simililarities. In other words: We are not interested in the exact output of the neuron but in knowing which neuron provides output. so to speak. Let me point out that the brain does not have any training samples and therefore no "desired output". How are data stored in the brain? If you take a look at the concepts of biological neural networks mentioned in the introduction. self-organizing map shortly referred to as self-organizing maps or SOMs.
In this special case they only have the same In a one-dimensional grid. ()*+ /. If an input vector is entered.com /. the SOM simply obtains arbitrary many points of the input space. ()*+ /.-. ()*+ /.-. During the input of the points the SOM will try to cover as good as possible the positions on which the points appear by its neurons.-. ()*+ /.-. Irregular topologies are possible.A self-organizing map is a set K of SOM tion capability they are not employed very neurons. ()*+ dkriesel. Similar space would be some kind of honeycomb to the neurons in an RBF network a SOM shape. could be.Chapter 10 Self-organizing feature maps dimensional grid of cells (G dimensions) to draw a map of the high-dimensional space. these facts seem to be a bit con/. other possible array in two-dimensional Definition 10.-.-. input ↓ low-dim. ()*+ /. A two-dimensional grid could be a map and then make it clear by means of square array of neurons (fig. ()*+ /. ()*+ /. Every neuron would have exactly Initially. ()*+ /. ()*+ /. like pearls on a string.1). ()*+ /. ()*+ /. the neurons dimension. 10. for instance. ()*+ /.2 (Self-organizing map). but not very often. possible.-.-. neuron k does not occupy a fixed position too. we will briefly and formally retwo neighbors (except for the two end neu. ()*+ /. and it is recommended to briefly reflect about them.-.some examples.-.-.-. ()*+ /.-. input space and topology Important! the G-dimensional grid on which the neurons are lying and which indicates the neighborhood relationships between the neurons and therefore Even if N = G is true. exoften. map At first. actly that neuron k ∈ K is activated which c K 148 D. To generate this map. k more dimensions and considerably more neighborhood relationships would also be Definition 10.-. This particularly means. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .-.-.-. Above we can see a onedimensional topology.-.-. An. ()*+ /. so to speak. the two spaces are the network topology.-. not equal and have to be distinguished.gard the functionality of a self-organizing rons). but due to their lack of visualiza. There are two spaces in which SOMs are working: Figure 10. ()*+ /. Topolgies with c (a center ) in the input space. /. below a two-dimensional one. ()*+ /. ()*+ /.1: Example topologies of a selfThe N -dimensional input space and organizing map. ()*+ /.-. ()*+ fusing. that every neuron can be assigned to a certain position in the input space.-. ()*+ /. ()*+ /.-.-.-.1 (SOM neuron). ()*+ /. ()*+ high-dim.
These neighborhood relationships are called topology. k the neuron to be adapted (which will be discussed later) and t the timestep. One neuron becomes active. a point p.correspond to those of functionality. which partially Calculation of the distance between ev. D.e. It is defined by the topology function h(i. The dimension of the input space is referred to as N .3 (Topology).e.3 Training functionality of a complete self-organizing map before training. k. namely Like many other neural networks. Basically. i. such neuron i with the shortest Creating an input pattern: A stimulus. is selected from the 1 We will learn soon what a winner neuron is. calculation of ||p − ck ||. Functionality [Training makes the SOM topology cover the input space] The training of a SOM consists of the following steps: is nearly as straightforward as the funcInput of an arbitrary value p of the input tionality described above.com is closest to the input pattern in the input space. since there are many analogies to the training. N input ↓ winner i k G 10. i. The SOM layer is laterally linked in itself so that a winner neuron can be established and inhibit the other neurons. The neurons are interconnected by neighborhood relationships. I think that this explanation of a SOM is not very descriptive and therefore I tried to provide a clearer description of the network structure. Then the input layer (N neurons) forwards all inputs to the SOM layer. But let us regard the very simple 10. the description of SOMs is more formal: Often an input layer is described that is completely linked towards an SOM layer. Definition 10. All other neurons remain inactive. t).3 Training calculated distance to the input. In many literature citations. The output we expect due to the input of a SOM shows which neuron becomes active. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 149 . The training of a SOM is highly influenced by the topology. random neuron centers ck ∈ RN from the input space.2 SOMs always activate the neuron with the least distance to an input pattern ery neuron k and p by means of a Initialization: The network starts with norm. 10. structured into five steps.This paradigm of activity is also called winner-takes-all scheme.dkriesel. where i is the winner neuron1 ist. it is space RN . The dimension of the topology is referred to as G. Now the question is which neuron is activated by which input – and the answer is given by the network itself during training. the SOM has to be trained before it can be used.
The tion: The topology function must be uniabove-mentioned network topology exmodal. last factor shows that the change in In principle. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . t). which wrongly leads the reader to believe that h is a constant. → winner i. i.1 The topology function defines. and the parameter i added to the existing centers. for which the distance to in the following.e. which has the smallest ∆ck = η (t) · h(i. SMore precise definidependent learning rate η (t).4 (SOM learning rule). it must have exactly one maxierts its influence by means of the funcmum. This maximum must be next to the tion h(i. You can see that from several winner neurons one can be selected at will. defined on the grid Additionally. the function shall take a large position of the neurons k is proporvalue if k is the neighbor of the winner neutional to the distance to the input ron or even the winner neuron itself.1) condition c (t + 1) = c (t) + ∆c (t). as usual. itself certainly is 0.Chapter 10 Self-organizing feature maps dkriesel. This problem can easily be solved by not omitting the multiplication dots ·. and pattern p and.e. to a timesmall values if not. which are defined by the neuron k in the network.com training: input. how a learning neuron influences its neighbors Adapting the centers: The neuron cen. The parameter k is the index running where the values ∆ck are simply through all neurons. change in position i and neighbors input space RN . only 1 maximum for the winner 150 D.2) k k k ||p − ci || ≤ ||p − ck || ∀k=i .e. k. distance to p. 2 Note: In many sources this rule is written ηh(p − ck ).ner neuron. to reduce the neighborhood in the course of time. network. The is the index of the winner neuron. (10. The winner neuron and its tance ||p − ck || is determined for every neighbor neurons. for example. i. k. which will be discussed winner neuron i. then adapt their centers according to the rule Winner takes all: The winner neuron i is determined.3. 10. which fulfills the (10. A SOM is trained by presenting an input patentered into the network. k. Now this stimulus is Definition 10. It can be time-dependent (which it often is) – which explains the parameter t. tern and determining the associated winDistance measurement: Then the dis. i.The topology function h is not defined ters are moved within the input space on the input space but on the grid and repaccording to the rule2 resents the neighborhood relationships between the neurons. t) · (p − ck ). the time-dependence enables us. topology function. t) · (p − ck ). the topology of the ∆ck = η (t) · h(i.
for instance. It is unimodal with a maximum close to 0.1 Introduction of common distance is determined (in two-dimensional space distance and topology equivalent to the Pythagoream theorem). ()*+ /.5 (Topology function).-. 10.-. ()*+ /. There are different methods to calculate this distance. It can be any unimodal function that reaches its maximum when i = k gilt. ()*+ /. its width can be changed by applying its parameter σ . ()*+ /. σ example. ()*+ /.-. 10.3.-.3 Training /. ()*+ /.-.-. t) describes the neighborhood relationships in the topology.-. the function h needs some kind of distance notion on the grid because from somewhere it has to know how far i and k are apart from each other on the grid. the Euclidean distance (lower part of fig. ()*+ Figure 10. ()*+ /.-. ()*+ 1 G ?>=< 89:. ()*+ 89:.-.-.o i o 89:. ()*+ /.1. ()*+ /.-.23 qqq q q q xq 89:.2: Example distances of a onedimensional SOM topology (above) and a twodimensional SOM topology (below) between two neurons i and k .-. To simplify matters I required a fixed grid edge length of 1 in both A common distance function would be. Time-dependence is optional. ?>=< /()*+ G . ()*+ /.dkriesel.-.-. ()*+ /. Definition 10.com In order to be able to output large values for the neighbors of i and small values for non-neighbors. ?>=< qV k q y q qqq G/()*+ .-. In the functions upper case we simply count the discrete path length between i and k .-. for cases. the already known Gaussian bell (see fig. On a two-dimensional grid we could apply.-. k /. /.-. ?>=< i o /.3 on page 153).2) or on a one-dimensional grid we could simply use the number of the connections between the neurons i and k (upper part of the same figure). 10. but often used. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 151 . ()*+ /.-.-.-. which can be used to realize the neighborhood being reduced in the course of time: We simply relate the time-dependence to the σ and the result is D. ()*+ 2. k. ()*+ /. The topology function h(i. ()*+ /. In the lower case the Euclidean 10. ()*+ /. Additionally.
At first. i. Other functions that can be used instead of the Gaussian function are. Here. Then our Typical sizes of the target value of a learning rate are two sizes smaller than the initopology function could look like this: tial value. i. a behavior that has already been observed in nature. not the neuron posi. for instance. by means of a time-dependent. referred to as ci and ck .3 on the facing page).3. 10.3) 0. k. In the end of the learning process. the cone function. a decreasing neighborhood size can be realized.com a monotonically decreasing σ (t). the SOMs often work But enough of theory – let us take a look with temporally monotonically decreasing at a SOM in action! learning rates and neighborhood sizes. it could virtually explode. which would be pend on the network topology or the size of the neighborhood.Chapter 10 Self-organizing feature maps dkriesel. It must be noted that must always be true.6 where gi and gk represent the neuron positions on the grid. t) = e − ||gi −ck || 2·σ (t)2 . But this adjustment characteristic is not necessary for the functionality of the map. e.01 < η < 0. forcefully pull the entire map towards a new pattern. This can cause sharply separated map areas – and that is exactly why the Mexican hat function has been suggested by Teuvo Kohonen himself. since otherwise the neurons would constantly miss the current To avoid that the later training phases training sample.e.could be true. (10. The advantage of a decreasing neighborhood size is that in the beginning a moving neuron "pulls along" many neurons in its vicinity. monotonically decreasing σ with the Gaussin bell being used in the topology function. for example. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . the cylinder function or the Mexican hat function (fig. the randomly initialized network can unfold fast and properly in the beginning. let us talk about the learning rate: 10.2 Learning rates and neighborhoods can decrease monotonically over time h·η ≤1 152 D. the Mexican hat function offers a particular biological motivation: Due to its negative digits it rejects some neurons close to the winner neuron.g 2 h(i. it could even be possible that the map would diverge. only a few neurons are influenced at the same time which stiffens the network as a whole but enables a good "fine tuning" of the individual neurons.e. As we have already seen. But this size must also detions in the input space.
5 −3 −2 Mexican Hat Function −1 0 x 1 2 3 Figure 10. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 153 .dkriesel.5 −1 −1.6 0.8 0. cone function. cylinder function and the Mexican hat function suggested by Kohonen as examples for topology functions of a SOM.6 h(r) f(x) 0.5 1 1.3: Gaussian bell.6 f(x) f(x) 0.8 0.8 0.5 1 0.4 0.com 10.4 0..2 0 Cone Function 0 x 2 4 Cylinder Funktion 3.5 −1 −0.5 1 0.4 0.2 0 −2 −1.3 Training Gaussian in 1D 1 1 0.5 0 r 0.5 2 −4 −2 0.5 2 1. D.5 0 −0.2 0 −4 −2 0 x 2 4 3 2.
The arrows mark the movement of the winner neuron and its neighbors towards the training sample p. In the topology. ?>=< 7 ?>=< 89:. Neuron 3 is the winner neuron since it is closest to p. 2 ÕÕ 89:. To illustrate the one-dimensional topology of the network. ?>=< 6 89:.com 89:.4: Illustration of the two-dimensional input space (left) and the one-dimensional topolgy space (right) of a self-organizing map. ?>=< 6 89:. 154 D. ?>=< 4 89:. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . ?>=< 3 GG p 89:. ?>=< 7 ?>=< 89:. ?>=< 2 89:. ?>=< 3 89:. ?>=< 5 89:. 4b bb bb bb b 11 89:.Chapter 10 Self-organizing feature maps dkriesel. ?>=< 1 89:. ?>=< 1 89:. The arrows mark the movement of the winner neuron and its neighbors towards the pattern. ?>=< 5 Figure 10. the neurons 2 and 4 are the neighbors of 3. it is plotted into the input space by the dotted line.
The neighborhood function is also kept simple so that we will be able to mentally The learning rate indicates. and process the three factors from the After the adaptation of the neurons 2. and so back: on. who will learn D. N = 2 is true. (10. Another example of how such a oneLearning direction: Remember that the dimensional SOM can develop in a twoneuron centers ck are vectors in the dimensional input space with uniformly input space. our example SOM should is not specified. i. all in all. k. As already h(i.e. as well as the pattern p. e. we use a two-dimensional closest neighbors (here: 2 and 4) are input space. 3 and 4 the next pattern is applied. i. 10. k. the result is that the winner neuron and its neighbors (here: 2. i.4) mentioned. distributed input patterns in the course of topology specifies. otherw. Let the allowed to learn by returning 0 for grid structure be one-dimensional (G = 1).5. Our topology function h indicates that only the winner neuron and its two In this example. our vector consist of 7 neurons and the learning rate (p − ck ) is multiplied by either 1 or should be η = 0. k = i. Obviously. the factor (p − ck ) indicates the vector of the neuron k to the pattern p. comprehend the network: the strength of learning. Thus.4 Examples for the functionality of SOMs Let us begin with a simple. all other neurons.e.com 10. This is now multiplied by different scalars: 10. ∆ck = η (t) · h(i.5. in our example the input pattern is closest to neuron 3. mentally comprehensible example.dkriesel. Although the center of neuron 7 – seen from the input space – is considerably closer to the input pattern p than neuron 2. η = 0. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 155 . A time-dependence Furthermore. This is exactly the mechanism by We remember the learning rule for which a topology can significantly cover an SOMs input space without having to be related to it by any sort. this is the winning neuron. t) = 1 1 0 k direct neighbor of i. 3 and 4) approximate the pattern p half the way (in the figure marked by arrows). as always. I want to remind that the network topology specifies which neuron is allowed to learn and not its position in the input space. neuron 2 is learning and neuron 7 is not.4 on the preceding page) and enter a training sample p. t) · (p − ck ) Now let us take a look at the abovementioned network with random initialization of the centers (fig. 0.4 Examples Thus.
e.and two-dimensional SOMs with differently shaped input spaces can be seen in figure 10. during training on circularly arranged input patterns it is nearly impossible with a twodimensional squared topology to avoid the exposed neurons in the center of the circle.com End states of one. "knot" in map 10. There are so called exposed neurons – neurons which are located in an area where no input pattern has ever been occurred.4. plex the topology is (or the more neighbors each neuron has.5 on the facing page. i. These are pulled in every direction Figure 10. the SOM does not unfold correctly. since a three-dimensional or a honeycombed two10. But this does not make the one-dimensional topology an optimal topology since it can only find less complex neighborhood relationships than neighborhood size.5 It is possible to adjust the resolution of certain areas in a SOM A remedy for topological defects could We have seen that a SOM is trained by be to increase the initial values for the entering input patterns of the input space 156 D.Chapter 10 Self-organizing feature maps time can be seen in figure 10.7: A topological defect in a twoduring the training so that they finally dimensional SOM. respectively. A topological defect can be described at best by means of the word "knotting". As we can see. A one-dimensional topology generally produces less exposed neurons than a two-dimensional one: For instance. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .7) occurs. 10. During the unfolding of a SOM it could happen that a topological defect (fig.6 on page 158. not every input space can be neatly covered by every network topology.1 Topological defects are dimensional topology could also be generfailures in SOM unfolding ated) the more difficult it is for a randomly initialized map to unfold. because the more coma multi-dimensional one. dkriesel. remain in the center.
D. 5000.dkriesel.5: Behavior of a SOM with one-dimensional topology (G = 1) after the input of 0.2.5 Adjustment of resolution and position-dependent learning rate Figure 10. 70000 and 80000 randomly distributed input patterns p ∈ R2 . During the training η decreased from 1.0 to 0. the σ parameter of the Gauss function decreased from 10. 300. 50000. 500.0 to 0. 100.com 10. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 157 .1.
158 D. 200 neurons were used for the one-dimensional topology.com Figure 10. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .000 input patterns for all maps.Chapter 10 Self-organizing feature maps dkriesel. 10 × 10 neurons for the two-dimensionsal topology and 80.6: End states of one-dimensional (left column) and two-dimensional (right column) SOMs on different input spaces.
10.6 Application For example. similar.based search also works with many other proved corner coverage. 10. within the topology – and that’s why it is so interesting. Then Kohonen created a SOM with G = 2 and used it to map the high-dimensional "paper space" developed by him. i.e. there are many This example shows that the position c of fields of application for self-organizing the neurons in the input space is not significant. too. depending on the occurrence of keywords. It could happen that we want a certain subset U of the input space to be mapped more precise than the other ones. input spaces. 10. This type of brain-like contextogy. It Also. the edge of the SOM could be deformed. it is possible to enter any paper corner with the SOMs). Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 159 . So one tries once more to break down a high-dimensional space into a low-dimensional space (the topology). It is to be noted that the system itself defines what is neighbored. looks if some structures have been developed – et voilà: clearly defined areas for the individual phenomenons are formed. again and again so that the SOM will be aligned with these patterns and map them.ing. since they are bored papers in the topology are interestonly pulled into the center by the topol.dkriesel. a higher learning rate is often used will be likely to discover that the neighfor edge and corner neurons.8 on the next page). into the completely trained SOM and look which neuron in the SOM is activated. the different phonemes of the finnish language have successfully been mapped onto a SOM with a two dimensional discrete grid topology and therefore neighborhoods have been found (a SOM does nothing else than finding neighborhood relationships). Teuvo Kohonen himself made the effort to search many papers mentioning his SOMs in their keywords. In this large input space the individual papers now individual positions. then more neurons will group there while the remaining neurons are sparsely distributed on RN \ U (fig. This problem can easily be solved by means of SOMs: During the training disproportionally many input patterns of the area U are presented to the SOM. If the number of training patterns of U ⊂ RN presented to the SOM exceeds the number of those patterns of the remaining RN \ U . more patterns ↓ higher resolution As you can see in the illustration. SOM finds similarities D. It is rather interesting to see which maps and their variations. This also results in a significantly im.com RN one after another.6 Application of SOMs Regarding the biologically inspired associative data storage. This can be compensated by assigning to the edge of the input space a slightly higher probability of being hit by training patterns (an often applied approach for reaching every Thus.
Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .com Figure 10.8: Training of a SOM with G = 2 on a two-dimensional input space. 160 D. In this circle the neurons are obviously more crowded and the remaining area is covered less dense but in both cases the neurons are still evenly distributed. On the left side.000 training samples and decreasing η (1 → 0. On the right side. The two SOMS were trained by means of 80. for the central circle in the input space.2) as well as decreasing σ (5 → 0.5).Chapter 10 Self-organizing feature maps dkriesel. this chance is more than ten times larger than for the remaining input space (visible in the larger pattern density in the background). the chance to become a training pattern was equal for each coordinate of the input space.
we can look at which of the previous inputs this neuron was also activated – and will immediately discover a group of very similar inputs.or. Virtually. As a result they are used.6.com neuron is activated when an unknown input pattern is entered.e. many neural network simulators offer an additional so-called SOM layer in connection with the simulation of RBF networks.1 SOMs can be used to determine centers for RBF neurons 10. We have already been introduced to the paradigm of the RBF network in chapter 6.7. ate step: work more exactly. Next. 10. Due to the fact that they are deshould be covered with higher resolution rived from the SOMs the learning steps . in connection with RBF networks. i. roughly speakAs we have already seen. to realize a SOM without a grid structo control which areas of the input space ture. As a further useful feature of the combination of RBF networks with SOMs one can use the topology obtained through the SOM: During the final training of a RBF neuron it can be used again.7 Variations of SOMs There are different variations of SOMs Therefore. 10. the topology of a SOM often for different variations of representation is two-dimensional so that it can be easily tasks: visualized.7 Variations to influence neighboring RBF neurons in different ways.dkriesel. it is possible ing. 10. while the input space can be very high-dimensional. The idea of a neural gas is. The more the inputs within the topology are diverging. which has been developed from the difficulty of mapping complex input information that partially only occur in the subspaces of the input space or even change the subspaces (fig. the topology generates a map of the input characteristics – reduced to descriptively few dimensions in relation to the input dimension. are very similar to the SOM learning steps. the less things they have in common. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 161 .9 on the following page). 10. random initialization of ck ∈ Rn selection and presentation of a pattern of the input space p ∈ Rn The neural gas is a variation of the selforganizing maps of Thomas Martinetz [MBS93].1 A neural gas is a SOM without a static topology SOMs arrange themselves exactly towards the positions of the outgoing inputs. for example. on which areas of our function should the but they include an additional intermediRBF network work with more neurons. to select the centers of an RBF network. For this. D.
t).decreasing neighborhood size. dynamic neighborhood The bulk of neurons can become as stiffchanging the centers by means of the ened as a SOM by means of a constantly known rule but with the slightly mod. A disadvantage could be that there is no fixed grid forcing the input space to become regularly covered. of the winner neuron i. t). hL (i. and the number of neighbors is almost arbitrary. The distance within the neighborhood is now represented by the distance within the input space.com Figure 10. The function hL (i. the first neuron in the list L is the neuron that is closest to the winner neuron. which is slightly modified compared with the original function h(i. Thus. too. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . now regards the first elements of the list as the neighborhood 162 D. neuron distance measurement identification of the winner neuron i Intermediate step: generation of a list L of neurons sorted in ascending order by their distance to the winner neuron. k. It does not have a fixed dimension but it can take the ified topology function dimension that is locally needed at the moment. k.Chapter 10 Self-organizing feature maps dkriesel. The direct result is that – similar to the free-floating molecules in a gas – the neighborhood relationships between the neurons can change anytime. t). and therefore wholes can occur in the cover or neurons can be isolated. which can be very advantageous. k.9: A figure filling different subspaces of the actual input space of different positions therefore can hardly be filled by a SOM.
In order to present another variant of the The reader certainly wonders what advanSOMs. start). However.2 A Multi-SOM consists of Again.3 A multi-neural gas consists of several separate neural winner neuron.7 (Multi-SOM). 10. It is unnecessary that the SOMs have the same topology or size. it could be effective to store the list individual SOMs exactly reflect these clusin an ordered data structure right from the ters.6 (Neural gas). Thus. shortly referred to as M-SOM [GKE01b. the neighborhood of a neural gas must initially refer to all neurons since otherwise some outliers of the random initialization may never reach the remaining group. several SOMs can classify complex figure Unlike a SOM. A multiDefinition 10. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 163 . GKE01a. I want to formulate an extended tage is there to use a multi-neural gas since several gases D. Generally. the (here.7 Variations problem: What do we do with input patterns from which we know that they are confined in different (maybe disjoint) areas? Here. the criterion for this decision is the distance between gases the neurosn and the winner neuron in the input space. namic neighborhood function.ous use of M SOMs. Actually. This learning process is analog to that of the SOMs. the idea is to use not only one SOM but several ones: A multi-selforganizing map.com In spite of all practical hints. an M-SOM is just a combination of M SOMs.7. we also have a set of M neural gases: a multi-neural gas [GS06. even if one of the some computational effort could be necesclusters is not represented in every dimensary for the permanent sorting of the list sion of the input space RN . only the neurons beWith a neural gas it is possible to learn a longing to the winner SOM of each trainkind of complex input such as in fig.7. Analogous to the multi-SOM. To forget this is a popular error during the implementation of a neural gas. it is as always the user’s responsibility not to understand this text as a catalog for easy answers but to explore all advantages and disadvantages himself. But means of two SOMs. Definition 10. GS06]. SG06]. This construct behaves analogous to neural gas and M-SOM: 10.9 ing step are adapted. only the neurons of the winner gas several separate SOMs are adapted. With every learning cycle it is decided anew which neurons are the neigborhood neurons of the 10. A neural SOM is nothing more than the simultanegas differs from a SOM by a completely dy. 10. it is easy to on the preceding page since we are not represent two disjoint clusters of data by bound to a fixed-dimensional grid.dkriesel.
this is an attempt to work against the isolation of neurons or the generation of larger wholes in the cover.Chapter 10 Self-organizing feature maps an individual neural gas is already capable to divide into clusters and to work on complex input patterns with changing dimensions. The very imprecise formulation of this exwe only use one single neural gas. Thus. we can directly dkriesel.7.8 (Multi-neural gas). for which multineural gases have been used recently.com Definition 10. two-dimensional rons.because new neurons have to be integrated ready mentioned) the sorting of the in the neighborhood. but in most cases these local sortings are sufficient. a few or only one neuron per gas) behaves analogously to the K-means clustering (for more information on clustering procedures see excursus A). Which criteria did you use for "well" cases of multi-neural gases: One extreme and "best"? case is the ordinary neural gas M = 1. . A lot of computational effort is saved tioned but not discussed. list L could use a lot of computational effort while the sorting of several smaller lists L1 . this is correct. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . 1. i. A multi-neural gas is nothing more than the simultaneous use of M neural gases. Interestercise is intentional. 10. Simple neural gases can also find and cover clusters. ing enough.4 Growing neural gases can add neurons to themselves A growing neural gas is a variation of the aforementioned neural gas to which more and more neurons are added according to certain rules. This is particularly important for clustering tasks.as "well" as possible. . grid shall cover a two-dimensional surface As a result we will only obtain local in. LM is less Exercises time-consuming – even if these lists in total contain the same number of neuExercise 17. less computational effort Here. for this purpose? Now we can choose between two extreme 2. this subject should only be men2. . Basically. the other extreme case (very large M . With several gases. Which grid structure would suit best tell which neuron belongs to which gas. when large original gases are divided To build a growing SOM is more difficult into several smaller ones since (as al. . but a multi-neural gas has two serious advantages over a simple neural gas.e. 1. but now we cannot recognize which neuron belongs to which cluster. A regular. L2 . 164 D. stead of global sortings.
It is the idea of unsupervised learning. Simple binary patterns are entered into the input layer and transferred to the recognition layer while the recognition layer shall return a 1-out-of-|O| encoding. This was followed by a whole family of ART improvements (which we want to discuss briefly.1 Task and structure of an ART network An ART network comprises exactly two layers: the input layer I and the recognition layer O with the input layer being completely linked towards the recognition layer. whose aim is the (initially binary) pattern recognition. the adaptive resonance theory (abbreviated: ART ) without discussing its theory profoundly. Stephen Grossberg and Gail Carpenter published the first version of their ART network [Gro76] in order to alleviate this problem. i. 11.1 on the following page).Chapter 11 Adaptive resonance theory An ART network in its original form shall classify binary input vectors. we want tionally an ART network shall be capable to try to figure out the basic idea of to find new classes. This circumstance is called stability / plasticity dilemma. or more precisely the categorization of patterns into classes. In several sections we have already mentioned that it is difficult to use neural networks for the learning of new information in addition to but without destroying the already existing information. it should follow the winner-takes-all pattern recognition 165 . Simultaneously. too). In 1987. As in the other smaller chapters. But addi- 11. This complete link induces a top-down weight matrix W that contains the weight values of the connections between each neuron in the input layer and each neuron in the recognition layer (fig.e. i.e. to assign them to a 1-out-of-n output. the so far unclassified patterns shall be recognized and assigned to a new class.
Top: the input layer. bottom: the recognition layer.1 Resonance takes place by activities being tossed and turned But there also exists a bottom-up weight matrix V .1. For instance.Chapter 11 Adaptive resonance theory dkriesel. scheme. In this illustration the lateral inhibition of the recognition layer and the control neurons are omitted. 166 D. Now it is obvious that these activities are bounced forth and back again and again. to realize this 1out-of-|O| encoding the principle of lateral inhibition can be used – or in the implementation the most activated neuron can be searched.1: Simplified illustration of the ART network structure. put layer causes an activity within the recognition layer while in turn in the recognition layer every activity causes an activity within the input layer. But we do not want to discuss this theory further since here only the basic principle of the ART network should become explicit. the ART network will achieve a stable state after an input. layers activate one another 11.com @ABC GFED @ABC GFED GFED @ABC @ABC GFED S i i i i yy UY i 3 R UY i 4 R k i yy p pp kk Y i 2R y yy o o k gp g y y k p p p y y yy o o i y 1R p p o o x x x k R R R R y y o o k p p o o y y R x x x p p p x x x k Rp k y k y R y o o o o y k p p p x x x RR RR k p p p x x x y y o o k o o y y k R R R p p p x x x y y o o p p p x x x o o y y k R R R RRR k y y k p p p o o x x x o o y y p p p x x x k R R R k y y o o o o y y R R RR R k p p p x x x k p p p x x x y y k o o oy oy y y R p p k p x x x p k pp p pp R RR RR RR y y x x x o o o o y y k p k o o x x R RRp o o y y p x x x k k R RR R k y y o o o o k y y p p pp x x xxRR k p p p x x x R R k y y o o o o y y k p p R R R RR x x x k p p p x x x y y o o k o o y y k R R R p p p k x x x y y o o o o y y p p p x x x k R R RR R k y y o o k o o y y p p p x x x k p p p x x x R R R k y y o o o o y y k R R RR R p p p x x x k p p p x x x y y o o k o o y y R R R k p p p k x x x y y o o R R RR R p p p o o y y x x x k k y y o o k p p p o o y y x x x R R R k p p p x x x k R R RR R y y o o o o y y k p p p x x xoo k p p p x x x k y y R R R o o o y y k R R R RR p p p k x x x y y o p p p x x x o o y y k k R R R k y y o o p p p x x x o o y y k p p pp x x x R R RR R k y y o o o o k y y p p p x x x k R R R p p x x x k y y o o o o y y k R R RR R p p p k x x x p p p y y o o x x x k o o y y k % % % k p p p y y o o x x x o o y y Õ Õ Õx Õ k 5 5 x x k o o 9 k o o y y { { {x x x k A9 5 % k o o w w k u @ABC GFED GFED @ABC @ABC GFED @ABC GFED @ABC GFED @ABC GFED Ω1 Ω2 Ω3 Ω4 Ω5 Ω6 Figure 11. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . a fact that leads us to resonance. For practical reasons an IF query would suit this task best. Every activity within the in- V In addition to the two mentioned layers. in an ART network also exist a few neurons that exercise control functions such as signal enhancement. I have only mentioned it to explain that in spite of the recurrences. which propagates the activities within the recognition layer back into the input layer.
Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 167 . it could happen that the neudivided to top-down and rons are nearly equally activated or that bottom-up learning several neurons are activated. In an ART network there are different additional control neurons which answer this question according to different mathematical rules and which are responsible for intercepting special cases. enhance input vectors. input is teach. In this case. however.e. on the other hand we train the bottom-up matrix Thus. Then the current pattern is assigned to this output neuron and the weight sets of the new neuron are trained as usual. the system can only moderately distinguish the patterns.e. one of the largest objections to an ART is the fact that an ART network uses a special distinction of 11. Then the weights of the matrix W going towards the output neuron are changed such that the output of the strongest neuron Ω is still enhanced. that has been learning forced into the mechanism of a neural network.3 Adding an output neuron an ART network is Of course.as already mentioned . the advantage of this system is not V (fig.2.1 Pattern input and top-down typical representative of a class looks like learning .2.2 on the next page). for backward weights At the same time. D. winner neuron is amplified Often.which is a significant feature.2 Resonance and bottom-up cases. the network is trained to As already mentioned above. the class affiliation of the input vector to the class of the output neuron Ω becomes enhanced. that the The trick of adaptive resonance theory is not only the configuration of the ART network but also the two-piece learning procedure of the theory: On the one hand we train the top-down matrix W .2. inp. only to divide inputs into classes and to find new classes. network is indecisive. i.com 11. the mechanisms of the control neurons activate a signal that adds a new output neuron.an activation at the output neurons and the strongest neuron wins. The training of the backward weights of the matrix V is a bit tricky: Only the weights of the respective winner neuron are trained towards the input layer and 11. the ART networks have often been extended. When a pattern is entered into the network it causes . The question is when a new neuron is permitted to become active and when it should learn.dkriesel. similar to an IF query.2 The learning process of 11.3 Extensions 11. i. 11. Thus. it can also tell us after the activation of an output neuron what a 11.3 Extensions our current input pattern is used as teaching input.
3 Erweiterungen tional control neurons and layers. ability of ART-2 by adapting additional % Õ | GFED @ABC Ω1 4% Õ GFED @ABC Ω2 0 1 GFED @ABC @ABC GFED GFED @ABC @ABC GFED i2 R i1 pp i3 ` i i4 i pp y R y RR pp pp RR pp R pp R pp RR pp RR pp R ppR% % Õ 4 Õ | @ABC GFED @ABC GFED Ω2 Ω1 ART-2 [CG87] processes ist eine Erweiterung biological such as the chemical auf kontinuierliche Eingaben bietet 1 . ” Abbildung 11. them "ART-n networks".com GFED @ABC i1 GFED @ABC i2 y GFED @ABC i 3 i y GFED @ABC ` i i4 einer IF-Abfrage. Genetwork and that the numbers mark Mitte: Also die Gewichte Top:winnerneuron.B. Let us asdargestellt. processes within the und synapses zus¨ atzlich (in einer ART-2A genannten Erweiterung) Verbesserungen der LerngeApart from the described ones there exist schwindigkeit.com dkriesel. 0 1 GFED @ABC GFED @ABC @ABC GFED @ABC GFED i1 p i i i 2 3 4 ` i y R pp y R i pp RR pp RR pp R pp pp RRR pp R pp RR pp R % % Õ p4 Õ | GFED @ABC @ABC GFED Ω1 Ω2 0 1 1 Durch die h¨ aufigen Erweiterungen der Adaptive Resonance Theory sprechen b¨ ose Zungen bereits von ART-n-Netzen“. indem zus¨ atzliche biologische Vorg¨ ange wie z. die man in den MechaART-2 [CG87] Netzes is extended to continuous nismus eines Neuronalen gepresst hat. inputs and additionally offers (in an ex- tension called ART-2A) enhancements of the learning speed which results in addi11. die chemischen Vorg¨ ange innerhalb der Synapsen adaptiert werden1 .2: Simplified illustration of the Trainings eines ART-Netzes: piecezweigeteilten training of an ART network: The Die trained ¨ 168 trainierten D. Krieselsind – Ein kleiner Uberblick u ¨ber Neuronale Netze (EPSILON-DE) jeweils Gewichte durchgezogen weights are represented by solid lines. ist Ω2the das outputs. Zus¨ atzlich zu den beschriebenen Erweiterungen existieren noch viele mehr.Chapter 11 resonance theory Kapitel 11Adaptive Adaptive Resonance Theory dkriesel. Oben: Wir wir sehen. 168 D. Nehmen wir an. die Middle: So the weights are trained towards 1 Because of the frequent extensions of the adapGewichte vom Gewinnerneuron zur Eingangstive resonance theory wagging tongues already call the winner neuron and (below) the weights of schicht trainiert. We can see that Ωwerden 2 is the winner neuzum Gewinnerneuron hin trainiert und (unten) ron. ein Muster wurde in sume that a eingegeben pattern has entered into the das Netz und been die Zahlen markieren Ausgaben. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . Wie schon eingangs erw¨ ahnt. wurden die the learning ART-3 [CG90] 3 improves ART-Netze vielfach erweitert. ART-3 [CG90] verbessert die Lernf¨ ahigkeit von ART-2. was zus¨ atzliche Kontrollmany other extensions.2: Vereinfachte Darstellung des twoFigure 11. the winner neuron are trained towards the input layer. neurone und Schichten zur Folge hat.
appendices and registers 169 .Part IV Excursi.
.
3. duced. the distances have where these points are situated. sym- metry. 2. A regional and online learnable field models from a point cloud. the is referred to as metric if each of the folsquared distance and the Euclidean lowing criteria applies: distance. dist(x1 . dist(x1 .1 (Metric). x2 ) defined for two objects x1 . Based on such metrics we can de- 171 . Here. a comparatively small set of neurons being representative for the point cloud.e. and the distance beWe briefly want to specify what a metric tween to points may only be 0 if the two is. x1 ). many problems can be traced back to problems in cluster analysis. x2 ) + the triangle Since cluster analysis procedures need a notion of distance between two points. inequality holds. x3 ) ≤ dist(x2 . possibly with a lot of points. the trianDefinition A. i. As already mentioned. comparison of their advantages and disadvantages. for example.)". x2 ) = 0 if and only if x1 = x2 .e. which have already been intro1. a Colloquially speaking. points are equal. it is necessary to research procedures that examine whether groups (so-called clusters) exist within point clouds. x2 ) = dist(x2 . Additionally. dist(x1 . A relation gle inequality must apply. the formation of groups within point clouds is explored. x3 ). Introduction of some procedures. Therefore. dist(x1 . i. dist(x1 . Discussion of an adaptive clustering method based on neural networks. to be symmetrical.Appendix A Excursus: Cluster analysis and regional and online learnable fields In Grimm’s dictionary the extinct German word "Kluster" is described by "was dicht und dick zusammensitzet (a thick and dense group of sth. x2 Metrics are provided by. In static cluster analysis. a metric is a tool metric must be defined on the space for determining distances between points in any space.
Provide data to be examined. the outer ring of the construction in the following illustration will be recog1. The problem is that it is not necessarily known in advance how k can be determined best.the ring with the small inner clusters will be recognized as one cluster. MacQueen [Mac67] is an algorithm that is often used because of its low computation and storage complexity and which is regarded as "inexpensive and good".1 k-means clustering allocates data to a predefined number of clusters k-means clustering according to J. Another problem is that the procedure can become quite instable if the codebook vectors are badly initialized. which is the number of clus.For an illustration see the upper right part Step 2 already shows one of the great questions of the k-means algorithm: The number k of the cluster centers has to be determined in advance. But since this is random.com fine a clustering procedure that uses a metric as distance measure. you will receive quite good results. 2. Now we want to introduce and briefly discuss different clustering procedures. 172 D. Assign each data point to the next 5. 7. nized as many single clusters.of fig. Select k random vectors for the clus. Define k . it is often useful to restart the procedure.Appendix A Excursus: Cluster analysis and regional and online learnable fields dkriesel.2 k-nearest neighboring looks for the k nearest neighbors of each data point The k-nearest neighboring procedure [CH67] connects each data point to the k 1 The name codebook vector was created because closest neighbors. Set codebook vectors to new cluster A. A. Compute cluster centers for all clus6. Then such a group clear. If you are fully aware of those weaknesses. A. The However. centers. complex structures such as "clusoperation sequence of the k-means clusterters in clusters" cannot be recognized. This has the advantage of not requiring much computational effort. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . which often results in a the often used name cluster vector was too undivision of the groups. Continue with 4 until the assignments are no longer changed. number of cluster must be known previously ter centers (also referred to as code. 3. This cannot be done by the algorithm. book vectors). If k ing algorithm is the following: is high. If k is low. ter centers. 4.1 on page 174. codebook vector1 ters.
the storage and computational effort is obviously very high.4 The silhouette coefficient looks for neighbors within determines how accurate the radius ε for each a given clustering is data point As we can see above. For an illustration see the lower left part For an illustration see the lower right part of fig. But this procedure allows a recognition of rings and therefore of "clusters in clusters". Another Furthermore.1. can possibly be a problem. of fig. vantage is that the procedure adaptively i. This can also happen with k -nearest neighboring. With variable cluster and point distances within clusters this the clusters.3 ε-nearest neighboring A. A. (see the two small clusters in the upper right of the illustration).e. But note that there are some special cases: Two separate clusters can easily be connected due to the unfavorable situation of a single data point. Each procethe neighborhood detection does not use a dure described has very specific disadvanfixed number k of neighbors but a radius ε. tages. A. it is not mandatory that the advantage is that the combination of minimal clusters due to a fixed number of links between the points are symmetric. clustering radii around points A. if k is too high. Another ad. The disadvantage is that a large storage and computational effort is required to find the next neighbor (the distances between all data points must be computed and stored). On the other hand. The advantage is that the number of clusters occurs all by itself. which is a disadvantage. swer for clustering problems.fully initialize ε in order to be successful. neighbors is avoided. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 173 . there is no easy anAnother approach of neighboring: here. but it would be more difficult since in this case the number of neighbors per point is limited. A.1. Points are neigbors if they are at most ε apart from each other. which is not An advantage is the symmetric nature of always intentional. In this respect it is useful to have D. smaller than half the smallest distance responds to the distances in and between between two clusters. clustering next points There are some special cases in which the procedure combines data points belonging to different clusters.4 The silhouette coefficient which is the reason for the name epsilonnearest neighboring. Clusters consisting of only one single data point are basically conncted to another cluster. the neighborhood relationships.dkriesel. Here. it is necessary to skillwhich is a clear advantage.com builds a cluster.
this will result in cluster combinations shown in the upper right of the illustration. This procedure will cause difficulties if ε is selected larger than the minimum distance between two clusters (see upper left of the illustration).Appendix A Excursus: Cluster analysis and regional and online learnable fields dkriesel. Top right: k -means clustering. the procedure is not capable to recognize "clusters in clusters" (bottom left of the illustration). which will then be combined. We will use this set to explore the different clustering methods. Bottom right: ε-nearest neighboring. 174 D. As we can see. Long "lines" of points are a problem. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) .com Figure A. If k is selected too high (higher than the number of points in the smallest cluster). Bottom left: k -nearest neighboring. Using this procedure we chose k = 6.1: Top left: our set of points. too: They would be recognized as many small clusters (if k is sufficiently large).
p ∈ c. (A.5 Regional and online learnable fields Apparently. I want to introduce a clustering method based 1 a(p) = dist(p.q=p work [SGE05] which was published in 2005. 1]. In this case. A. 1]. let b(p) be the average disnot be perfect but it eliminates large stantance between our point p and all points dard weaknesses of the known clustering of the next cluster (g represents all clusters methods except for c): b(p) = min g ∈C. i. shortly remax{a(p). which I lowing term provides a value close to 1: want to introduce now. Let c ⊆ P be a cluster within the |P | p∈P point cloud and p be part of this cluster. The set of clusters is called C . This coefficient measures how well the clusters are delimited from each other and indicates if points may be assigned to the wrong clusters. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 175 . q ) (A. A value close to -1 indicates a bad classification of p. As above the total quality of the clusSummary: ter division is expressed by the interval p∈c⊆P [−1. as well as a measure to invariable is referred to as a(p) and defined dicate the quality of an existing arrangeas follows: ment of given data into clusters. applies.4) P . are the regional b(p) − a(p) s(p) = (A.e. Like all the other methods this one may Furthermore. the folThe paradigm of neural networks. As different clustering strategies with difTo calculate the silhouette coefficient.5 Regional and online learnable fields are a neural clustering strategy D. q ) |g | q ∈ g (A. we ferent characteristics have been presented initially need the average distance between now (lots of further material is presented point p and all its cluster neighbors.com a criterion to decide how good our cluster division is. the whole term s(p) can only be within the interval [−1.3) and online learnable fields. A.dkriesel. b(p)} ferred to as ROLFs.1) on an unsupervised learning neural net|c| − 1 q∈c. This in [DHS01]).2) The point p is classified well if the distance to the center of the own cluster is minimal and the distance to the centers of the other clusters is maximal. This possibility is offered by the silhouette coefficient according to [Kau90]. The silhouette coefficient S (P ) results from the average of all values s(p): clustering quality is measureable Let P be a point cloud and p a point in 1 S (P ) = s(p).g =c 1 dist(p.
neurons are added.2) with the multiplier ρ being globally defined and previously specified for all neurons. The parameters of the individual neurons will be discussed later.2 (Regional and online learnable field).5. rameters of a ROLF neuron k are a center ck and σk are locally defined for each neu.1 ROLF neurons feature a position and a radius in the input space Here. The perceptive surface of a ROLF neuron 176 D.3 (ROLF neuron). For this. A. which defines the radius of the perceptive surface surrounding the neuron2 . the regional and online learnable fields are a set K of neurons which try to cover a set of points as well as possible by means of their distribution in the input space. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . Its significance will be discussed later. Furthermore. moved or changed in their size during training if necessary.1 ROLFs try to cover data with neurons Roughly speaking.1. 2 I write "defines" and not "is" because the actual radius is specified by σ · ρ. a position in the input space. A regional and online learnable field (abbreviated ROLF or ROLF network) is a set K of neurons that are trained to cover a certain set in the input space as well as possible. ron. the following has to be observed: It is not necessary for the perceptive surface of the different neurons to be of the same size. A. A neuron covers the part of the input space Definition A.com A.Appendix A Excursus: Cluster analysis and regional and online learnable fields dkriesel. The radius of the perceptive surface is specified by r = ρ · σ (fig.2: Structure of a ROLF neuron. a ROLF neuron k ∈ K has two parameters: Similar to the RBF networks. K network covers point cloud Figure A. The pathat is situated within this radius.4 (Perceptive surface). This particularly means that the neurons are capable to cover surfaces of different sizes. Definition A.5. it has a center ck .e.ck and a radius σk . c σ neuron represents surface But it has yet another parameter: The radius σ . i. the reader will wonder what this multiplicator is used for. Intuitively. Definition A.
5 (Accepting neuron). ρ Definition A. samples online ησ .dkriesel.6 (Adapting a ROLF neuron).e.6) able. For each training sample p entered into the network two cases can occur: ck (t + 1) = ck (t) + ηc (p − ck (t)) σk (t + 1) = σk (t) + ησ (||p − ck (t)|| − σk (t)) Note that here σk is a scalar while ck is a vector in the input space.com A. The radius multiplier ρ > 1 is globally defined and expands the perceptive surface of a neuron k to a multiple of σk .2. Definition A. one can be chosen randomly.7 (Radius multiplier). There is one accepting neuron k for p adapted according to the following rules: or ck (t + 1) = ck (t) + ηc (p − ck (t)) (A. ηc Like many other paradigms of neural networks our ROLF network learns by receiving many training samples p of a training set P . Additionally.5 Regional and online learnable fields k consists of all points within the radius is an accepting neuron k . then the closest neuron will be the accepting one. towards the ρ · σ in the input space. For the accepting A.5. 2. A neuron k accepted by a point p is 1. A. This means that due to the aforementioned learning rule σ cannot only decrease but also increase. then there will be exactly one accepting neuron insofar as the closest neuron is the accepting one. distance between p and ck ) and the center ck towards p. neurons to be able not only to shrink Definition A. The Now we can understand the function of the multiplier ρ: Due to this multiplier the perceptive surface of a neuron includes more than only all points surrounding the neuron in the radius σ . so the neurons can grow D.2 The radius multiplier allows neuron k ck and σk are adapted. The learning is unsupervised. If there are several closest neurons.2. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 177 .5.1 Both positions and radii are adapted throughout learning Adapting existing neurons σk (t + 1) = σk (t) + ησ (||p − ck (t)|| − σk (t)) If in the first case several neurons are suit(A. there is no accepting neuron at all. If p is located in the perceptive surfaces of several neurons. Then the radius moves towards ||p − ck || (i. let us define A.2 A ROLF learns unsupervised the two learning rates ησ and ηc for radii by presenting training and centers.5.5) criterion for a ROLF neuron k to be an accepting neuron of a point p is that the point p must be located within the perceptive surface of k . So it is enLet us assume that we entered a training sured that the radius σk cannot only desample p into the network and that there crease but also increase.
Appendix A Excursus: Cluster analysis and regional and online learnable fields dkriesel. the radius multiplier is set to Mean σ : We select the mean σ of all neurons. Currently. such as 2 or 3. then ck is intialized with p and σk according to ron. Minimum σ : We take a look at the σ of each neuron and select the minimum. the mean-σ variant is the faSo far we only have discussed the case in vorite one although the learning procedure the ROLF training that there is an accept. i. generated Definition A.also works with the other ones. maximum-σ .5. cover less of the surface. ck = p.com Generally.e. In the minimum-σ variant the neurons tend to ing neuron for the training sample p. new neurons are surface. minimum-σ .ated by entering a training sample p. generated for our training sample. The result is of course that ck and σk have to be The training is complete when after reinitialized. values in the lower one-digit range.2.8 (Generating a ROLF neuThis suggests to discuss the approach for ron). mean-σ ). in the maximumσ variant they tend to cover more of the A. peated randomly permuted pattern presen- initialization of a neurons The initialization of ck can be understood tation no new neuron has been generated intuitively: The center of the new neuron in an epoch and the positions of the neurons barely change. Thus.3 Evaluating a ROLF We generate a new neuron because there is no neuron close to p – for logical reasons.5. is simply set on the training sample. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . The result of the training algorithm is that the training set is gradually covered well we place the neuron exactly on p. A.3 As required. put set). one of the aforementioned strategies (initIn this case a new accepting neuron k is σ . nected when their perceptive surfaces over- cluster = connected neurons 178 D. Then it is very easy to define the number of clusters: Two neurons are (accordMaximum σ : We take a look at the σ of ing to the definition of the ROLF) coneach neuron and select the maximum. If a new ROLF neuron k is generthe case that there is no accepting neu. and precisely by the ROLF neurons and But how to set a σ when a new neuron that a high concentration of points on a is generated? For this purpose there exist spot of the input space does not automatidifferent options: cally generate more neurons. a posInit-σ : We always select a predefined sibly very large point cloud is reduced to very few representatives (based on the instatic σ .
e.e. Particularly with clustering methods whose storage effort grows quadratic to |P | the storage effort can be reduced dramatically since generally there are considerably less ROLF neurons than original data points. Of course. i. that storing the neurons rather than storing the input points takes the biggest part of the storage effort of the ROLFs.5 Regional and online learnable fields A. Since it is unnecessary to store the entire point cloud.5. but the neurons represent the data points quite well.3: The clustering process. some kind of nearest neighboring is executed with the variable perceptive surfaces). as a neural clustering method. A. which is definitely a great advantage. which is by far the greatest disadvantage of the two neighboring methods. the complete ROLF network can be evaluated by means of other clustering methods.dkriesel. has the capability to learn online. A cluster is a group of connected neurons or a group of points of the input space covered by these neurons (fig. it can (similar to ε nearest neighboring or k nearest neighboring) distinguish clusters from enclosed clusters – but due to the online presentation of the data without a quadratically growing storage effort. our ROLF. the neurons can be searched for clusters. D. bottom: the input space only covered by the neurons (representatives).com lap (i.3). Furthermore. middle: the input space covered by ROLF neurons. This is a great advantage for huge point clouds with a lot of points.4 Comparison with popular clustering methods It is obvious. Top: the input set. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 179 . A. less storage effort! recognize "cluster in clusters" Figure A.
Determine at least four adaptation steps for one single ROLF neuron k if the four patterns stated below are presented one after another in the indicated order. for σ and ρ.1.005 to 0. ing color clusters in RGB images. k -means clustering recognizes clusters enclosed by other A first application example could be findclusters as separate clusters. the ROLF is on a par with the other clustering methods and is particularly very interesting for systems with The ROLF compares favorably with k . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . variations during P = {(0.5 Initializing radii. 0. The previous knowledge about the data set can so to say be included in ρ and the initial value of σ of the ROLF: Fine-grained data clusters should use a small ρ and a small σ initial value.com Additionally.9)}.1. the disadvantages of the ROLF dimensions. they often have to be tested). depend on the cluster and data distribu= (0. As a whole. lar. But compared to wrong initializations – 180 D. means clustering.1. just like for the learning rates ηc and ησ .1).Appendix A Excursus: Cluster analysis and regional and online learnable fields dkriesel.5.5 and digit range such as 2 or 3 are very popuη = 0. Thus.1). Further applications can be shall not be concealed: It is not always found in the field of analysis of attacks on easy to select the appropriate initial value network systems and their classification. Furthermore.9.σ ues about 0.low storage capacity or huge data sets.6 Application examples of clusters and. 0. secondly. at least with the mean-σ strategy – they are relatively robust after some training time. But the smaller the ρ the smaller. Another field of application directly described in the ROLF publication is the recognition of A. ηc and ησ successfully work with val. Initial values for σ generally = (0. run-time are also imaginable for this type = (0.1) and For ρ the multipliers in the lower singleσk = 1. Let ρ = 3. Let the initial values for the ROLF neuron be ck = (0. 0. learning words transferred into a 720-dimensional rates and multiplier is not feature space. let ηc = 0. tion (i. we can see that trivial ROLFs are relatively robust against higher Certainly.which is also not always the case for the two mentioned methods. there is no easy answer.5. the issue of the size of the individual clusters proportional to their distance from each other is addressed by using variable perceptive surfaces . 0.e.9. Exercises Exercise 18. of network. the chance that the neurons will grow if necessary.1. as well: Firstly. Here again. it is unnecessary to previously know the number A.9). 0.
we will respect I will again try to avoid formal deflook for a neural network that maps the initions. In this If we want to predict a time series. After discussing the different paradigms of neural networks it is now useful to take a look at an application of neural networks which is brought up often and (as we will see) is also used for fraud: The application of time series prediction. we will time series of values ∆t 181 . Finally. Share price values also represent a time series. For example.Appendix B Excursus: neural networks used for prediction Discussion of an application of neural networks: a look ahead into the future of time series. daily measured temperature values or other meteorological data of a specific site could be represented by a time series. B.1 About time series A time series is a series of values discretized in time. Time series can also be values of an actually continuous function read in a certain This chapter should not be a detailed distance of time ∆t (fig. I will say something about the range of software which should predict share prices or other economic characteristics by means of neural networks or other procedures. B. proaches for time series prediction.g. the daily weather forecast. and in many time series the future development of their values is very interesting.page). Often the measurement of time series is timely equidistant. This excursus is structured into the description of time series and estimations about the requirements that are actually needed to predict the values of a time series.e. if we know longer sections of the time series. e.1 on the next description but rather indicate some ap. i. previous series values to future developments of the time series.
we assume systems whose future values can be deduced from their states – the deterministic systems. In this chapter. Do we have any evidence which sug- gests that future values depend in any way on the past values of the time series? Does the past of a time series include information about its future? time series that can be used as training patterns? function: What must a useful ∆t look like? 2. Do we have enough past values of the 3. for instance. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . In case of a prediction of a continuous Figure B. these are not examples for the future to be predicted but it is tried to generalize and to extrapolate the past by means of the said samples. This 182 D.Appendix B Excursus: neural networks used for prediction dkriesel. If the future values of a time series.com have enough training samples. The sampled values are entered into a neural network (in this example an SLP) which shall learn to predict the future values of the time series. Now these questions shall be explored in detail. then a time series prediction based on them will be impossible. this means that the result is a time series.1: A function x that depends on the time is sampled at discrete time steps (time discretized). But before we begin to predict a time series we have to answer some questions about this time series we are dealing with and ensure that it fulfills some requirements. How much information about the future is included in the past values of a time series? This is the most important question to be answered for any time series that should be mapped into the future. do not depend on the past values. Of course. 1.
xt ) = x ˜t+1 . . From this tions. The future The first attempt to predict the next fuof a deterministic system would be clearly ture value of a time series out of past valdefined by means of the complete descripues is called one-step-ahead prediction tion of its current state. . input and outputs the prediction for the next state (or state part). xt−1 . e. . . B.1) wide phenomena that control the weather would be interesting as well as small local pheonomena such as the cooling system of which receives exactly n past values in orthe local power plant. Here we use the fact that time series x ˜ D. The aim of the predictor is to realize a But the whole state would include signifi.dkriesel.2) weaknesses by using not only one single state (the last one) for the prediction. .values. . but that approximately fulfills our condiby using several past states. for a The most intuitive and simplest approach weather forecast these fragments are the would be to find a linear combination said weather data. (fig. the atmospheric pressure and the cloud density as the meteorological state of the place at a time t. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 183 . (B.g. der to predict the future value.to distinguish them from the actual future sirable for prediction but not always possi.com leads us to the question of what a system state is. B. the temperature.function predict the next value cantly more information.g. Often only fragments of the current states can be acquired.2 on the following page). The problem in the real world is that such Such a predictor system receives the last a state concept includes all things that inn observed state parts of the system as fluence our system by any means. we can partially overcome these (B.2 One-step-ahead prediction B. x ˜i+1 = a0 xi + a1 xi−1 + . The idea of In case of our weather forecast for a spea state space with predictable states is cific site we could definitely determine called state space forecasting.2 One-step-ahead prediction A system state completely describes a system for a certain point of time. Predicted values shall be headed by a tilde (e. Here. ble to obtain. x ˜) So we shall note that the system state is de. + aj xi−j However. the worldf (xt−n+1 . we want to derive our first prediction system: Such a construction is called digital filter.
In fact. can set up a series of equations1 : Even if this approach often provides satisxt−1 = a0 xt−2 + . Additional layers with xt−n = a0 xt−n + . But remember that here the number mental setup would comply with fig. .2: Representation of the one-step-ahead prediction. Or another. . activation functions provide a universal But this linear structure corresponds to a non-linear function approximator. a multilayer perceptron will require the prediction becomes easier the more past values considerably less computational effort.The multilayer perceptron and non-linear ing average procedure. This is called mov. .1 n has to remain low since in RBF networks on page 182). since a multilayer perceptron with Thus. . . Such could use m > n equations for n unknowns considerations lead to a non-linear apin such a way that the sum of the mean proach. .3) lems cannot be solved by using a singlelayer perceptron. we have seen that many prob. + aj xt−1−(n−1) 184 D.only linear activation functions can be resible). .com x ˜t+1 u FEC predictor Figure B. usually have a lot of past values so that we means of the delta rule provides results very close to the analytical solution. + aj xt−2−(n−1) fying results. n equations could be found for n unknown coefficients and solve them (if pos. better approach: we duced to a singlelayer perceptron. B. An RBF network could also be means of data from the past (The experi. The predicting element (in this case a neural network) is referred to as predictor. It is tried to calculate the future value from a series of past values. + aj xt−n−(n−1) linear activation function are useless. as well. the training by high input dimensions are very complex to realize. i. . I want to remark that values.can use an n-|H |-1-MLP for n n inputs out tion function which has been trained by of the past. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . (B.Appendix B Excursus: neural networks used for prediction xt−3 xt−2 xt−1 xt dkriesel.used. I would like to ask the reader to read up on the Nyquist-Shannon sampling theorem xt = a0 xt−1 + . we singlelayer perceptron with a linear activa. So if we want to include many past 1 Without going into detail.e. of the time series are available. squared errors of the already known prediction is minimized.
1 Changing temporal prediction is generally imprecise so that parameters errors can be built up.m. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 185 .3.e.4 Additional optimization approaches for prediction B. we can certainly train it to predict the It is also possible to combine different ∆t: next but one value.4 on the we use the last values of several periods. a neural network Monday the values of the last few days to look two time steps ahead into the fu. everyone of us has difference is the training.many people sat in the lecture room on stance. two time steps into the future.com B.The possibility to predict values far away in the future is not only important because ther into the future? we try to look farther ahead into the future. There can also be periodic time series where other approaches are hardly posB. Thus. i. it is not very useful to know how In order to extend the prediction to.2 Direct two-step-ahead which past value is used for prediction.e. to periodically occurring commuter page). every prediction Thursday. We could also include an anthe one-step-ahead prediction. to introduce the parameter ∆t which indicates B. it can be useful to intentionally leave imprecise becomes the result. step-ahead prediction (fig. which is referred to as direct two. prediction Technically speaking. Obviously.3. the value determined by means of a one-step-ahead B. extent input period direct prediction is better D. a recursive two-step-ahead jams. B.dkriesel. prediction. gaps in the future values as well as in the past values of the time series. for extions in a row (fig.4.could be used as data input in addition to ture. This means we di. for in. next page).the values of the previous Mondays. The only nual period in the form of the beginning of the holidays (for sure. can be trained to predict the next value. The same applies. we still use a onestep-ahead prediction only that we extend We have already guessed that there exists the input space or train the system to prea better approach: Just like the system dict values lying farther away. for example. we Monday to predict the number of lecture could perform two one-step-ahead predic.1 Recursive two-step-ahead sible: If a lecture begins at 9 a. B. i.3 on the following ample.participants.4 Additional optimization approaches for prediction predict future values What approaches can we use to to see far. and the more predictions are performed in a row the more Thus.In case of the traffic jam prediction for a rectly train. Unfortunately.in this case the values of a weekly and a ahead prediction is technically identical to daily period.3 Two-step-ahead prediction B. the direct two-step.
the first one is omitted.com H predictor y xt−3 xt−2 xt−1 xt x ˜t+1 t FEC predictor x ˜t+2 Figure B.Appendix B Excursus: neural networks used for prediction dkriesel. Technically. the second time step is predicted directly. 186 D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . xt−3 xt−2 xt−1 xt x ˜t+1 FEC predictor x ˜t+2 i Figure B. Attempt to predict the second future value out of a past value series by means of a second predictor and the involvement of an already predicted value. it does not differ from a one-step-ahead prediction.4: Representation of the direct two-step-ahead prediction.3: Representation of the two-step-ahead prediction. Here.
dkriesel.com
B.5 Remarks on the prediction of share prices
already spent a lot of time on the highway discrete values – often, for example, in a because he forgot the beginning of the hol- daily rhythm (including the maximum and minimum values per day, if we are lucky) idays). with the daily variations certainly being eliminated. But this makes the whole B.4.2 Heterogeneous prediction thing even more difficult. Another prediction approach would be to predict the future values of a single time series out of several time series, if it is assumed that the additional time series is related to the future of the first one (heterogeneous one-step-ahead prediction, fig. B.5 on the following page). If we want to predict two outputs of two related time series, it is certainly possible to perform two parallel one-step-ahead predictions (analytically this is done very often because otherwise the equations would become very confusing); or in case of the neural networks an additional output neuron is attached and the knowledge of both time series is used for both outputs (fig. B.6 on the next page). You’ll find more and more general material on time series in [WG94]. There are chartists, i.e. people who look at many diagrams and decide by means of a lot of background knowledge and decade-long experience whether the equities should be bought or not (and often they are very successful). Apart from the share prices it is very interesting to predict the exchange rates of currencies: If we exchange 100 Euros into Dollars, the Dollars into Pounds and the Pounds back into Euros it could be possible that we will finally receive 110 Euros. But once found out, we would do this more often and thus we would change the exchange rates into a state in which such an increasing circulation would no longer be possible (otherwise we could produce money by generating, so to speak, a financial perpetual motion machine. At the stock exchange, successful stock and currency brokers raise or lower their thumbs – and thereby indicate whether in their opinion a share price or an exchange rate will increase or decrease. Mathematically speaking, they indicate the first bit (sign) of the first derivative of the exchange rate. In that way excellent worldclass brokers obtain success rates of about 70%.
use information outside of time series
B.5 Remarks on the prediction of share prices
Many people observe the changes of a share price in the past and try to conclude the future from those values in order to benefit from this knowledge. Share prices are discontinuous and therefore they are principally difficult functions. Further- In Great Britain, the heterogeneous onemore, the functions can only be used for step-ahead prediction was successfully
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
187
Appendix B Excursus: neural networks used for prediction
dkriesel.com
xt−3
xt−2
xt−1
xt
x ˜t+1
u FHEICQ predictor
yt−3
yt−2
yt−1
yt
Figure B.5: Representation of the heterogeneous one-step-ahead prediction. Prediction of a time series under consideration of a second one.
xt−3
xt−2
xt−1
xt
x ˜t+1
u FHEICQ predictor
yt−3
yt−2
yt−1
yt
y ˜t+1
Figure B.6: Heterogeneous one-step-ahead prediction of two time series at the same time.
188
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
dkriesel.com
B.5 Remarks on the prediction of share prices Again and again some software appears which uses scientific key words such as ”neural networks” to purport that it is capable to predict where share prices are going. Do not buy such software! In addition to the aforementioned scientific exclusions there is one simple reason for this: If these tools work – why should the manufacturer sell them? Normally, useful economic knowledge is kept secret. If we knew a way to definitely gain wealth by means of shares, we would earn our millions by using this knowledge instead of selling it for 30 euros, wouldn’t we?
used to increase the accuracy of such predictions to 76%: In addition to the time series of the values indicators such as the oil price in Rotterdam or the US national debt were included. This is just an example to show the magnitude of the accuracy of stock-exchange evaluations, since we are still talking only about the first bit of the first derivation! We still do not know how strong the expected increase or decrease will be and also whether the effort will pay off: Probably, one wrong prediction could nullify the profit of one hundred correct predictions. How can neural networks be used to predict share prices? Intuitively, we assume that future share prices are a function of the previous share values. But this assumption is wrong: Share prices are no function of their past values, but a function of their assumed future value. We do not buy shares because their values have been increased during the last days, but because we believe that they will futher increase tomorrow. If, as a consequence, many people buy a share, they will boost the price. Therefore their assumption was right – a self-fulfilling prophecy has been generated, a phenomenon long known in economics. The same applies the other way around: We sell shares because we believe that tomorrow the prices will decrease. This will beat down the prices the next day and generally even more the day after the next.
share price function of assumed future value!
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
189
Now we want to explore something inbetween: The learning paradigm of reinforcement learning – reinforcement learning according to Sutton and Barto [SB98]. Due to its very rudimentary feedback it is reasonable to separate it from the supervised learning procedures – apart from the fact that there are no training samples at all. i.e. we provide exemplary output values. In some sources it is counted among the supervised learning procedures since a feedback is given. The term reinforcement learning comes from cognitive science and psychology and it describes the learning system of carrot and stick. then nobody could tell us exactly which han- no samples but feedback 191 . but no results for the individual intermediate steps. Reinforcement learning in itself is no neural network but only one of the three learning paradigms already mentioned in chapter 4.e. But there is no learning aid that exactly explains what we have to do: We only receive a total result for a process (Did we win the game of chess or not? And how sure was this victory?). I now want to introduce a more exotic approach of learning – just to leave the usual paths. For example. if we ride our bike with worn tires and at a speed of exactly 21. which occurs everywhere in nature. into which only input values are entered. i. While it is generally known that procedures such as backpropagation cannot work in the human brain itself. reward and punishment.Appendix C Excursus: reinforcement learning What if there were no training samples but it would nevertheless be possible to evaluate how well we have learned to solve a problem? Let us examine a learning paradigm that is situated between supervised and unsupervised learning. learning by means of good or bad experience.1mm. 5 km h through a turn over some sand with a grain size of 0. We know learning procedures in which the network is exactly told what to do. on the average. We also know learning procedures like those of the self-organizing maps. reinforcement learning is usually considered as being biologically more motivated.
The agent influences the system. be it good or bad. we will get a feel for what works and what does not. as mentioned above. Broadly speaking. The reward is a real or discrete scalar which describes. a feedback or a reward. which in the following is called reward. The agent performs some actions within the environment and in return receives a feedback from the environment.Appendix C Excursus: reinforcement learning dlebar angle we have to adjust or. each of these components sizes and components of the system. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . how strong the great number of muscle parts in our arms or legs have to contract for this. how well we achieve our aim. The agent shall solve some problem. He could. be an autonomous robot that shall avoid obstacles. even worse. discrete forcement learning represents the mutual simple examplary world 192 D.1 on the facing page) is a simple. Thus. The aim is always to make the sum of rewards as high as possible on the long term. However. C. This cycle of action and reward is characteristic for reinforcement learning.1 The gridworld tournament.1. the system provides a reward and then changes. reinforcement gridworld. Now let us exemplary deC. We will be examined more exactly. it is very suitable for representing the approach of reinforcement learning.but on the other hand it is considerably easier to obtain. Depending on whether we reach the end of the curve unharmed or not. We will see that its struclearning often means trial and error – and ture is very simple and easy to figure out and therefore reinforcement is actually not therefore it is very slow. As a learning example for reinforcement To get straight to the point: Since we learning I would like to use the so-called receive only little feedback.1 System structure fine the individual components of the reinforcement system by means of the gridNow we want to briefly discuss different world.com interaction between an agent and an environmental system (fig. The aim of reinforcement learning is to maintain exactly this feeling. Later. dkriesel. Another example for the quasiimpossibility to achieve a sort of cost or utility function is a tennis player who tries to maximize his athletic success on the long term by means of complex movements and ballistic trajectories in the three-dimensional space including the wind direction. we soon have to face the learning experience. rein. for instance. the reward is very simple . C. private factors and many more. necessary.2). If we now have tested different velocities and turning angles often enough and received some rewards. but it does not give any guidance how we can achieve it.Environment: The gridworld (fig. the importance of the C. will define them more precisely in the following sections.
com world in two dimensions which in the following we want to use as environmental system. in the lower part it is closed. We simply define that the robot could move one field up or down. Agent: As an Agent we use a simple robot being situated in our gridworld.1 System structure × Action space: The actions are still missing.1. our agent can occupy 29 positions in the grid world. gridworld. The symbol × marks the starting position of our agent. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 193 . We now have created a small world that will accompany us through the following learning strategies and illustrate them. The exit is located on the right of the light-colored field. The exit is located on the right side of the light-colored field. The position of the door cannot change during a cycle but only between the cycles. These positions are regarded as states for the agent. Therefore. c Agent reward / new situation action environment Figure C. Dark-colored cells are obstacles and Task: Our agent’s task is to leave the gridworld. Non-determinism: The two obstacles can be connected by a "door". State space: As we can see. it D. to the right or to the left (as long as there is no obstacle or the edge of our Figure C. When the door is closed (lower part of the illustration). C. the corresponding field is inaccessible. Thus.1: A graphical representation of our gridworld).dkriesel.2: The agent performs some actions within the environment and in return receives a reward. therefore inaccessible.2 Agent und environment Our aim is that the agent learns what happens by means of the reward. × C. our gridworld has 5 × 7 fields with 6 fields being unaccessible. In the upper part of our figure the door is open.
it would be possible to plan opment learning the agent can be formally timally and also easy to find an optimal In the gridworld: In the gridworld. solution it may sometimes be useful to t+1 receive a smaller award or a punishment Environment: S × A → P (S × rt ) (C.2 (Environment).3 States. The award is. the final sum of all rewards – which is also called return. In reinforce. uations to actions (called policy ).Appendix C Excursus: reinforcement learning is trained over. The aim is simply shown to the agent by giving an Definition C.e. But what does learning mean in this context? dkriesel. vironment represents a stochastic mapping of an action A in the current situaSuch an award must not be mistaken for tion st to a reward rt and a new situation the reward – on the agent’s way to the s .1) to achieve a certain (given) aim. speak. of and by means of a dynamic system. it different states: In case of the gridworld.system). we want to discuss more state so that we have to introduce the term precisely which components can be used to situation. if the agent is heading into As already mentioned. For an agent is ist not always possible to After having colloquially named all the ba. in order to reach an aim. only a more or less precise approximation of a state. ing system. the environment. If we knew all states and the transitions between them exactly (thus. the complete Definition C. So.1 (Agent).com agent acts in environment described as a mapping of the situation space S into the action space A(st ). i. i. The meaning of situations st will be defined later and should only indicate that the action space depends on the current situaThe agent shall learn a mapping of sittion.1. it can be in different positions ceives no reward at all or even a negative (here we get a two-dimensional state vecreward (punishment). receives a positive reward. it shall learn what to do in which situation Agent: S → A(st ) (C.realize all information about its current sic components. 194 D. The enaward for the achievement. an agent can be in the right direction towards the target. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . and if not it refor example. situations and actions share price or to a pawn sacrifice in a chess game). A situation is a state from the make up our abstract reinforcement learn. which is a discrete gridworld. The environment is the gridworld itself. situations generally do not allow to clearly "predict" successor situations – even with a completely deterministic system this may not be applicable. the agent is a simple robot that should find the exit of the gridworld.e. Therefore.2) when in return the longterm result is maximum (similar to the situation when an investor just sits out the downturn of the C. so to tor).agent’s point of view.
an infinite sum in the first place rt D. the return is only estimated directly know what is better or worse. only finitely many time steps will be tion within a deterministic system out of possible.5 (Action). . Possible actions would be to move towards north.1.com C. For finitely many time steps1 the rewards can simply be added: st S at A(S ) Rt = rt+1 + rt+2 + .3 (State).4) however. the situations equal the states point of view. real or discrete (even sometimes it is theoretically possible to clearly pre.e. called return R. They cause state transitions and where the agent can be situated. which would not be possible. here (if we knew all rewards and therefore the return completely. it would no longer Definition C. south. S are the agent’s limited. The agent cannot determine dictions impossible. C. Thus. could be possible that depending on the situation another action space A(S ) exIn the gridworld: States are positions ists). Actions at can why it receives the said reward from the be performed by the agent (whereupon it environment. This approxis an interaction between the agent and imation (about which the agent cannot the system including actions at and siteven know how good it is) makes clear preuations st . the reward is always a scalar (in an extreme case even only a binary value) since the aim of reinforcement learning is to get along with little feedback. A reward rt is within the environmental system. As in real life it is our aim to receive an award that is as high as possible. A complex vectorial reward would equal a real teaching input. east or west. Situations st (here at time t) of a situation space by dynamic programming). with a vectorial reward since we x=1 do not have any intuitive order relations in multi-dimensional space. i. . Simtherefore a new situation from the agent’s ply said. vironment the agent is in a state. Definition C. on the long term. by itself whether the current situation is good or bad: This is exactly the reason Definition C. to maximize the sum of the expected rewards r. the cost function should be ∞ minimized.6 (Reward). i. for example.3) By the way. we do not Certainly. = rt+x (C.dkriesel.only binary) reward or punishment which dict a successor state to a performed ac1 In practice. even though the formulas are stated with this godlike state knowledge.e. Within its enbe necessary to learn). (C. States contain any information about the agent Definition C.1 System structure policy (methods are provided.4 (Situation). in the gridworld. a scalar. approximate Now we know that reinforcement learning knowledge about its state.4 Reward and return Situation and action can be vectorial. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 195 .
5) During reinforcement learning the agent learns a policy ∞ = x=1 γ x−1 rt+x (C. This is not only some system components of reinforcement useful if there exists no target but also if learning the actual aim is still to be discussed: the target is very far away: Rt = rt+1 + γ 1 rt+2 + γ 2 rt+3 + . our current situation to a desired state.1.6) Π Π : S → P (A).7 (Return). the smaller Thus. the pawn sacrifice in a chess game) plicit target and therefore a finite sum (e. . our agent can be a robot having the task to drive around again and again and to avoid obstacles). τ so that only τ many following rewards In the gridworld: In the gridworld the polrt+1 . not every problem has an ex(e. . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . . but will pay off later. The policy Π s a mapping of situations to probabilities 196 D. sions. it continuously adjusts a mapping is the influence it has in the agent’s deci.of the situations to the probabilities P (A).5 The policy diverging sum in case of an infinite series of reward estimations a weakening factor 0 < γ < 1 is used. we divide the timeline into episodes. ods is used to limit the sum. it time is also possible to perform actions that. The return Rt methods together. Usually. = τ x=1 γ x−1 rt+x (C. with which any action A is performed in any situation S . A policy can be defined Another possibility to handle the return as a strategy to select actions that would sum would be a limited time horizon maximize the reward in the long term. rt+τ are regarded: icy is the strategy according to which the Rt = rt+1 + . .g. τ The farther the reward is away.Appendix C Excursus: reinforcement learning dkriesel. .1 Dealing with long periods of tal sum decides what the agent will do. + γ τ −1 rt+τ (C.After having considered and formalized fluence of future rewards. (C.8 (Policy).4. if not both Definition C. on short notice. In order not to receive a C. . .com Rt γ the environmental system returns to the Thus. Since it is not mandatory that only the next expected reward but the expected toC.8) Definition C.g. which weakens the in.1. result in a negative reward However.7) agent tries to exit the gridworld. . is the accumulation of all received rewards As in daily living we try to approximate until time t. one of the two methagent as reaction to an action.
we distinguish between two pol. This policy represents such problems we have to find an alterna. C. . Here. In particular. which incorpo. Π : S → P (A). (C. so to speak. Thus. in the beginning the agent develops a plan and consecutively executes it to the end without considering the intermediate situations (therefore ai = ai (si ). But. to perform every action out of the action in a manner of speaking.a reactive plan to map current situations icy paradigms: An open loop policy rep. as already illustrated in fig. when an obstacle appears dynamically. such as the way from the given starting position to (in ab. to know the A greedy policy always chooses the way chess game well and truly it would be nec.of the highest reward that can be deteressary to try every possible move. Thus. In the gridworld: A closed-loop policy would be responsive to the current position and choose the direction according to the action.e. an examined.C.the exploitation approach and is very tive to the open-loop policy. i > 0. actions after a0 do not depend on the situations). open-loop policy would provide a precise direction towards the exit.promising when the used system is already rates the current situations into the action known. which mined in advance. resents an open control chain and creates out of an initial situation s0 a sequence of actions a0 . exploration breviations of the directions) EEEEN. with ai = ai (si ). So it can be formalized as responds to the input of the environment. starting situation. for example. plan: In contrast to the exploitation approach it A closed loop policy is a closed loop.2. As in real life.exisiting knowledge is only willfully exquence of actions is generated out of a ploited or new ways are also explored. research or safety? D. for est known reward.1 System structure When selecting the actions to be performed. such an open-loop policy tremes: can be used successfully and lead to useful results. A se.com C.1 Exploitation vs. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 197 .1. a1 .dkriesel. again two basic strategies can be In the gridworld: In the gridworld. i. we want to discuss the two exwell and truly. is Basically. a is the aim of the exploration approach to explore a system as detailed as possible function so that also such paths leading to the target can be found which may be not very Π : si → ai with ai = ai (si ). such a policy is the better choice. If the system is known Initially. the environment influences our action or the agent space. during reinforcement learnSo an open-loop policy is a sequence of ing often the question arises whether the actions without interim feedback.9) respectively. . . the way of the highwould be very time-consuming.5.to actions to be performed. A closed-loop policy.
Here. C. not matter how unoptimal and long it may be. the reexplore shorter ways every now and then. The exploration apvery successful.Appendix C Excursus: reinforcement learning dkriesel.com promising at first glance but are in fact he leaves of such a tree are the end situations of the system. know. and not to try to explore bet. we also ter ways.the end of and not during the game. a static probability distribution is also possible and often applied.2. even at the risk of taking a long time and Now we have to adapt from daily life how being unsuccessful. from each subsit.cases as design examples for the reward: tions can lead us from one situation into different subsituations.finally can say whether we were succesful rately be referred to as a situation graph ). First of all. the restaurant example aption. This ered (often there are several ways to reach method is always advantageous when we a situation – so the tree could more accu. a safe policy would leaves. or not. we get a situation tree where reward : We only receive the reward at links between the nodes must be consid. proach would search the tree as thoroughly Let us assume that we are looking for the as possible and become acquainted with all way to a restaurant. there generally are (again as in daily life) various acIn the gridworld: For finding the way in tions that can be performed in any situathe gridworld.2 Learning process We now want to indicate some extreme Let us again take a look at daily life. Another approach would be to can create an action tree. In reality. In chess game is referred to as pure delayed a sense.A rewarding similar to the rewarding in a uation into further sub-subsituations. As we have seen above.Analogous to the situation tree. uate the selected situations and to learn which series of actions would lead to the target. Ac. There are different strategies to evalplies equally. The exploitation approach would be to always take the way we already unerringly go to the best known leave. often a combination of both methods is applied: In the beginning of the learning process it is researched with a higher probability while at the end more existing knowledge is exploited. wards for the actions are within the nodes. this principle should be explained in the following. but the interim steps do not allow 198 D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . having to take the original way and arrive too late at the restaurant. Here. C. and therefore finally we learn exactly.1 Rewarding strategies Interesting and very important is the question for what a reward and what kind of reward is awarded since the design of the reward significantly controls system behavior.
If we lose. If we win. only a few of them receive a negative reward. Most situations do not receive any reward.2 The state-value function Unlike our agent we have a godlike view of our gridworld so that we can swiftly determine which robot starting position can provide which optimal return. For our gridworld we want to apply the rt = 0 ∀t < τ (C. only returned by the leaves of the situation complex tasks. then rτ = −1. we can see that it would be more practical for the robot to be capable to evaluate the current and future situations. (C. The agent agent will avoid getting too close to such negative situations Thus. we can show that especially small tasks can be solved better by means as well as rτ = 1. which with regard to a policy Π is often called VΠ (s). (C. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 199 .11) pure negative reward strategy: The robot shall find the exit as fast as possible. we will understand that this A situation being bad under a policy that behavior optimally fulfills the return of the is searching risks and checking out limits D.10) Pure negative reward : Here.3 on the next page these optimal returns are applied per field. rt = −1 ∀t < τ. So let us take a look at another system component of reinforcement learning: the state-value function V (s). This system finds the most rapid way to reach the target because this way is automatically the most favorable one in respect of the reward. C.12) is unknown and has to be learned. The agent receives punishment for anything it does – even if it does nothing. If standing still is also punished. Because whether a situation is bad often depends on the general behavior Π of the agent. for our gridworld exactly represents such Here.2 Learning process an estimation of our situation.dkriesel. more With this rewarding strategy a reward is differentiated rewards are useful for large. tree.In the gridworld: The state-value function egy : Harmful situations are avoided. a function per situation (= position) with the difference being that here the function rt ∈ {0. then Furthermore. As a result it is the most inexpensive method for the agent to reach the target fast. robot but unfortunately was not intended to do so.2.com C. −1}. state evaluation Another strategy is the avoidance strat. Reconsidering this. In figure C. A robot that is told "have it your own way but if you touch an obstacle you will be punished" will simply stand still. it will drive in small circles. of negative rewards while positive. Warning: Rewarding strategies can have unexpected consequences.
13) -7 -3 -7 have a godlike view of its environment. It does not have a table with optimal returns like the one shown above to orient itself.tion bit by bit on the basis of the returns of cycle turns a corner and the front wheel many trials and approximates the optimal begins to slide out.1 Policy evaluation Policy evaluation is the approach to try a policy a few times.3: Representation of each optimal re.Appendix C Excursus: reinforcement learning -6 -7 -6 -7 -8 -9 -10 -6 -7 -8 -9 -10 -11 -10 -5 -5 -6 -7 -8 -9 -5 -9 -10 -11 -10 -9 -4 -4 -5 -6 -7 -8 -4 -10 -11 -10 -9 -8 -3 -3 -2 -1 -2 -3 -4 -5 -6 -2 -1 -2 -3 -4 -5 -6 dkriesel. if an agent on a bi. the value of the statevalue function corresponds to the return Rt (the expected value) of a situation st . With a risk-aware policy terms closely related to the cycle between the same situations would look much betstate-value function and policy: ter. Π turn per field in our gridworld by means of pure negative reward awarding.V ∗ (s). devil policy the agent would not brake in In this context I want to introduce two this situation. For this purpose it returns the expectation of the return under the situation: VΠ (s) = EΠ {Rt |s = st } (C. The state-value function VΠ (s) has the task of determining the value of situations under a policy.com EΠ denotes the set of the expected returns under Π and the current situation st . at the top with an Unfortunaely.2.state-value function V ∗ (if there is one). to provide many rewards that way and to gradually accumulate a state-value function by means of these rewards.e. Figure C. VΠ (s) = EΠ {Rt |s = st } Definition C. according to the above definitions. unlike us our robot does not open and at the bottom with a closed door. for instance. to answer the agent’s question of whether a situation s is good or bad or how good or bad it is. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . The aim of reinforcement learning is that the robot generates its state-value funcwould be. And due to its dare. Abstractly speaking. The optimal state-value function is called ∗ (s) VΠ 200 D.2. C.9 (State-value function). thus it would be evaluated higher by a good state-value function VΠ (s) VΠ (s) simply returns the value the current situation s has for the agent under policy Π. i.
But here caution is advised: In this way.2 Learning process The easiest approach to accumulate a state-value function is mere trial and erV∗ Π∗ ror. random pol.2. would produce oscillations for all fields and such oscillations would influence their shortest way to the target. D. At first.4). If we additionally assume a pure negative reward. let us regard a simple.com C. one field). Our door.e.dkriesel. we want to memorize only the better value for one state (i. derived by out any previous knowledge. The changed state-value function provides information about the system with which we again improve our policy.e. V (st )new = V (st )alt + α(Rt − V (st )alt ).2. Thus.to use the learning rule consuming. It is tried to evaluate how good a policy is in individual situations. but this derivation is not discussed in this chapter. to turn it into a new and better one. V i A Π C.2. It can be proved that at some which ideally leads to optimal Π∗ and V ∗ .in which the update of the state-value funcicy by which our robot could slowly fulfill tion is obviously influenced by both the and improve its state-value function with2 The learning rule is. point we will find the exit of our gridworld by chance. C.2 Policy improvement Policy improvement means to improve a policy itself.e. among others.4: The cycle of reinforcement learning lated state-value function for its random decisions. With the Monte Carlo method we prefer 2 This cycle sounds simple but is very time. i. Intuitively. it is obvious that we can receive an optimum value of −6 for our starting field in the state-value function.3 Monte Carlo method C. means of the Bellman equation. The principle of reinforcement learning is to realize an interaction. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 201 . These two values lift each other. the learning procedure would work only with deterministic systems. i. so that the final result is an optimal policy Π∗ and an optimal state-value function V ∗ (fig. which can be open or closed during a cycle. Depending on the random way the random policy takes values other (smaller) than −6 can occur for the starting field. we select a randomly behaving policy which does not consider the accumuFigure C. In order to improve the policy we have to aim at the return finally having a larger value than before. which can mathematically be proved. until we have found a shorter way to the restaurant and have walked it successfully Inspired by random-based games of chance this approach is called Monte Carlo method.
Due to the fact that in the course of time many different ways are walked given a random policy. the agent gets some kind of memory. But this method is the only one for which it can be mathematically proved that it works and therefore it is very useful for theoretical considerations. C. the computation of the state value was applied for only one single state (our initial state). dkriesel. C. The result of such a calculation related to our example is illustrated in fig. In this example. It should be obvious that it is possible (and often done) to train the values for the states visited inbetween (in case of the gridworld our ways to the target) at the same time.10 (Monte Carlo learning). walking or riding a bicycle Figure C.g.com α -6 -5 -4 -3 -1 -2 -14 -13 -12 -11 -10 -9 -8 -7 -1 -2 -3 -4 -5 -6 -10 C. 202 D.Appendix C Excursus: reinforcement learning old state value and the received return (α is the learning rate). Definition C. Bottom: The result of the learning rule for the value of the initial state considering both ways.5: Application of the Monte Carlo learning rule with a learning rate of α = 0.4 Temporal difference learning Most of the learning is the result of experiences. Thus.6 on the facing page. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . Actions are randomly performed regardless of the state-value function and in the long term an expressive state-value function is accumulated by means of the following learning rule. The Monte Carlo method seems to be suboptimal and usually it is significantly slower than the following methods of reinforcement learning.5. An exemplary learning step is shown in fig.5. new findings always change the situation value just a little bit. Top: two exemplary ways the agent randomly selects are applied (one with an open and one with a closed door). a very expressive statevalue function is obtained. e.2. V (st )new = V (st )alt + α(Rt − V (st )alt ).
2.11 (Temporal difference learning). the temporal difference learning (abbreviated: TD learning ).5 in which the returns for intermediate states are also used to accumulate the statevalue function. tal skills like mathematical problem solv. TD learning looks ahead by rewithout getting injured (or not). Just as we learn from experience to re. is influenced by the received reward rt+1 . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 203 . which is proportional to the learning rate α. the previous return weighted with a factor γ of the following situation V (st+1 ). the following sit-9 uations with st+1 and so on.dkriesel.2 Learning process in fig.14) ple trial and error. Again the current situa-10 tion is identified with st . Thus.garding the following situation st+1 .Analogous to the state-value function act on different situations in different ways VΠ (s).7). the -8 -7 learning formula for the state-value funcFigure C. Unlike the Monte Carlo method. learn and improve the policy due to experience change of previous value (fig.6: Extension of the learning example tion VΠ (st ) is -1 -2 -3 -4 -5 -6 V (st )new =V (st ) + α(rt+1 + γV (st+1 ) − V (st )) change of previous value Evaluation We can see that the change in value of the current situation st .5 The action-value function rected manner. this state is impossible.the learning rule is given by ing benefit a lot from experience and sim(C. the agent learns to estimate which situations are worth a lot and -11 which are not).7: We try different actions within the environment and as a result we learn and improve the policy. we initialize our V (st )new =V (st ) + α(rt+1 + γV (st+1 ) − V (st )) . Thus. C. If the door is closed. the low value on the door field can be seen very well: If this state is possible. the action-value function action evaluation D. Thus. Here. does the same by -10 -9 -8 -3 training VΠ (s) (i. Definition C.com C. even men. C. In contrast to the Monte Carlo method we want to do this in a more diC.e. policy with arbitrary values – we try. the previous value of the situation V (st ). it must be very positive. Π 3 Q policy improvement Figure C.
But we must not disregard that reinforcement learning is generally quite slow: The system has to find out itself what is good. we do not mind to Definition C. always get into the best known next Like the state-value function. a)new =Q(st . Q(st . otherwise the actions are simply performed again and again). a) as learning fomula for the action-value function. a) −Q(st . Π t means of α). Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . a) Again we break down the change of the current action value (proportional to the learning rate α) under the current situaQΠ (s. moving greedy strategy down is not a good way at all (provided that the change of previous value door is open for all cases). a) is another system component of tion.8). moving up is still a quite fast way. on the other hand.2. a) + α(rt+1 + γ max Q(st+1 . the maximum action over the following actions weighted with γ (Here. a In the gridworld: In the gridworld. value function QΠ (st .6 Q learning +1 This implies QΠ (s. C. the actionsituation.com 0 × -1 C. one remains on the fastest way towards the tara get. The optimal action-value member that this is also weighted by function is called Q∗ ( s . a) Q∗ Π (s. a)) . With TD learning.9. a ) .12 (Action-value function). a) evaluates certain the previous value of the action under actions on the basis of certain situations our situation st known as Q(st . Usually. But the advantage of Q 204 D. It is influenced by reinforcement learning. tain direction (fig. which evaluates a the received reward rt+1 . QΠ (s. the actions are performed until a target situation (here referred to as sτ ) is achieved (if there exists a target situation. C.8: Exemplary values of an actionvalue function for the position ×.). a) (reunder a policy. the greedy strategy is applied since it can action-value function tells us how good it be assumed that the best known acis to move from a certain field into a certion is selected. and – analogously to TD learning – its application is called Q learning : Figure C. the action-value function learns considerably faster than the state-value function. Moving right. As shown in fig.Appendix C Excursus: reinforcement learning dkriesel. certain action a under a certain situation s and the policy Π.
Then the + α(rt+1 + γ max Q(st+1 .played backgammon knows that the situily. a)) . The situation here is the current configuration of the board. and by means of Q learning the result ation space is huge (approx.9: Actions are performed until the desired target situation is achieved. 1020 situais always Q∗ . The result ∗ was that it achieved the highest ranking in and thus finds Q in any case. a)new =Q(st . system was allowed to practice itself a (initially against a backgammon program.e.ticularly in the late eighties when TD gaming trains the action-value function by mon was introduced). a computer-backgammon league and strikingly disproved the theory that a computer programm is not capable to master a task C.3. As a result. The selected remeans of the learning rule warding strategy was the pure delayed reward. the system receives the reward not before the end of the game and at the Q(st . Q learn. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 205 . Anyone who has ever C. i.3 Example applications better than its programmer.2 The car in the pit Let us take a look at a car parking on a one-dimensional road at the bottom of a deep pit without being able to get over the slope on both sides straight away by means of its engine power in order to leave D. a) − Q(st . C. learning is: Π can be initialized arbitrar.dkriesel. the state-value functions cannot be computed explicitly (parDefinition C.3 Example applications @ a aτ −2 a a GFED @ABC @ABC @ABC G ONML HIJK @ABC sτ −1 l τ −1 G GFED s0 hk 0 G GFED s1 k 1 G GFED sτ ··· k r1 r2 rτ −1 rτ direction of reward direction of actions Figure C.13 (Q learning). actions and situations beginning with 0 (This has simply been adopted as a convention).1 TD gammon TD gammon is a very successful backgammon game based on TD learning invented by Gerald Tesauro.com C.15) same time the reward is the return. then against an entity of itself). tions). a) (C. Attention should be paid to numbering: Rewards are numbered beginning with 1.3.
Only these two More difficult for the system is the folactions can be performed. there are maximum values and minimum values x can adopt. In to both sides. On the top of this car is hangs down. The pole is built in such a the literature this task is called swing up way that it always tips over to one side so an inverted pendulum. This is achieved best by an avoidchoice for awarding the reward so that the ance strategy: As long as the pole is balsystem learns fast how to leave the pit and anced the reward is 0. 206 D.Appendix C Excursus: reinforcement learning the pit. to prevent the pole from tipping Here.3. Furthermore. If the pole tips over. The pole balancer was developed by Barto. Our one-dimensional world is limited. the pole will tip over).e. it never stands still (let us assume that the pole is rounded at the lower end). standing still lowing initial situation: the pole initially is impossible. "everything costs" would be a good over. table since the state space is hard to dis. So the system will slowly build up Interestingly.At this the system mostly is in the cencretize. dkriesel. to keep the pole balanced by tilting it sufThe policy can no longer be stored as a ficiently fast and with small movements. Sutton and Anderson.3.3 The pole balancer C. Trivially. the system is soon capable the movement. The aim of our system is to learn to steer the car in such a way that it can balance "full reverse" and "doing nothing". by means of mere forward directed engine power. the executable actions here are the possibilities to drive forwards and backwards. The intuitive solution we think of immediately is to move backwards. the vehicle always has a fixed position x an our one-dimensional world and a velocity of x ˙ . realizes that our problem cannot be solved the reward is -1.3. the pole. The actions of a reinforcement learning system would be "full throttle forward".1 Swinging up an inverted pendulum Let be given a situation including a vehicle that is capable to move either to the right at full throttle or to the left at full throttle (bang bang control).com The angle of the pole relative to the vertical line is referred to as α. As policy a function has to be ter of the space since this is farthest from generated. the walls which it understands as negative (if it touches the wall. to gain momentum at the opposite slope and oscillate in this way several times to dash out of the pit. has to be swung up over the hinged an upright pole that could tip over vehicle and finally has to be stabilized. i. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . C.
problems of informatics which could be But not every problem is that easily solved solved efficiently by means of reinforcelike our gridworld: In our backgammon ex. Here. we have to find approximators for these functions. ton and Anderson to control the pole There is often something in between. Exercises Exercise 19. Please give reasons for ample we have approx.ment learning. this does not mean that they have been proposed by Barto.obstacles and at any time knows its posiready been introduced to supervised and tion (x. And which learning approximators for these reinforcement learning components come immediately into our mind? Exactly: neural networks. What could an appropriate statevalue function look like? How would you generate an appropriate reward? C. We have al. Problems Bibliography: [BSA83].4 Reinforcement learning in connection with neural networks Finally. kind of criticism or school mark. unsupervised learning procedures.dkriesel. some balancer. let alone other games. Although we do not always have an om.com C. 1020 situations and your answers. Assume that the robot is capable to avoid The answer is very simple. Describe the function of niscient teacher who makes unsupervised the two components ASE and ACE as learning possible.and action-value functions. the reader would like to ask why a text on "neural networks" includes a chapter about reinforcement learning. Indicate several "classical" forcement learning. y ) and orientation φ. Sutwe do not receive any feedback at all. the situation tree has a large branching factor.4 Reinforcement learning in connection with neural networks ment learning to find a strategy in order to exit a maze as fast as possible. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 207 . Thus. the tables used in the gridworld can no longer be realized as state. like this can be solved by means of reinExercise 21.Exercise 20. A robot control system shall be persuaded by means of reinforce- D.
.
IEEE Transactions on Information Theory. R.A. Computer Society Press Technology Series Neural Networks. and Cybernetics. 1987. 1967. Oregon Convention Center. and R.E. Barto. 1972.O. Spektrum. ART 3: Hierarchical search using chemical transmitters in self-organising pattern recognition architectures. Grossberg. Wiley New York. 13(1):21–27. Applied Optics. Cover and P. Portland: World Congress on Neural Networks. IEEE Transactions on Systems. 1988.A. Mathematical Biosciences. Portland. Absolute stability of global pattern formation and parallel memory storage by competitive neural networks. 1990. 2(4):303–314. 1993. Grossberg. A simple neural network generating an interactive memory. Cohen and S. D. Akademischer Verlag. Sutton. Hart. ART2: Self-organization of stable category recognition codes for analog input patterns. Stork. Nearest neighbor pattern classification. [BSA83] [CG87] [CG88] [CG90] [CH67] [CR00] [Cyb89] [DHS01] 209 . G. 1989. 2000. Pattern classification. G. Anderson. R. and C. Campbell and JB Reece. 13(5):834–846. A. Neuron-like adaptive elements that can solve difficult learning control problems. Man. Parodi. Signals. Grossberg.G. 14:197–220. G. and D. and Systems (MCSS). Zunino. G. Hart. A. Cybenko. P. 3(2):129–152. Anderson. Neural Networks. Carpenter and S. Mathematics of Control.Bibliography [And72] [APZ93] James A. Speed improvement of the backpropagation on current-generation workstations. A. Duda. 2001. Carpenter and S. September 1983. N. Biologie. July 11-15. 26:4919– 4930. In WCNN’93. T. pages 70–81. Approximation by superpositions of a sigmoidal function. volume 1. Oregon. 1993. M. Anguita. Lawrence Erlbaum.
Proceedings. 23:121–134. JJ Hopfield. pages 3895–3902. 79:2554–2558. S.com Jeffrey L. M. N. Hopfield. Neurons with graded response have collective computational properties like those of two-state neurons. 14(2):179– 211. Adaptive pattern classification and universal recoding. I. Self organized partitioning of chaotic attractors for control. Classification using multi-soms and multi-neural gas. JJ Hopfield and DW Tank. Finding structure in time. Jordan. Ito. Hebb. 52(3):141–152. F. Neocognitron: A neural network model for a mechanism of visual pattern recognition. New York. 2006. S. Kintzler. Fast learning with incremental RBF networks. Fahlman. In IJCNN. Grossberg. N. Donald O. [Fri94] [GKE01a] [GKE01b] [Gro76] [GS06] [Heb49] [Hop82] [Hop84] [HT85] [Jor86] 210 D. Nils Goerke and Alexandra Scherbart. and R. 81(10):3088–3092. IEEE Transactions on Systems. 1985. Erlbaum. Biological cybernetics. Attractor dynamics and parallelism in a connectionist sequential machine. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . 1982. Neural Processing Letters. USA. and R. Cognitive Science. 1(1):2–5. 1984. 1976. B. Proc. Fukushima. Eckmiller. Proceedings of the National Academy of Sciences. IJCNN’01. 13(5):826–834. Eckmiller. Elman. Neural networks and physical systems with emergent collective computational abilities. Goerke. Miyake. I: Parallel development and coding of neural feature detectors. April 1990. 2001. Lecture notes in computer science. Fritzke. E. pages 851–856. Biological Cybernetics. In Neural Networks. An empirical sudy of learning speed in back-propagation networks. Technical Report CMU-CS-88-162. The Organization of Behavior: A Neuropsychological Theory. volume 3. K. John J. 1986. CMU. 2001. of the National Academy of Science. 2001. S. F. 1994. International Joint Conference on. 1949. Kintzler. pages 531–546. In Proceedings of the Eighth Conference of the Cognitive Science Society. Man. and Cybernetics. Goerke. September/October 1983. and T.Bibliography [Elm90] [Fah88] [FMI83] dkriesel. Self organized classification of chaotic domains from a nonlinearattractor. Wiley. 1988. Neural computation of decisions in optimization problems.
C-21:353–359. 4(4):558–569. New York. E. 1986. Optimal brain damage.C. Vol. Parallel Distributed Processing: Explorations in the Microstructure of Cognition. IEEEtC. Kaufman. B. Y. and S. In D. 1. 1972. Solla. Rumelhart. 5(4):115–133. 21(1-3):1–6. Busse. 1967. J. Mass. Touretzky. Denker. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 211 . le Cun. McCulloch and W. and S. N. 2000. L. Appleton & Lange. third edition.M. on Neural Networks. Teuvo Kohonen. [Koh72] [Koh82] [Koh89] [Koh98] [KSJ00] [lCDS90] [Mac67] [MBS93] [MBW+ 10] K. Statistics and Probability.D. N. ’Neural-gas’ network for vector quantization and its application to timeseries prediction. Kohonen. Berlin. J. D. Papert. Advances in Neural Information Processing Systems 2. McClelland and D.S. T.dkriesel. Micheva. Cambridge. S. In Finding Groups in Data: An Introduction to Cluster Analysis. Jessell. 1982. Kandel. 68(4):639–653. Morgan Kaufmann. Weiler. Self-organized formation of topologically correct feature maps. pages 281–296. Berkovich. and Klaus J. 1990. 1990.R. Smith. Teuvo Kohonen. [MP43] [MP69] [MR86] W. Thomas M. 2010. IEEE Trans. O’Rourke. Schulten. Self-Organization and Associative Memory. MacQueen. Some methods for classification and analysis of multivariate observations. Correlation matrix memories. Bulletin of Mathematical Biology.J.com [Kau90] Bibliography L. editor. Wiley. Finding groups in data: an introduction to cluster analysis. MIT Press. SpringerVerlag. and T. pages 598–605. J. Cambridge. T. volume 2. 1969. 1993. Martinetz. Biological Cybernetics. 43:59–69. J. Perceptrons. Principles of neural science. Neuron. Kohonen. The self-organizing map. Neurocomputing. Singlesynapse analysis of a diverse synapse population: proteomic imaging methods and markers. 1998. M. Pitts. A logical calculus of the ideas immanent in nervous activity. Schwartz. 1943. Stanislav G. E. 1989.H. Minsky and S. In Proceedings of the Fifth Berkeley Symposium on Mathematics. A. MIT Press.
Williams.. Poggio and F. McCulloch. Rosenblatt. Rosenblatt. Prechelt. McClelland. Spartan. Cambridge Mass. Pitts and W. [PG89] [Pin87] [PM47] [Pre94] [RB93] [RD05] [RHW86a] D. and second order hebbian learning. Nature. How we know universals the perception of auditory and visual forms.. 1947. G. Reinforcement Learning: An Introduction. 1962. Learning representations by back-propagating errors. Learning internal representations by error propagation. G. editors. Rumelhart. Dicke. pages 586–591. 9(3):127–147. 1986. 1989. F. pages II–593–II–600. Rprop . second order direct propagation. Williams. IEEE First International Conference on Neural Networks (ICNN’87). Proben1: A set of neural network benchmark problems and benchmarking rules. Roth and U. CA. Technical Report. [Ros62] [SB98] 212 D. F. and R. MIT Press. Pineda. 9(5):250–257. L. Optimal algorithms for adaptive networks: Second order back propagation. Braun. MIT Press. W. In D. L. Rumelhart. IEEE International Conference on. 1998. J. Psychological Review. Hinton. 2005. Parallel distributed processing: Explorations in the microstructure of cognition. M. 1958. Geoffrey E. T. 1993. IEEE.. Girosi. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . In Maureen Caudill and Charles Butler. [RHW86b] David E. 1994. J. The perceptron: a probabilistic model for information storage and organization in the brain. San Diego. Bulletin of Mathematical Biology. [Rie94] [Ros58] M. and R. 59:2229–2232. E. A theory of networks for approximation and learning. IEEE. Sutton and A. Parker. A direct adaptive method for faster backpropagation learning: The rprop algorithm.description and implementation details. June 1987. University of Karlsruhe. Hinton.S. 1987. Volume 1: Foundations. Barto. Cambridge. In Neural Networks. MA. New York. 21:94. and the PDP research group. Evolution of the brain and intelligence. October 1986. Technical report. 1994. Rumelhart. J. editors. volume II. MIT Press. S. G. Physical Review Letters. 323:533–536. Trends in Cognitive Sciences.Bibliography [Par87] dkriesel.com David R. Principles of Neurodynamics. Riedmiller. Generalization of back-propagation to recurrent neural networks. Riedmiller and H. F. R. 1993. 65:386–408.
1988. Goerke. Simulation Neuronaler Netze. P. Nils Goerke. Neural Computing Theory and Practice. P. E.com [SG06] [SGE05] Bibliography A. Adaptive switching circuits. and Petra Perner. pages 343–353. 1960. 1989. Unsupervised system for discovering patterns in time-series. Kybernetik (Biological Cybernetics). [Ste61] [vdM73] [Was89] [Wer74] [Wer88] [WG94] [WH60] [Wid89] [Zel94] D. 1974. Andreas Zell. San Diego. B. editors. 1989.A. ICAPR (2). Kybernetik. Widrow and M. German. Regional and online learnable fields. D. and Rolf Eckmiller. Single-stage logic. 1961. Werbos. Hoff. AddisonWesley. Theory and Practice. PhD thesis. Van Nostrand Reinhold. Backpropagation: Past and future. Scherbart and N. Wasserman. Springer. Gershenfeld. Self-organizing of orientation sensitive cells in striate cortex. Steinbuch. 1973. Time series prediction. Wasserman. 1994. In Proceedings WESCON. Die lernmatrix. Harvard University.dkriesel. Addison-Wesley. Weigend and N. K. P. pages 96–104. 14:85–100. In Sameer Singh. 1:36–45. Rolf Schatten. 1994. Neural Computing. A. P. Werbos. J. Widner. 2005. Chidanand Apté. In Proceedings ICNN-88. Maneesha Singh. 1960. pages 74–83. volume 3687 of Lecture Notes in Computer Science. C. Beyond Regression: New Tools for Prediction and Analysis in the Behavioral Sciences. R. 2006. J. von der Malsburg. AIEE Fall General Meeting.S. New York : Van Nostrand Reinhold. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 213 .
.
. . . . . . . . . . . . . . . Biological neuron . . . . . . . . . .4 Robot with 8 sensors and 2 motors . . . . . . . . . . . . . . . . . . . . .2 4. . . . 6 7 8 9 14 15 17 22 27 35 38 40 41 41 42 43 44 45 46 56 60 62 63 65 65 72 74 74 75 Data processing of a neuron . . . . . . . . . . . . . . . Black box with eight inputs and two outputs Learning samples for the example robot . . .3 2. . . . .3 1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 5. . . .1 4. . .2 3. . . . Compound eye . . . . . . . . . . .1 1. . . . . . . . . . . The perceptron in three different views . . . . . . . . . . . .5 3. . . . . . . . . . . . . . . . . . . . . .3 3. . .5 3. . . . . . . . . . . . . . . . . . . . . . . . . . 215 . . . . . . . . . . . . . . . . Singlelayer perceptron with several output AND and OR singlelayer perceptron . .2 5. . . . . . . . . . . . . . . . . . .7 3. . . . . . . . . . Possible errors during a gradient descent The 2-spiral problem . . . . . . . . .2 2. . . Examples for different types of neurons . . . . . . . . . . . Laterally recurrent network . . . . . . . . . Example network with and without bias neuron Training samples and network capacities Learning curve with different scalings . . . .4 4. . . . . . . Gradient descent. . . . . . . . . Feedforward network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 2. . . . . . . . . . . . . . . . . . . . Institutions of the field of neural networks . . . . . . . . . . . . . . . . neurons . . . . . . . . . Action potential . Feedforward network with shortcuts . . . . . . . . . .1 3. . .4 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 4. . . . . . . . . . . . . 2D visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Indirectly recurrent network . . . . . . . Singlelayer perceptron . . . . . . . . . . . . . . . . . . Central nervous system Brain . .3 5.1 2. . . . . Checkerboard problem . Directly recurrent network . . . .4 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 4.List of Figures 1. . . . . . Completely linked network . . . . . .2 1. . . .6 3. . . . . .1 5. . . . . . . . . . . . . . . . . . Various popular activation functions . . . . . . . . . . . .10 3. . . . . . . . . . . . . . . . . . . . . . . . .8 3. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . Position of an inner neuron for derivation of backpropagation Illustration of the backpropagation derivation . . . . . . . . . . uneven coverage of an input space with radial basis functions Roessler attractor . . . . . . . . Two-dimensional linear separation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Sketch of a XOR-SLP . . . Accumulating Gaussian bells in one-dimensional space . . . . . . . . . . . . . . . . . .4 8. . . . . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . . . . . . . . . . . . . . . . Accumulating Gaussian bells in two-dimensional space . .3 10. . . . . . . . Momentum term .1 10. .2 10. . .3 7. Multilayer perceptrons and output sets . . . . . . . . . . . . . . . . . . . . . . . . . . .14 5. . . . . .11 5. . . . . . . . . . . . . . .15 6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 216 D. . . . . 156 Training a SOM with one-dimensional topology . . . Unfolding in time . . . . . . . . . . . . dkriesel. . . . .8 Error surface of a network with 2 connections . .1 10. . . . . . . . . . . . . . .com . . . . . . . . 154 Topological defect of a SOM . . . . . . . . . . . . . . . . . . . . . . .9 5. . . . .13 5. . . .1 6. . . . . . . . . . . . . . . . . . . . . . . . Elman network . . Even coverage of an input space with radial basis functions . . Convergence of a Hopfield network Fermi function . Three-dimensional linear separation . . . . . . . . . 151 SOM topology functions . . . . . . . . . . . . . . .2 7. . . . . . . . . . . .1 7. . . . . . . . . . . . . . . 148 Example distances of SOM topologies . . . . . . . . . . . . . . . . . Distance function in the RBF network . . . 157 SOMs with one. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .List of Figures 5.2 6.6 6. . . . . . . . . . Individual Gaussian bells in one. . . . . . . . 153 First example of a SOM . .10 5. . . . Hopfield network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 82 82 83 84 85 87 89 97 102 103 107 108 109 109 110 116 117 117 122 123 124 126 130 132 134 137 RBF network . . . . . . . . . . . . . . . Binary threshold function . . . . . Examples for quantization . .5 6.3 6. . . . . . . . . . . . . . . . . . . . . . . . .6 5. . Uneven coverage of an input space with radial basis functions . . . . . . . . . . . . . 141 Example topologies of a SOM . . . . . . . . . . .12 5. . .3 8. . .5 5. . . . . . . . . . . . . . . Fermi function and hyperbolic tangent . . . . .and two-dimensional topologies and different input spaces158 Resolution optimization of a SOM to certain areas . . . . . . . . . . . . .7 6. . . . . . . . . . . . . . . . Random. . . . .6 10.1 8. . . .8 7. . . . . . . . . . Functionality of 8-2-8 encoding .4 9. . . .and two-dimensional space . . The XOR network . . . .2 8.5 10. . . . . . . . . . . . . . . . . .4 6. . .8 5. . . . . . . . . . . . Jordan network . .7 5. . . . . .4 10. . . . . .7 10. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . 179 B. . . . . .dkriesel. . . . . . . .com List of Figures 10. . . . .4 C. . . . 176 A. . . . . . . . . . . . . .6 C. . . . . . . . . . . . . . . . .3 C. . . . . .2 C. . . . . Heterogeneous one-step-ahead prediction Heterogeneous one-step-ahead prediction Gridworld . . . .6 C. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 217 . . . . . . . . . . . . . . .4 B. 166 11. . . .9 Neural network reading time series . . . . . . . Two-step-ahead prediction . . . . . . . . . . . . . .5 B. . . . . . . two outputs . . . . . . . . . . Reinforcement learning timeline . . . . . . . . . . . . . . The Monte Carlo method . . . . . . . . . . . . . . . . . . . . .3 Clustering by means of a ROLF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 Learning process of an ART network . . . . . . . . . . . . . . . . .1 Comparing cluster analysis methods . . . . . .8 C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 C. . . . . . . . . . . . . . . . . . . . Extended Monte Carlo method Improving the policy . One-step-ahead prediction . . . . . . . .3 B. . . . . . . . . . . . . . . . . . . . . . Gridworld with optimal returns Reinforcement learning cycle . .9 Shape to be classified by neural gas . . . . . . . . . . . . . . . . . . . . . . Direct two-step-ahead prediction . with . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2 ROLF neuron . . 168 A. . . . . . . 182 184 186 186 188 188 193 193 200 201 202 203 203 204 205 D. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 C. . . . . . . . 162 11. . 174 A. . . . . . . . . . . . . . . . . .1 B. . Action-value function . . . . . . . . . . . Reinforcement learning . . . .7 C.2 B. . .1 Structure of an ART network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
.
. . . . . . . 138 bias neuron . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18. . . . . . . . . . . . . . . . 28 approximation. . see adaptive linear neuron adaptive linear neuron . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 of a SOM neuron . . . . . . . . . . . . . . . . . . . 168 ART-3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 autoassociator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 B backpropagation . 44 binary threshold function . . . see adaptive linear neuron adaptive linear element . . . . . . . 5 ATP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .84 recurrent . . . . . . . . 195 action-value function . . . . . 37 bipolar cell . . . 36 activation function . . 23 A Action . . . . . . . . . . . . . . . . . . . . . . . . see adaptive resonance theory ART-2 . . . . . . . . . 98 ADALINE . . . . . . . 4 center of a ROLF neuron . . . . . . . . . . 146 219 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .110 ART . . . . . . . . 203 activation . . . . . . . . . . . . . . . . . . . . . 20 attractor . . . . 165 agent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 algorithm. . . . . . . . 36 selection of . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 brainstem . . 14 basis . . . . . . . . . . . 16 C capability to learn . . . 167 ART-2A . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 artificial intelligence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 second order . . . . . . . . . . . . . . . . . . . 10 adaptive resonance theory . . . . . . . . . 195 action potential . . . . . . . . . . . . . . . . . . . .50 amacrine cell . . . . . . . . . . . . . . . . . . . 21 action space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 brain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 black box . . . . . . . . .Index * 100-step rule . . . . . . 10 associative data storage . . . . . . . . . . . . . 95 backpropagation of error. . . . . . 131 axon . . . . . . . . . . . . . . . . 11. . . . . .
196 epoch . . . . . . . . . . . . .39 Fermi function . . . . . . . . . . . . . . . . . . . . 75 specific . . . . . . . . . . . . . . . . . . . 21 diencephalon . . . . . 37 flat spot elimination . . . . . .34 context-based search . . . . . . . . . . . . . . . . . . . . . . . . . 18 depolarization . . . . 138. . . . . . . . . . .76. . . . . . . . . . . . 14 cerebrum . . . . . . . . . 53 evolutionary algorithms . . . . . . . . . . . . . . 93. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 cortical field . . . . . . . . . 56. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . see quantization distance Euclidean . . . . . . . . . 197 exploration approach . . . . . . . . . . . . . . . 19 cone function . . . . . . . . . 79 dendrite . . 56 total . . . . 137 discretization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 cerebellum . . . . . . . . . . . . . . . . 119 E early stopping . . . . . . . . . . . . 18 tree . . . . . . . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . . . . . . . . . . . . . . . . . . . . . . . .39 compound eye . . . . . . . . . . 171 dynamical system . . . . . . . 171 squared. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 episode . . . . . . . . . . . . . . . . . . . . . . 104 distance to the . . . . . . . . 15 cerebral cortex . . . . . . . . . . . . 47 fault tolerance . . . . 172 complete linkage. .com digitization . . . . . . see error vector digital filter . . . .Index of an RBF neuron . 9 Elman network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 F fastprop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 epsilon-nearest neighboring . . . . . . . . . . . . . . . . . 197 exteroceptor . . . . . . . . . . . . . . 107 central nervous system . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 error vector . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 exploitation approach . . . . . . . . . . 171 CNS . . . . . . . . . . . . 95 220 D. . . . . . . . 150 dkriesel. . . . . . . . . . 173 error specific . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . see central nervous system codebook vector . . . . . . . . . . . . . . see interbrain difference vector . . . 137 cortex . . . see cerebral cortex visual . . . . . . . . . . . . . . . 26 concentration gradient . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 cylinder function . . . . . . . . . . . . . . . . . . . . . . . . . . 171 clusters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 primary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 electronic brain . . . . . . . . . . . . . . . . 150 connection. . . . . . . . . . . 157 continuous . . . . . 24 D Dartmouth Summer Research Project9 deep networks . . . . . . . . . . . . . . . . 14 change in weight. . . . . . . . . . . . 121 environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 discrete . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 feedforward. 79 delta rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 association . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .64 cluster analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 Delta . . . . . . . . . . . . . . . . 56 error function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
dkriesel.com fudging . . . . . . . see flat spot elimination function approximation . . . . . . . . . . . . . 98 function approximator universal . . . . . . . . . . . . . . . . . . . . . . . 82
Index
I
individual eye . . . . . . . . see ommatidium input dimension . . . . . . . . . . . . . . . . . . . . 48 input patterns . . . . . . . . . . . . . . . . . . . . . . 50 input vector . . . . . . . . . . . . . . . . . . . . . . . . 48 interbrain . . . . . . . . . . . . . . . . . . . . . . . . . . 15 internodes . . . . . . . . . . . . . . . . . . . . . . . . . . 23 interoceptor . . . . . . . . . . . . . . . . . . . . . . . . 24 interpolation precise . . . . . . . . . . . . . . . . . . . . . . . . 110 ion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 iris . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
G
ganglion cell . . . . . . . . . . . . . . . . . . . . . . . . 27 Gauss-Markov model . . . . . . . . . . . . . . 111 Gaussian bell . . . . . . . . . . . . . . . . . . . . . . 149 generalization . . . . . . . . . . . . . . . . . . . . 4, 49 glial cell . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 gradient . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 gradient descent . . . . . . . . . . . . . . . . . . . . 59 problems . . . . . . . . . . . . . . . . . . . . . . . 60 grid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 gridworld. . . . . . . . . . . . . . . . . . . . . . . . . .192
J
Jordan network. . . . . . . . . . . . . . . . . . . .120
H
Heaviside function see binary threshold function Hebbian rule . . . . . . . . . . . . . . . . . . . . . . . 64 generalized form . . . . . . . . . . . . . . . . 65 heteroassociator . . . . . . . . . . . . . . . . . . . 132 Hinton diagram . . . . . . . . . . . . . . . . . . . . 34 history of development. . . . . . . . . . . . . . .8 Hopfield networks . . . . . . . . . . . . . . . . . 127 continuous . . . . . . . . . . . . . . . . . . . . 134 horizontal cell . . . . . . . . . . . . . . . . . . . . . . 28 hyperbolic tangent . . . . . . . . . . . . . . . . . 37 hyperpolarization . . . . . . . . . . . . . . . . . . . 21 hypothalamus . . . . . . . . . . . . . . . . . . . . . . 15
K
k-means clustering . . . . . . . . . . . . . . . . 172 k-nearest neighboring. . . . . . . . . . . . . .172
L
layer hidden . . . . . . . . . . . . . . . . . . . . . . . . . 39 input . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 output . . . . . . . . . . . . . . . . . . . . . . . . . 39 learnability . . . . . . . . . . . . . . . . . . . . . . . . . 97 learning
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
221
Index batch . . . . . . . . . . see learning, offline offline . . . . . . . . . . . . . . . . . . . . . . . . . . 52 online . . . . . . . . . . . . . . . . . . . . . . . . . . 52 reinforcement . . . . . . . . . . . . . . . . . . 51 supervised. . . . . . . . . . . . . . . . . . . . . .51 unsupervised . . . . . . . . . . . . . . . . . . . 50 learning rate . . . . . . . . . . . . . . . . . . . . . . . 89 variable . . . . . . . . . . . . . . . . . . . . . . . . 90 learning strategy . . . . . . . . . . . . . . . . . . . 39 learning vector quantization . . . . . . . 137 lens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 linear separability . . . . . . . . . . . . . . . . . . 81 linearer associator . . . . . . . . . . . . . . . . . . 11 locked-in syndrome . . . . . . . . . . . . . . . . . 16 logistic function . . . . see Fermi function temperature parameter . . . . . . . . . 37 LVQ . . see learning vector quantization LVQ1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 LVQ2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140 LVQ3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
dkriesel.com S . . . . . . . . . . . . . . see situation space T . . . . . . see temperature parameter ∗ (s) . . . . . see state-value function, VΠ optimal VΠ (s) . . . . . see state-value function W . . . . . . . . . . . . . . see weight matrix ∆wi,j . . . . . . . . see change in weight Π . . . . . . . . . . . . . . . . . . . . . . . see policy Θ . . . . . . . . . . . . . . see threshold value α . . . . . . . . . . . . . . . . . . see momentum β . . . . . . . . . . . . . . . . see weight decay δ . . . . . . . . . . . . . . . . . . . . . . . . see Delta η . . . . . . . . . . . . . . . . . see learning rate η ↑ . . . . . . . . . . . . . . . . . . . . . . see Rprop η ↓ . . . . . . . . . . . . . . . . . . . . . . see Rprop ηmax . . . . . . . . . . . . . . . . . . . . see Rprop ηmin . . . . . . . . . . . . . . . . . . . . see Rprop ηi,j . . . . . . . . . . . . . . . . . . . . . see Rprop ∇ . . . . . . . . . . . . . . see nabla operator ρ . . . . . . . . . . . . . see radius multiplier Err . . . . . . . . . . . . . . . . see error, total Err(W ) . . . . . . . . . see error function Errp . . . . . . . . . . . . . see error, specific Errp (W ) see error function, specific ErrWD . . . . . . . . . . . see weight decay at . . . . . . . . . . . . . . . . . . . . . . see action c . . . . . . . . . . . . . . . . . . . . . . . . see center of an RBF neuron, see neuron, self-organizing map, center m . . . . . . . . . . . see output dimension n . . . . . . . . . . . . . see input dimension p . . . . . . . . . . . . . see training pattern rh . . . see center of an RBF neuron, distance to the rt . . . . . . . . . . . . . . . . . . . . . . see reward st . . . . . . . . . . . . . . . . . . . . see situation t . . . . . . . . . . . . . . . see teaching input wi,j . . . . . . . . . . . . . . . . . . . . see weight x . . . . . . . . . . . . . . . . . see input vector y . . . . . . . . . . . . . . . . see output vector
M
M-SOM . see self-organizing map, multi Mark I perceptron . . . . . . . . . . . . . . . . . . 10 Mathematical Symbols (t) . . . . . . . . . . . . . . . see time concept A(S ) . . . . . . . . . . . . . see action space Ep . . . . . . . . . . . . . . . . see error vector G . . . . . . . . . . . . . . . . . . . . see topology N . . see self-organizing map, input dimension P . . . . . . . . . . . . . . . . . see training set Q∗ Π (s, a) . see action-value function, optimal QΠ (s, a) . see action-value function Rt . . . . . . . . . . . . . . . . . . . . . . see return
222
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
dkriesel.com fact . . . . . . . . see activation function fout . . . . . . . . . . . see output function membrane . . . . . . . . . . . . . . . . . . . . . . . . . . 19 -potential . . . . . . . . . . . . . . . . . . . . . . 19 memorized . . . . . . . . . . . . . . . . . . . . . . . . . 54 metric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 Mexican hat function . . . . . . . . . . . . . . 150 MLP. . . . . . . . see perceptron, multilayer momentum . . . . . . . . . . . . . . . . . . . . . . . . . 94 momentum term. . . . . . . . . . . . . . . . . . . .94 Monte Carlo method . . . . . . . . . . . . . . 201 Moore-Penrose pseudo inverse . . . . . 110 moving average procedure . . . . . . . . . 184 myelin sheath . . . . . . . . . . . . . . . . . . . . . . 23
Index self-organizing map. . . . . . . . . . . .146 tanh . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 winner . . . . . . . . . . . . . . . . . . . . . . . . 148 neuron layers . . . . . . . . . . . . . . . . . see layer neurotransmitters . . . . . . . . . . . . . . . . . . 17 nodes of Ranvier . . . . . . . . . . . . . . . . . . . 23
O
oligodendrocytes . . . . . . . . . . . . . . . . . . . 23 OLVQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 on-neuron . . . . . . . . . . . . . see bias neuron one-step-ahead prediction . . . . . . . . . 183 heterogeneous . . . . . . . . . . . . . . . . . 187 open loop learning. . . . . . . . . . . . . . . . .125 optimal brain damage . . . . . . . . . . . . . . 96 order of activation . . . . . . . . . . . . . . . . . . 45 asynchronous fixed order . . . . . . . . . . . . . . . . . . . 47 random order . . . . . . . . . . . . . . . . 46 randomly permuted order . . . . 46 topological order . . . . . . . . . . . . . 47 synchronous . . . . . . . . . . . . . . . . . . . . 46 output dimension . . . . . . . . . . . . . . . . . . . 48 output function. . . . . . . . . . . . . . . . . . . . .38 output vector . . . . . . . . . . . . . . . . . . . . . . . 48
N
nabla operator. . . . . . . . . . . . . . . . . . . . . .59 Neocognitron . . . . . . . . . . . . . . . . . . . . . . . 12 nervous system . . . . . . . . . . . . . . . . . . . . . 13 network input . . . . . . . . . . . . . . . . . . . . . . 35 neural gas . . . . . . . . . . . . . . . . . . . . . . . . . 159 growing . . . . . . . . . . . . . . . . . . . . . . . 162 multi- . . . . . . . . . . . . . . . . . . . . . . . . . 161 neural network . . . . . . . . . . . . . . . . . . . . . 34 recurrent . . . . . . . . . . . . . . . . . . . . . . 119 neuron . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 accepting . . . . . . . . . . . . . . . . . . . . . 177 binary. . . . . . . . . . . . . . . . . . . . . . . . . .71 context. . . . . . . . . . . . . . . . . . . . . . . .120 Fermi . . . . . . . . . . . . . . . . . . . . . . . . . . 71 identity . . . . . . . . . . . . . . . . . . . . . . . . 71 information processing . . . . . . . . . 71 input . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 RBF . . . . . . . . . . . . . . . . . . . . . . . . . . 104 output . . . . . . . . . . . . . . . . . . . . . . 104 ROLF. . . . . . . . . . . . . . . . . . . . . . . . .176
P
parallelism . . . . . . . . . . . . . . . . . . . . . . . . . . 5 pattern . . . . . . . . . . . see training pattern pattern recognition . . . . . . . . . . . . 98, 131 perceptron . . . . . . . . . . . . . . . . . . . . . . . . . 71 multilayer . . . . . . . . . . . . . . . . . . . . . . 82 recurrent . . . . . . . . . . . . . . . . . . . . 119
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
223
Index singlelayer . . . . . . . . . . . . . . . . . . . . . . 72 perceptron convergence theorem . . . . 73 perceptron learning algorithm . . . . . . 73 period . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 peripheral nervous system . . . . . . . . . . 13 Persons Anderson . . . . . . . . . . . . . . . . . . . . 206 f. Anderson, James A. . . . . . . . . . . . . 11 Anguita . . . . . . . . . . . . . . . . . . . . . . . . 37 Barto . . . . . . . . . . . . . . . . . . . 191, 206 f. Carpenter, Gail . . . . . . . . . . . . 11, 165 Elman . . . . . . . . . . . . . . . . . . . . . . . . 120 Fukushima . . . . . . . . . . . . . . . . . . . . . 12 Girosi . . . . . . . . . . . . . . . . . . . . . . . . . 103 Grossberg, Stephen . . . . . . . . 11, 165 Hebb, Donald O. . . . . . . . . . . . . 9, 64 Hinton . . . . . . . . . . . . . . . . . . . . . . . . . 12 Hoff, Marcian E. . . . . . . . . . . . . . . . 10 Hopfield, John . . . . . . . . . . . 11 f., 127 Ito . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Jordan . . . . . . . . . . . . . . . . . . . . . . . . 120 Kohonen, Teuvo . 11, 137, 145, 157 Lashley, Karl . . . . . . . . . . . . . . . . . . . . 9 MacQueen, J. . . . . . . . . . . . . . . . . . 172 Martinetz, Thomas . . . . . . . . . . . . 159 McCulloch, Warren . . . . . . . . . . . . 8 f. Minsky, Marvin . . . . . . . . . . . . . . . . 9 f. Miyake . . . . . . . . . . . . . . . . . . . . . . . . . 12 Nilsson, Nils. . . . . . . . . . . . . . . . . . . .10 Papert, Seymour . . . . . . . . . . . . . . . 10 Parker, David . . . . . . . . . . . . . . . . . . 95 Pitts, Walter . . . . . . . . . . . . . . . . . . . 8 f. Poggio . . . . . . . . . . . . . . . . . . . . . . . . 103 Pythagoras . . . . . . . . . . . . . . . . . . . . . 56 Riedmiller, Martin . . . . . . . . . . . . . 90 Rosenblatt, Frank . . . . . . . . . . 10, 69 Rumelhart . . . . . . . . . . . . . . . . . . . . . 12 Steinbuch, Karl . . . . . . . . . . . . . . . . 10 Sutton . . . . . . . . . . . . . . . . . . 191, 206 f. Tesauro, Gerald . . . . . . . . . . . . . . . 205
dkriesel.com von der Malsburg, Christoph . . . 11 Werbos, Paul . . . . . . . . . . . 11, 84, 96 Widrow, Bernard . . . . . . . . . . . . . . . 10 Wightman, Charles . . . . . . . . . . . . . 10 Williams . . . . . . . . . . . . . . . . . . . . . . . 12 Zuse, Konrad . . . . . . . . . . . . . . . . . . . . 9 pinhole eye . . . . . . . . . . . . . . . . . . . . . . . . . 26 PNS . . . . see peripheral nervous system pole balancer . . . . . . . . . . . . . . . . . . . . . . 206 policy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 closed loop . . . . . . . . . . . . . . . . . . . . 197 evaluation . . . . . . . . . . . . . . . . . . . . . 200 greedy . . . . . . . . . . . . . . . . . . . . . . . . 197 improvement . . . . . . . . . . . . . . . . . . 200 open loop . . . . . . . . . . . . . . . . . . . . . 197 pons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 propagation function . . . . . . . . . . . . . . . 35 pruning . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 pupil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Q
Q learning . . . . . . . . . . . . . . . . . . . . . . . . 204 quantization . . . . . . . . . . . . . . . . . . . . . . . 137 quickpropagation . . . . . . . . . . . . . . . . . . . 95
R
RBF network. . . . . . . . . . . . . . . . . . . . . .104 growing . . . . . . . . . . . . . . . . . . . . . . . 115 receptive field . . . . . . . . . . . . . . . . . . . . . . 27 receptor cell . . . . . . . . . . . . . . . . . . . . . . . . 24 photo-. . . . . . . . . . . . . . . . . . . . . . . . . .27 primary . . . . . . . . . . . . . . . . . . . . . . . . 24 secondary . . . . . . . . . . . . . . . . . . . . . . 24
224
D. Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN)
. . . . . . . . . . . . . . . . . . . . 183 state-value function . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . 11 self-organizing map . . . . 18 spin . . 23 self-fulfilling prophecy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 D. . . . . . . . . . . 97 resilient backpropagation . . . . . . . . . . . . . . . . . . . . . . . . . 34 TD gammon . . . . 27. . . . . . . . . . . . . . . 23 regional and online learnable fields 175 reinforcement learning . 40 indirect . . . . . . . . . 71 return . 53 telencephalon . . . . . . . . 205 TD learning. 17 electrical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200 stimulus . . . . . . . . . . . . . . . 127 spinal cord . . . . . 195 avoidance strategy . . . . . . . . . . . . . . . . . . . 119 direct . . . . . . . . . . . . . . . . . . . . . . . . . . 199 pure delayed . . . . . . 20 SOM . . . . . . . . . . . . . . . . . . . . see resilient backpropagation Index situation . . . . . . . . . . . . . . 27 Single Shot Learning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 silhouette coefficient . . . . . . . . . 90 resonance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 multi. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . see root mean square ROLFs . . . . . . . . . . see self-organizing map soma . . . . . . . . . . . . . . . . . . . . 161 sensory adaptation . . . . . . . . . . . 17 S saltatory conductor . . . . . . . 125 teaching input . . . . . . . . 175 single lense eye . . . . . . . . . . . . . . . 17 synapses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 situation space . . . 21. . . . . . . . . . . . . 40. . . . .206 symmetry breaking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .176 swing up an inverted pendulum. . . . . . . 41 lateral . . . . . . . . . . . perceptive. . . . 42 refractory period . . 14 stability / plasticity dilemma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . see temporal difference learning teacher forcing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24 surface. . . . . . . . . . . . . . . . vi sodium-potassium pump . . . . . . . 191 repolarization . . see perceptron. . . . . . . . . . . . . . . 166 retina . . . . . . . . singlelayer Snark . . . . . . . . . . . . . . . . . 147 stimulus-conducting apparatus. . . . . . . . . . . . . . . . . . 9 SNIPE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 thalamus . . . . . . . . . 21 representability . . . see cerebrum temporal difference learning . . . . . . . . .dkriesel. . . . . . . . . . . . . . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) 225 . . . . . . .17 synaptic cleft .24 shortcut connections . . . . . 198 SLP . . 165 state . . . . . . . . . .com recurrence . 56 Rprop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 state space forecasting . . . 195 situation tree . . . . . . see regional and online learnable fields root mean square . . . . . . . . . . . 98 synapse chemical . . . . . . . . . . . . . . . . . . . . . . . 195 reward . . . . . . . . . . . . . . . . 198 pure negative . . 198 RMS . . . . . . 23 Schwann cell . . . . . . . . . . . . . . . . . 130 T target . . . . . . . . . . . . . . . . . . . . . . . . . . 25 sensory transduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 self-organizing feature maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . .165 weight vector . . . . . Kriesel – A Brief Introduction to Neural Networks (ZETA2-EN) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . see brainstem two-step-ahead prediction . . . . 123 V voronoi diagram . . 34 bottom-up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 topology function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 time horizon . . 53 set of . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . see delta rule winner-takes-all scheme . . . . . . . . . . . . . 42 U unfolding in time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 dkriesel. . . . . . 50 transfer functionsee activation function truncus cerebri . . . . . . . . 181 time series prediction . . 181 topological defect. . 35 Widrow-Hoff rule . . . . . . . . . . . . . . . 166 top-down. . . . . . . . . . . . . . . . . . . . . . . . 34 226 D. . . . . . . . . . . . .Index threshold potential . . . . . . . . . . . . . . . . . . . . . . . . . . 148 training pattern . . . . . . . 21 threshold value . 53 training set . . . . . 185 direct . . . . . . . . . .154 topology . 196 time series . . . . . . . . . . . . . . . . . . . . . . . . 138 W weight . . . . . . 34 weight matrix . . . 36 time concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .com weighted sum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue listening from where you left off, or restart the preview. | https://www.scribd.com/document/135168483/Brief-Introduction-to-Neural-Networks | CC-MAIN-2016-30 | refinedweb | 79,458 | 60.01 |
a point
current in a straight line towards a
target point.
The value returned by this function is a point
maxDistanceDelta units closer to a
target/
point along a line between
current and
target. If the target is closer than
maxDistanceDelta/
then the returned value will be equal to target (ie, the movement will not overshoot the target).
Negative values of
maxDistanceDelta can be used to push the point away from the target.
using UnityEngine; using System.Collections;
public class ExampleClass : MonoBehaviour { // The target marker. public Transform target;
// Speed in units per sec. public float speed;
void Update() { // The step size is equal to speed times frame time. float step = speed * Time.deltaTime;
// Move our position a step closer to the target. transform.position = Vector3.MoveTowards(transform.position, target.position, step); } }
Did you find this page useful? Please give it a rating: | https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html | CC-MAIN-2018-47 | refinedweb | 142 | 68.47 |
BizTalk Property Schemas in Different Namespaces
In BizTalk 2006 R2, I have noticed that sometimes the promoted property fields are not available. This seemed to be a random occurance so I decided to spend a little time investigating.
Problem Scenario:
The property schema field will not show up in a Receive Shape filter. No matter how many times you build, rebuild, and close the solution it will not show up. Just for kicks, I set the property schema field to “MessageContextPropertyBase” (the default is MessageDataPropertyBase). I then built the project and sure enough the property field now shows up. Good right? Wrong – This type is only used for property fields that are promoted that are NOT included in your message. For example, if you had a custom pipeline that promoted a property not included in the message schema. The MessageDataPropertyBase should be used for fields included in the message.
Ok, so I started looking into this further and decided to open up an orchestration that was working with the Receive Shape filter. The property field used as the filter was in the same namespace as my orchestration’s message schema. The previous test that did not work used a message that was in a different BizTalk project than the property schema.
Cause:
A property schema used in a different BizTalk project will not be available in Receive Shape filters. This also applies to intellisense used in the expression shapes. I am not sure if this a BizTalk bug or Microsoft intended this design. It seems like a proper design to have one common property schema for the solution where fields are available across projects.
Resolution:
Create a property schema in each BizTalk schema project.
Hope this helps in your future development where the promoted property field is not available.
I had a similar situation. I have reusable property schemas in one project that needed to be used in a number of other projects. Although normally MessageDataPropertyBase is used to promote fields included in the message, MessageContextPropertyBase will work just fine – your field will be properly promoted in the pipeline by XLM Disassembler AND the property will be available in the orchestration (just add reference to property schema project). | https://blog.tallan.com/2010/04/15/biztalk-property-schemas-in-different-namespaces/ | CC-MAIN-2018-05 | refinedweb | 368 | 62.17 |
Provided by: libpcre2-dev_10.32-5_amd64
NAME
PCRE2 - Perl-compatible regular expressions (revised API)
SYNOPSIS
#include <pcre2.h> pcre2_match_data *pcre2_match_data_create(uint32_t ovecsize, pcre2_general_context *gcontext);
DESCRIPTION
This function creates a new match data block, which is used for holding the result of a match. The first argument specifies the number of pairs of offsets that are required. These form the "output vector" (ovector) within the match data block, and are used to identify the matched string and any captured substrings. There is always one pair of offsets; if ovecsize is zero, it is treated as one. The second argument points to a general context, for custom memory management, or is NULL for system memory management. The result of the function is NULL if the memory for the block could not be obtained. There is a complete description of the PCRE2 native API in the pcre2api page and a description of the POSIX API in the pcre2posix page. | http://manpages.ubuntu.com/manpages/eoan/man3/pcre2_match_data_create.3.html | CC-MAIN-2019-43 | refinedweb | 156 | 54.52 |
metacall alternatives and similar packages
Based on the "Embeddable Scripting Languages" category.
Alternatively, view core alternatives based on common mentions on social networks and blogs.
otto9.4 5.0 metacall VS ottoA JavaScript interpreter in Go (golang)
gopher-lua9.2 5.2 metacall VS gopher-luaGopherLua: VM and compiler for Lua in Go
go-lua8.9 1.5 metacall VS go-luaA Lua VM in Go
tengo8.7 4.5 metacall VS tengoA fast script language for Go
goja8.7 7.9 metacall VS gojaECMAScript/JavaScript engine in pure Go
expr8.6 4.2 metacall VS exprExpression language for Go
go-python7.9 0.0 metacall VS go-pythonnaive go bindings to the CPython2 C-API
cel-go7.8 8.5 metacall VS cel-goFast, portable, non-Turing complete expression evaluation with gradual typing (Go)
anko7.8 1.3 metacall VS ankoScriptable interpreter written in golang
go-php7.5 0.0 metacall VS go-phpPHP bindings for the Go programming language (Golang)
go-duktape7.4 0.7 L3 metacall VS go-duktape[abandoned] Duktape JavaScript engine bindings for Go
golua7.3 0.0 metacall VS goluaGo bindings for Lua C API - in progress
gval6.8 4.1 metacall VS gvalExpression evaluation in golang
gisp6.6 0.0 metacall VS gispSimple LISP in Go
agora6.2 0.0 metacall VS agoraDynamically typed, embeddable programming language in Go
prolog6.1 9.3 metacall VS prologThe only reasonable scripting engine for Go.
Gentee script programming languageGentee - script programming language for automation. It uses VM and compiler written in Go (Golang).
The uGO Language3.7 8.4 metacall VS The uGO LanguageScript Language for Go
binder3.4 0.0 metacall VS binderHigh level go to Lua binder. Write less, do more.
purl2.6 0.0 metacall VS purlPerl, but fluffy like a cat!
ngaro2.0 0.0 metacall VS ngaroAn embeddable implementation of the Ngaro Virtual Machine for Go programs
ecal2.0 0.3 metacall VS ecalA simple embeddable scripting language which supports concurrent event processing.
mosalat1.2 0.0 metacall metacall or a related project?
Popular Comparisons
README
MetaCall Polyglot Runtime MetaCall.io | Install | Docs
MetaCall allows calling functions, methods or procedures between multiple programming languages.
sum.py
def sum(a, b): return a + b
main.js
const { sum } = require('./sum.py'); sum(3, 4); // 7
shell
metacall main.js
MetaCall is a extensible, embeddable and interoperable cross-platform polyglot runtime. It supports NodeJS, Vanilla JavaScript, TypeScript, Python, Ruby, C#, Java, WASM, Go, C, C++, Rust, D, Cobol and more.
Install
The easiest way to install MetaCall is the following:
curl -sL | sh
For more information about other install methodologies and platforms or Docker, check the install documentation.
Examples
You can find a complete list of examples in the documentation. If you are interested in submitting new examples, please contact us in our chats. | https://go.libhunt.com/metacall-core-alternatives | CC-MAIN-2022-27 | refinedweb | 471 | 52.26 |
Notifications
You’re not receiving notifications from this thread.
Optimizing Queries in Service Objects
I'm currently building an app and using namespaced service objects containing a single call method in each class.
Below is an actual method (I'm aware the ABC size is too large, I'm wanting to get it squared away before I break it apart into smaller chunks):
module Orders class CalculateNextStep include Services::Base def call(order) if order.next_step? order.next_step = Course.where(id: order.course_id).first.course_steps .where(position: 1).first.id else position = CourseStep.find(order.next_step).position order.next_step = Course.where(id: order.course_id).first.course_steps .where('course_steps.position > ?', position) .first.id end end end end
My question is should I move the queries into a query object? And should I just use raw PG queries versus AR finder methods?
Hi Jacob,
When you say "optimize", what exactly do you mean? Are your current queries slow to perform, or would you just like to refactor them so they're more efficient to work with?
You don't really gain much in the terms of speed by doing raw sql vs an AR query (in most cases), and you can actually slow your queries down if you don't know what you're doing (in some cases). Also, raw sql is generally uglier / harder to read than AR methods so maintainability can become an issue later.
As for refactoring to be more efficient to work with, will these queries only ever be used when your app calls on this service object or are these queries used in multiple places? If they're only ever used like this here, then I'd question what's the benefit of abstracting it? Do you gain anything by putting that snippet of code in another file? If not, then just reorganize your code in this file so it's easy to come back to a few weeks / months / years later and call it a day!
Well hey right back at you Jacob!
Sorry for not explaining better. I'd like to refactor them to be more efficient to work with and speed them up as much as possible.
The calls will be used in multiple places. If a call is only going to be used in one place, I just place it in the model class.
I appreciate the input!
Sweet, then yeah I'd just clean up the queries some and ensure you have proper indexes on your tables. I'm far from an expert of DB query optimization but I really don't think you're going to gain much by moving away from what AR provides you, and so I'd spend my energy elsewhere in the project.
As for abstracting it out, really all this boils down to is maintainability. I don't believe there's really any measurable performance increase by having all your queries for that model in the model file vs abstracted out into 50 files. So I'd just do what makes the most sense for how your application functions. If you're ever bored, read up on design patterns, lot of good info there!
Hey Ohad Dahan,
Just wanted to chime in about
select should be used with caution as it still fetches all records and then starts 'selecting' the records to build an array of results..
don't load the entire ActiveRecord use select and pluck to to improve your memory and runtime performance.
That's the part that I'm referring to. If you have experience with queries then you already know this, but to newer developers the fact that
select still loads every object into memory is why I said to use caution. I'm certinally not saying to never use it, just be cautious of how you're using it, it's an iceberg function.
It's not necessarily a single query that would illustrate the problem, it's how it's used that's the problem. That's why I say it's not something a more experienced developer may get caught by, but to a new developer, the consequences aren't so obvious.
Off the top of my head, let's say you have a process that generates a lot of stats for a large group of records. Depending on the calculation being run, you may need to do some additional filtering from the initial group of objects you passed to the generator before passing it through to that particular calculation.
In this instance, a new developer may be inclined to use
select to handle this filtering, which may be a perfectly feasible solution if you know that there will never be a lot of records or you can safely use
limit, however, you may not always be able to use
limit or guarantee that there won't be a lot of objects to process. So care should be given as you're manipulating your data that you don't have any unexpected bottlenecks.
I'm not saying what you said was wrong in any way, just trying to add to the knowledge pool from personal experiences. :) | https://gorails.com/forum/optimizing-queries-in-service-objects | CC-MAIN-2022-21 | refinedweb | 857 | 67.28 |
This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.
On Fri, Jan 21, 2005 at 10:41:51AM +0000, Chris Jefferson wrote: > Paolo Carlini wrote: > > >chris jefferson wrote: > > > >>Good point! > >> > >>Perhaps then a better idea would be to wrap tests like this in a > >>#ifndef _GLIBCXX_DEBUG / #endif pair? > > > > > >Better, but I think we should really understand (I'm speaking for > >myself, first and foremost ;) why the debug mode is so strict about > >that behavior... > > > Hmm.. I'm not sure what you mean. If you mean why does it pass in the > const case, and not in the non-const case, I'd guess thats because that > exactly how it is written in debug/string :) (there is a different > implementation of [] for const and non-const, with the different > requirements.) > > I suppose what this really depends on is what the aim of the debugging > library is. I had at first assumed that it's purpose was exactly what it > says, a libstdc++ debugging library. However in this case it looks more > like it is aiming to be a super-pedantic library. Yes, that's certainly how I regard it - like run-time concept checks that identify anywhere you invoke non-standard behaviour, e.g. invalidating iterators. > One option would be to > introduce an extra "pedantic" mode.. There's already __GLIBCXX_DEBUG_PEDANTIC Maybe the non-pedantic debug mode should be changed to allow this v3 extension, but refuse it in pedantic mode. > however I'm not convinced how > useful that would be in the long run, as I suspect properly implementing > such a thing would require a lot of extra code, so perhaps we should > just nuke this extra test in string? jon -- "There is no governor anywhere. You are all absolutely free." - Cagliostro the Great "The Schroedinger's Cat Trilogy" RAW | http://gcc.gnu.org/ml/libstdc++/2005-01/msg00218.html | CC-MAIN-2018-34 | refinedweb | 307 | 62.88 |
Same here : all tests pass, but it fails on submission for the 4th test only. The code is quite simple, weight computation seems OK, but something is obviously wrong. I am desesparte (sort of).
Shame on me. Wrong return code testing => 100% now.
The input spec clearly states : “Last line: The 7 letters available.”
But in some submission tests, there is a different number of letter on the last line. Maybe the spec should be something more like “Last line: The letters available.” and there should be somewhere something saying that there is not always 7 letters in your hand.
I just arrived at this page due to the same reason. I’m using C, and have a similar algorithm. All tests in dev pass, and all but “valid word” pass when submitting. All four large tests pass…so I’m not sure what’s up. I do handle receiving less than 7 letters as well.
It looks like the valid word test is testing what happens when the letters you get are in the right order and already form the best word.
When the first step of your algorithms is to take the letters and generate all combinations you have to make sure to include the original sequence.
That should already be happening the way my algorithm is written. I will see what happens if I prepend my generic checks with a few substring checks. Thanks for the idea.
I should also note a potential bug. The spec indicates N can approach 100,000, but in the template it is using a signed int. I haven’t run a sizeof on it, but I’m guessing it’s a 2-word, 16-bit short.
It’s 32-bit here.
Okie doke, thanks. I just redid my whole program with a diff algorithm (a lot faster, smaller mem footprint and half the sloc, yay!) still can’t pass valid word test. Scratchin’ my head.
Got 100% after adding a little magic … I am not sure that test case is compliant with the spec.
There is a test with only 6 letters, it may cause some bugs.
It’s a language-specific consideration. I’ve noticed this in many of their input files when using C; you need to do a lot of input sanitization. They send you some interesting characters…even if your algorithm is parametric.
If this is true the example test case could not pass: “which” has two ‘h’
Your proposed solution was not clear, the example solution also have doubled letters (‘which’ has two ‘h’):
Input:
5
because
first
these
could
which
hicquwh
Output
which
I have a question on elegence.
Using python I created a dictionary for the character values, and put it in a function to calculate the word value. But I was wondering if anyone can guide me to a better looking dictionary or maybe a more optimized algorithm, here goes my reasoning:
def calcWord(word): vals = { 'e': 1, 'a': 1, 'i': 1, 'o': 1, 'n': 1, 'r': 1, 't': 1, 'l': 1, 's':1, 'u': 1, 'd': 2, 'g': 2, 'b': 3, 'c': 3, 'm': 3, 'p': 3, 'f': 4, 'h': 4, 'v': 4, 'w': 4, 'y': 4, 'k': 5, 'j': 8, 'x': 8, 'q': 10, 'z': 10 } # later I return the sum of all the values of letters in the word
You can use the dictionary without the function. vals[“e”] will return 1.
Which witch?
Anyway my code passes all test cases but fails the two Large Dictionary validators when submitted. The suggestion of invalidating words with duplicated letters violates the example provided (the witchy ‘which’). I’ve tried that, just in case, and yeah, the first test case (the one based on the example) fails.
The wicked witch is dead, now?
Count the letters in the words.
Yeah, someday I will figure out your riddle. AFAIK I’ve been counting the letters, only scoring the first occurrence.
Riddle solved, thanks! The spec has a somewhat misleading constraint: “(a letter can only be used once)”. That made me think a letter as a class (e.g. all ‘h’), but it was, instead, as an instance, so the available letters could have more than one ‘h’ and, in this case, a word with that many ‘h’ was still valid. | https://forum.codingame.com/t/scrabble-puzzle-discussion/46?page=3 | CC-MAIN-2022-21 | refinedweb | 717 | 81.83 |
Created on 2010-08-02 21:02 by kune, last changed 2012-07-15 03:20 by eli.bendersky. This issue is now closed.
If one wants to use the encoding parameter of ElementTree.write() the file must be opened with "wb". Without encoding parameter normal files can be used, but the should be opened with the encoding "UTF-8", because otherwise this may create an error.
Probably comparable problems exist with the parser side of things.
Is this a behavior bug or a doc bug?
I believe handling of TextIOWrapper streams is broken in xml.etree.ElementTree.ElementTree.write().
First example:
import sys
from xml.etree import ElementTree
element = ElementTree.fromstring("""<foo><bar>foobar</bar></foo>""")
element_tree = ElementTree.ElementTree(element)
assert sys.stdout.encoding == "UTF-8"
element_tree.write(sys.stdout, encoding="UTF-8")
print()
I don't think that write a tree into a stream with the correct encoding should generate any problem at all.
The output looks like this:
Traceback (most recent call last):
File "/home/kunitz/test/lib/python3.2/xml/etree/ElementTree.py", line 825, in write
"xmlcharrefreplace"))
TypeError: must be str, not bytes
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "bug1.py", line 9, in <module>
element_tree.write(sys.stdout, encoding="UTF-8")
File "/home/kunitz/test/lib/python3.2/xml/etree/ElementTree.py", line 843, in write
write("<?xml version='1.0' encoding='%s'?>\n" % encoding_)
File "/home/kunitz/test/lib/python3.2/xml/etree/ElementTree.py", line 827, in write
_raise_serialization_error(text)
File "/home/kunitz/test/lib/python3.2/xml/etree/ElementTree.py", line 1077, in _raise_serialization_error
"cannot serialize %r (type %s)" % (text, type(text).__name__)
TypeError: cannot serialize "<?xml version='1.0' encoding='UTF-8'?>\n" (type str)
Example 2:
import sys
from xml.etree import ElementTree
element = ElementTree.fromstring("""<foo><bar>fööbar</bar></foo>""")
element_tree = ElementTree.ElementTree(element)
with open("bug2.xml", "w", encoding="US-ASCII") as f:
element_tree.write(f)
The first ö umlaut generates an UnicodeEncodeError here, while the method could use XML character references. One could argue this, but the method could take care of the problem.
Third example:
import sys
from xml.etree import ElementTree
element = ElementTree.fromstring("""<foo><bar>fööbar</bar></foo>""")
element_tree = ElementTree.ElementTree(element)
with open("bug3.xml", "w", encoding="ISO-8859-1",
errors="xmlcharrefreplace") as f:
element_tree.write(f, xml_declaration=True)
This creates finally an ISO-8859-1 encoded XML file, but without XML declaration. Didn't we request one?
Example 4: Try to do the right thing.
import sys
from xml.etree import ElementTree
element = ElementTree.fromstring("""<foo><bar>fööbar</bar></foo>""")
element_tree = ElementTree.ElementTree(element)
with open("bug4.xml", "w", encoding="ISO-8859-1",
errors="xmlcharrefreplace") as f:
element_tree.write(f, encoding="ISO-8859-1", xml_declaration=True)
Here we get the same exception as example 1 of course.
All the files can be found in the tar container below.
Here is a patch that handles all 4 examples in the last comment correctly and survives the Python test suite on Linux (Ubuntu 9.04 x86-64).
Thanks for the patch. The examples in your message need to be converted to a patch that applies to 3.2 or 2.7, so that we can reproduce the bug before fixing it.
These bugs are annoying. How does one convert a set of examples into a patch? Do you mean you want these to become test cases?
Yes. See the devguide if you need more info.
Please make sure that the patch(es) apply cleanly to 3.3, since this is the version I'll be focusing on.
I won't get to this, FYI.
ElementTree write works with two kinds of output -- binary and text. The difference between them is only determined by encoding argument. If encoding is "unicode", then output is text, else it is binary. There is no other way for filename or general file-like object to determine kind of output. If these are not explained in the documentation, then the documentation should be improved.
The patch can cause data corruption because direct writing to underlying file by fileno conflicts with TextIOBase/BufferedIOBase internal buffering. And not every file-like object have fileno. With patch the behavior becomes less obvious and will lead to confusion.
I don't see a behavior bug which should be fixed.
Only one thing can be enhanced -- error diagnostic in some corner cases. When we can determines that file object is instance of RawIOBase or TextIOBase and it is conflicts with encoding argument value, it will be helpful for novices to raise a descriptive exception. This is of course not eliminate all causes for confusing.
New changeset 51b5ee7cfa3b by Eli Bendersky in branch 'default':
Issue #9458: clarify the documentation of ElementTree.write with regards to the type of the stream expected for a given encoding
I agree with Serhiy that this is more of a documentation/understanding issue than a real bug. I've clarified the doc of ElementTree.write a bit to make it explicit what stream is expected for 'write'. | https://bugs.python.org/issue9458 | CC-MAIN-2020-50 | refinedweb | 846 | 53.47 |
DjPj 0.6.0
A template-block-based Django helper for jQuery-PJAX.
Overview of DjPj (formerly Django-PJAX-Blocks)
DjPj is a simple, flexible way to add PJAX support to your Django project and deliver a faster browsing experience to users of your website.
If you don’t know what PJAX is, read about how it works below. In a nutshell, it makes navigating between pages on your website faster by loading only the part of the page that needs to change, rather than the whole thing. It’s is a well-established technique; if you’re reading this on GitHub, you probably loaded this content via PJAX.
In a nutshell, your DjPj-enabled website will respond to PJAX requests with the contents of a single template block of your choosing. It requires no changes to your views, which means it’s easy to add PJAX support to third-party Django apps.
Getting started
PJAX requires cooperation between your front end (the Javascript that runs in your visitors’ web browsers) and your Django back end.
1. Set up the front end with jquery-pjax
The front end is handled by the jquery-pjax library, so first of all, read about how to use jQuery-PJAX and pick one of the techniques there.
2. Install DjPj on your server
First, make sure the views you’re PJAXing return TemplateResponse. DjPj works by changing the way your templates are rendered, so it won’t work with a pre-rendered HttpResponse.
Install DjPj from PyPI:
> pip install djpj
3. Start using PJAX - basic usage examples
Imagine you have a template, blog_post.html that looks like this:
<head> <title>{{ blog_post_title }}</title> </head> ... <div id="blog_post"> {% block blog_post %} ... {% endblock %} </article>
Respond to PJAX requests to blog_post_view with the contents of the “blog_post” template block:
@pjax_block("blog_post") def blog_post_view(request, ...) ... return TemplateResponse(request, "blog_post.html", context)
If you want PJAX to correctly update the title of your page, include a title_block or title_variable argument to pjax_block:
@pjax_block("blog_post", title_variable="blog_post_title") def blog_post_view(request, ...) ...
The “container” in PJAX parlance is the HTML element the contains the content you want to swap out. In the example above, the name of the block is the same as the id of the container element - they’re both “blog_post”. In these cases you can just omit the first argument entirely, and DjPj will look for a block whose name is the same as the container’s id:
@pjax_block(title_variable-"blog_post_title") def blog_post_view(request, ...) ...
Use DjPj’s middleware to enable PJAX without modifying your views
If your site uses third-party views that you can’t modify - for example, views defined by an ecommerce or CMS package - you can use DjPj’s middleware instead of decorating views directly. This can also be handy when you have a number of views that you want to PJAXify which all share a common URL pattern.
Here’s what it looks like:
# DjangoPJAXMiddleware should appear last in MIDDLEWARE_CLASSES MIDDLEWARE_CLASSES = ( ..., "djpj.middleware.DjangoPJAXMiddleware", ) DJPJ_PJAX_URLS = ( ('^/blog/', '@pjax_block("blog_post", title_variable="blog_post_title")'), )
Each entry in DJPJ_PJAX_URLS is a 2-tuple with the first element a regular expression matching the URLs you want to PJAXify, and the second a string containing Python code defining the decorator, just as it would be done in views.py.
Using a different template for PJAX requests
You can also use a specific template for PJAX requests, instead of returning a specific block. To do this, use the pjax_template decorator, and pass your PJAX template’s name as the first argument:
from djpj import pjax_template @pjax_template("pjax_template.html") def my_view(request) context = {"post_title": "My First Blog Post", ...} return TemplateResponse(request, "template.html", context)
Your template should include a <title> tag if you want the title to be updated in the user’s web browser.
Customising the behaviour of DjPj
You can customise how DjPj selects blocks and templates by supplying your own functions to the pjax_block and pjax_template decorators. Read more about that on GitHub.
How does PJAX work?
Normally, when you click a link, your browser has to set up everything from scratch: HTML has to be parsed, scripts have to be compiled and executed, stylesheets interpreted and applied. It’s a lot of work, and when you’re browsing between different pages on the same website, much of this work is duplicated. It’s like heating up a new skillet for every pancake.
When a user clicks a link on your PJAX-enabled website, the server sends only the content that needs to change to display the new page. The fresh dollop of content drops into place in your page, and the browser doesn’t have to do all the work associated with a full page load. To complete the trick, we manipulate the browser history to make the back and forward buttons work normally.
Acknowledgements
DjPj relies on defunkt’s jquery-pjax – the canonical client-side PJAX library and the same one used by GitHub.
DjPj was originally adapted from Jacob Kaplan-Moss’ Django-PJAX.
Python and Django compatibility
This package is tested in Django 1.4+ and Python 2.6, 2.7, 3.3+ and PyPy.
Testing
Tests are run using nose. To install:
pip install nose
And to run the tests:
nosetests tests.py
- Author: Alex Hill
- License: BSD
- Categories
- Development Status :: 4 - Beta
- Environment :: Web Environment
- Framework :: Django
- Intended Audience :: Developers
-
- Programming Language :: Python :: 3.6
- Programming Language :: Python :: Implementation :: CPython
- Programming Language :: Python :: Implementation :: PyPy
- Requires Distributions
- django (>=1.4)
- Package Index Owner: alexhill
- DOAP record: DjPj-0.6.0.xml | https://pypi.python.org/pypi/DjPj | CC-MAIN-2017-39 | refinedweb | 923 | 62.38 |
Liskov's Substitution Principle (LSP) - S.O.L.I.D. Framework
The third principle of the S.O.L.I.D. Framework is the Liskov’s Substitution Principle (LSP).
The main statement of this principle is “derived types must be completely substitutable for their base types“.
What does that means? Well, basically that every parent class should be replaceable by one of its derived child classes without any problems. Imagine we have a Car base class which provides a Accelerate() method. If we are now using the derived ElectricCar Class we would suggest that the Accelerate() would accelerate the car and not slow it down it.
public class Car { public double speed { get; set; } public virtual void Accelerate() { speed++; } } public class ElectricCar : Car { public override void Accelerate() { speed--; } }
In this case we would violate against the LSP because the behaviour changes without any reason and the programmer would probably running in a problem because he trusts that the Accelerate() method in the derived classes does the same as in the parent class.
To demonstrate the outcome I have written two little Unit Tests shown above. The first one uses the Car Class and after calling the Accelerate() method the speed property increase by one – and therefore is it greater than zero – so the test passes. In the second Test I used the ElectricCar class and the test fails because the ElectricCar implementation overrides the Accelerate() method and acutally decreases the speed – therefore it is lower than 0. | https://www.patrickschadler.com/solid-principles-part-iii/ | CC-MAIN-2022-05 | refinedweb | 247 | 59.84 |
Click for live demo!
In recent times, the HTML5 client platform is becoming an increasingly important platform to target for UI development. Not only is it supported on a large percentage of mobile devices, but it specifies an exciting new Canvas element that is especially interesting to those interested in creating graphics rich Data Visualizations on all platforms.
The promise of being able to write some logic to present client-side, highly interactive visualizations is extremely alluring, but presents interesting drawbacks to teams that are accustomed to leveraging the features of higher level languages to assert quality of product and to ensure ease of maintenance and enhancement. It also presents challenges to teams that already have large existing code libraries and experience in a higher level language (like C#, Java, etc.) that would like to reuse at least some of this logic on the browser client.
In this article we will discuss:
Disclaimer: I'm about to discuss what I view as some of the short-comings of JavaScript for large projects, compared to languages such as C# or Java. The pros and cons of a particular language can often end up boiling down to matters of opinion and personal preference. To those whose opinions are aligned with mine on what makes a language nice to work with, the below should resonate, I hope. If it is your opinion that JavaScript is the right tool for projects of every scale, then the portions of this article about code reuse should still be interesting, I'll warrant, and areas discussing the benefits of using a high level language to indirectly author JavaScript can safely be ignored. The below is relevant to the topic of this article, I believe, so I hope I'll be forgiven this digression into programming language comparative analysis.
JavaScript is a nimble and amazingly flexible language, with many surprisingly cool features, but compared to a language like C#, it can be vastly frustrating to maintain large codebases in. Attributes like its dynamic, weak type system and reliance on global variables contribute to JavaScript being very terse and expressive, but do little to enforce or make discoverable the intent of the code's author to either the compiler/interpreter or even other developers that must work on the codebase. Confusion of intent can lead to subtle (but maddening) logic errors, or code being unintelligible to other people, or even the same person too long after it was originally written. JavaScript's interpretive nature can lead to many more classes of errors only being discovered at runtime rather than by the compiler.
It is possible to, given the correct discipline, write a large amount of JavaScript that is as beautiful and maintainable as good quality C#, but the ways to fall off the road to a maintainable and extensible codebase are more numerous and varied with JavaScript. Modern JavaScript frameworks such as jQuery (motto: write less, do more) do much to reduce the amount of JavaScript that must be written to accomplish a task, and thus help to mitigate a lot of the failings of JavaScript as a reliable language for large projects. However, these frameworks mainly focus on ease of manipulation of the DOM and other common tasks required by all web developers.
With a data visualization control, however, we may have large requirements for complex logic that have little bearing on DOM inspection and arrangement. Is there another way that we can more reliably maintain a larger code base that runs in a large majority of modern browsers? Silverlight allows us to write large and comparatively easy to maintain projects in C# that can deploy down to many browser clients, but Silverlight support on the mobile platform is currently very limited. What about the other clients?
And what if we want to release visualizations that target both JavaScript/HTML5 and also C# based platforms (Silverlight/WPF/etc.)? Must we maintain many mutually exclusive code bases?
Due to some of the failings of JavaScript for large projects, as described above, some have created tools that leverage the syntactic similarity of C-like languages to JavaScript to enable translation or compilation of C-like higher level languages to JavaScript. One such project is Script#, and in the Java realm the Google Web Toolkit (GWT) provides a similar function. These strategies usually involve the code being written in the higher level language, compiled, and thus checked for errors using a much stricter set of requirements and higher level semantics (such as strong typing, interface implementation, etc.) and then either the resulting output is translated to JavaScript, or else the original high-level language syntax is directly syntactically translated into the equivalent JavaScript statements. The benefit of the latter technique being that the translated JavaScript will have a reliable similarity to the code written in the higher level language at the cost of the translator needing to be able to translate complex high level language concepts directly into JavaScript that otherwise may have been simplified away by the compilation process (e.g. linq).
Another benefit is that there are compelling tools (FxCop, etc.) for assessing the quality of C#, Java, and other high level languages that can be brought to bear to aid in maintaining the quality and maintainability of the code base at that high level, regardless of the eventual syntax of the logic.
The ability of tools like Script# to take code written using higher level languages and run it directly on the client browser is startling and not to be underestimated.
Here's an example of a translation performed by Script#:
Original C#:
public class Rectangle
{
public Rectangle(double width, double height)
{
_width = width;
_height = height;
}
public double GetArea()
{
return _width * _height;
}
public bool IsSquare()
{
return _width == _height;
}
public int CompareSize(Rectangle other)
{
double thisArea = GetArea();
double otherArea = other.GetArea();
if (thisArea < otherArea)
{
return -1;
}
if (thisArea > otherArea)
{
return 1;
}
return 0;
}
private double _width;
private double _height;
}
Translated JavaScript using Script#:
ClassLibrary1.Rectangle = function ClassLibrary1_Rectangle(width, height) {
this._width = width;
this._height = height;
}
ClassLibrary1.Rectangle.prototype = {
getArea: function ClassLibrary1_Rectangle$getArea() {
return this._width * this._height;
},
isSquare: function ClassLibrary1_Rectangle$isSquare() {
return this._width === this._height;
},
compareSize: function ClassLibrary1_Rectangle$compareSize(other) {
var thisArea = this.getArea();
var otherArea = other.getArea();
if (thisArea < otherArea) {
return -1;
}
if (thisArea > otherArea) {
return 1;
}
return 0;
},
_width: 0,
_height: 0
}
ClassLibrary1.Rectangle.registerClass('ClassLibrary1.Rectangle');
In the C# code above, you can see the benefit of strong typing in the CompareSize method where it is ensured that the other object passed in must be of Rectangle type. The C# compiler will assert that invocations of this method have the correct typed parameters at compile time. The intent of the method is also very clear, we are exclusively intending to compare the size of two Rectangles, not shapes of any other type.
In the JavaScript, you can see that Script# has emitted the class that we have defined, along with the requisite fields, constructor, and methods, which look syntactically very similar to the original C# methods. This similarity is likely due to Script# translating directly from the C# syntax, after the C# compile is completed, rather than moving backwards from the outputted IL code, which would likely make the logic flow more dissimilar from the original version.
You'll also notice that in the compareSize method, in the JavaScript, there is no need to check that the parameter has the correct type at runtime due to the fact that the C# compiler asserted this at compile time. Technically some hand written JavaScript could pass in an object which did not define the necessary getArea method, but all code that we have written in C# (and compile with Script#) that invokes CompareSize will have their invocations checked for the appropriate types at compile time.
This increased strictness prevents a whole class of errors at compile time that would otherwise surprise us at runtime!
Not so fast! We can't recompile the whole Silverlight runtime as JavaScript (much as we'd like to). And even if we could, a tool like Script# only re-implements a small subset of the BCL in JavaScript to be usable on the client. So we'd have to fill out the BCL a lot too. Also, certain C# language features are not available using the Script# compiler. The most painful missing features in terms of direct code compatibility are: generics, method overloading, extension methods, object initializers, auto-implemented properties, linq, and lambda expressions (although you can use anonymous methods). Clearly, if we want to share logic between the HTML5/JavaScript platform and more conventional C# based platforms, we will need some strategy to best leverage the subset of features that Script# can provide us on that platform.
One strategy we can use, especially when creating a new visualization is to separate the "what to render" logic from the "how to render" logic. And separating the "what to do about an interaction" from the "how to sense an interaction has occurred". There are many design patterns that people leverage to decouple the logic for these kinds of activities including MVC, MVP, MVVM, etc. But the key here is that the "what to..." shouldn't be dependent on the capabilities of the particular client platform, and that the "how to..." should contain as little code as possible (as it differs per client platform). It represents a platform specific implementation of how to render a visualization and how to shuttle interactions back to the associated controlling logic. In Data Visualization, especially, we can structure our logic such that most of the complexity and volume of the code expresses the "what" and we can keep our code that expresses the "how" as minimal as possible. The idea is that, if we are careful, we should be able to compile all of the "what" logic unmodified against both Script# and the C# compiler (for use in Silverlight/WPF/Windows Forms/etc.) And only have to maintain separate "how" logic on each platform.
When tasked to create a new Silverlight funnel chart, which releases as CTP in the next volume release of NetAdvantage for Silverlight Data Visualization, I used the above described pattern to drive a wedge of separation between the what of the chart, and the how. The resulting Controller ("what") logic of the funnel chart is entirely shared between Silverlight/WPF and Script# projects and so compiles to either a Silverlight binary, or to client executable JavaScript. I was then able to write the View ("how") of the funnel chart separately as a Silverlight project and then a Script# project, which translates down the JavaScript. In the case of the Silverlight "how" project, the how involves Silverlight Canvases and Paths, and Popups for tooltips, and in the case of the Script# "how" project, the how involves HTML5 Canvases and drawing, and CSS positioned tooltips. The "how" is not a large body of code compared to the "what", and even on the HTML5 platform, is entirely authored in C# and then compiled to JavaScript using Script#.
As a further experiment I wrapped the resulting JavaScript in a hand-written jQuery plug-in styled interface to make the usage story as consistent with a jQuery plug-in as possible. Below you can experiment with the live result, which is extremely similar in functionality to the upcoming Silverlight version of the control, and shares a large majority of its code directly. Some of its most complex behaviors such as the animation, positioning, weighting, selection management, and segmented curve generation are entirely shared logic with little to no requirement of platform specific customizations.
Click for Live Sample! (A browser supporting HTML5 canvas is required for the HTML5 version.)
Pretty wild huh?
Here's an example of a method from the shared C# code:
private void AddBezierPoints(SliceAppearance sliceAppearance, double currentTop, double currentBottom, double plotAreaCenter, double offsetx, double offsety)
{
BezierPoint top = Bezier.GetPointAt(currentTop);
BezierPoint bottom = Bezier.GetPointAt(currentBottom);
PointList points = new PointList();
PointList rightPoints = new PointList();
int startIndex = top.Index;
int endIndex = bottom.Index;
for (int i = startIndex; i <= endIndex; i++)
{
points.Add(
new Point(
((BezierPoint)Bezier.Points[i]).Point.X - offsetx,
((BezierPoint)Bezier.Points[i]).Point.Y - offsety));
}
for (int i = endIndex; i >= startIndex; i--)
{
Point p = ((BezierPoint)Bezier.Points[i]).Point;
double dist = plotAreaCenter - p.X;
Point rightPoint = new Point(plotAreaCenter + dist - offsetx, p.Y - offsety);
rightPoints.Add(rightPoint);
}
sliceAppearance.BezierPoints = points;
sliceAppearance.RightBezierPoints = rightPoints;
}
And the translated JavaScript created by Script#:
_addBezierPoints: function Infragistics_Controls_Charts__xamFunnelController$_addBezierPoints(sliceAppearance, currentTop, currentBottom, plotAreaCenter, offsetx, offsety) {
var top = this.get_bezier().getPointAt(currentTop);
var bottom = this.get_bezier().getPointAt(currentBottom);
var points = new Infragistics.Controls.Charts.PointList();
var rightPoints = new Infragistics.Controls.Charts.PointList();
var startIndex = top.index;
var endIndex = bottom.index;
for (var i = startIndex; i <= endIndex; i++) {
points.add(new Infragistics.Controls.Charts.Point((this.get_bezier().get_points()[i]).point.get_x() - offsetx, (this.get_bezier().get_points()[i]).point.get_y() - offsety));
}
for (var i = endIndex; i >= startIndex; i--) {
var p = (this.get_bezier().get_points()[i]).point;
var dist = plotAreaCenter - p.get_x();
var rightPoint = new Infragistics.Controls.Charts.Point(plotAreaCenter + dist - offsetx, p.get_y() - offsety);
rightPoints.add(rightPoint);
}
sliceAppearance.set_bezierPoints(points);
sliceAppearance.set_rightBezierPoints(rightPoints);
}
The use of a tool such as Script# for this purpose is immensely empowering and satisfying. Though it has still to reach V1, it demonstrates a surprising maturity, and can make it a dream to create even large JavaScript targeting projects. Working with Script# is also, it seems, at least to me, much faster than working with JavaScript directly, with fewer logic errors to fix during implementation and less problems where the detection is deferred until runtime. If you are careful, and are starting a new project, you can structure your logic so as to optimize the amount of code you can directly share between JavaScript and other platforms.
The picture is a bit murkier however, when adapting existing logic for cross-platform usage. Here is a short list of some pain points in the form of missing Script# features:
Most of these you can work-around in straightforward ways, but each workaround can result in the injection of risk into an existing body of logic.
Though Script# was created primarily as a tool to author C# for the sole consumption of browser (rather than to share logic between platforms), its utility as a tool to help create a truly cross-platform library is undeniable. The removal of some of these limitations would help to foster that utility. Using Script# to develop cross platform libraries will, of course, have its dangers for when JavaScript has differences in semantics or performance, but, with care, one can create a pool of shared logic of immense value, enabling excellent, compelling cross-platform scenarios.
Are there plans to make some Infragistics controls cross platform, Silveright and HTML5 using this technique?
Thanks,
Please Login or Register to add a comment. | http://www.infragistics.com/community/blogs/engineering/archive/2011/04/05/using-scriptsharp-to-create-compelling-cross-platform-data-visualizations.aspx | CC-MAIN-2016-22 | refinedweb | 2,473 | 50.67 |
Dan Nicolaescu <address@hidden> writes: > Unfortunately none of these ring a bell to me. Yidong I assume this > code is the reason you added the HAVE_GETRLIMIT autoconf check, can you > guess what can be wrong here? The reason I added the getrlimit check was because of the bug reported here (bug#86): > src/vm-limit.c has #ifdef HAVE_GETRLIMIT...#else...#endif sections > (i.e. line 36 onwards and line 158 onwards) and yet the configure > script never tests for getrlimit() and hence config.h never has any > HAVE_GETRLIMIT definition. Yes, configure does test for setrlimit() > and sets HAVE_SETRLIMIT though! Apparently, due to an oversight in the configure script, the HAVE_GETRLIMIT code was always turned off, even though the code had already been written. Could it be that getrlimit is buggy on Cygwin? Maybe we could work around this by turning off HAVE_GETRLIMIT on that platform :-P | http://lists.gnu.org/archive/html/emacs-devel/2008-08/msg00123.html | CC-MAIN-2019-09 | refinedweb | 146 | 67.25 |
The Christian practice of communion is a reminder of why Jesus is important and how his life affects us. To see the full depth of it, you have to consider pre-Christian religion.
Before Jesus: Manna Was “Bread from Heaven”
When the Israelites left Egypt, they spent 40 years in the desert as nomads. During this time, their primary sustenance was a food called “manna” (lit. What is it?). Every morning, it appeared on the surface of the ground. People milled it into flour, then baked cakes with it. This food couldn’t be kept overnight; it would spoil.
During this time, God sustained people in a very tangible way. They would have starved in the desert if he hadn’t provided them with this miraculous food. The people had no choice but trust God to provide it each day.
(Descriptions of manna: Exodos 16, Numbers 11)
Before Jesus: Sacrificed Meat
Part of the Israelites’ relationship with God was animal sacrifice. In short, sacrifices served as “bridges” between the supplicants (who were imperfect) and God (who was perfect). An animal would be killed, then some parts were burned on the altar. Other parts were given to the priests, to be eaten by them.
In this way, the sacrifice served a double purpose of providing access to God and providing food for full-time clergy.
(Priests eat meat: Leviticus 7, 1 Corinthians 9)
Jesus Is “Bread from Heaven”
These two points provide a backdrop for Jesus’s claims:
.
Here, Jesus united the traditions of sacrifice and “bread from heaven”:
- Jesus himself is some kind of better bread than manna.
- To eat this bread, you must eat his flesh. (Yuck!?)
- As the “living bread”, Jesus provides absolute sustenance: those who eat it have “eternal life”, meaning that they’ll enjoy eternity in union with God after Jesus’s return (cf “raised up on the last day”).
On the night before his arrest (ie, during the “last supper”), Jesus made this idea concrete:.”
This instituted the practice of communion, also called the Lord’s supper. Communion is a reflection of some points of faith:
- The bread & wine are imperfect pointers to a perfect “food”, which is Jesus himself.
- Although bread sustains you for short time, believing in Jesus provides eternal life upon Jesus’s return.
- The bread & wine are stand-ins for Jesus’s flesh and blood (😳), and by eating it, we remember Jesus as a sacrifice in both ways mentioned above:
- Jesus bridges the gap between us and God, allowing us to have a relationship with God
- Jesus provides sustenance for day-to-day life (by way of faith in him, in the form of hope for his kingdom to come).
These are the reasons I enjoy communion. It’s a reminder of how God made peace with me, a sinner, by Jesus’s sacrifice. As a result, I can trust God to forgive my sin, sustain me in day-to-day life and “raise [me] up on the last day”. | http://rmosolgo.github.io/blog/2015/08/08/communion-as-bread-from-heaven/ | CC-MAIN-2018-09 | refinedweb | 499 | 70.94 |
Interview with SETI@home Director David Anderson 172
CowboyRobot writes "ACM's Queue magazine interviews David P. Anderson, a research scientist at the U.C. Berkeley Space Sciences Laboratory, who directs the SETI@home and BOINC (Berkeley Open Infrastructure for Network Computing) projects. SETI@home uses hundreds of thousands of home computers in the search for extraterrestrial intelligence. FTA: "volunteer computing arose because projects such as SETI@home needed $100 million worth of computing power but didn't have the money. But there's no free lunch--a project must give participants something in return for their computer time.""
Give them a way to keep score (Score:5, Insightful)
Re:Give them a way to keep score (Score:5, Funny)
Re:Give them a way to keep score (Score:3, Insightful)
Only people with small e-peckers say stuff like that.
Not the same everywhere. (Score:2)
There is still some emphasis on stats, but overall the activity surrounding the related Open University course and discussion of climate change and ecology tend to eclipse competition for its own sake.
CPDN is the most demanding distributed computing research project I've seen and narcissists fall by the wayside pretty quickly. What we COULD use are more geeks. ;
Re:Give them a way to keep score (Score:2)
Re:Give them a way to keep score (Score:1)
I know all this is non-profit and volunteer, but I would love to see something substantive in return for making the office bedroom 10 degrees (F) hotter than the rest of the house.
Re:Give them a way to keep score (Score:4, Funny)
I can't understand how my nephew will play WOW for an entire weekend to change a number from 47 to 48.
Re:Give them a way to keep score (Score:1)
Re:Give them a way to keep score (Score:2, Funny)
Re:More Ambitious Project: STI (Score:2)
No one seriously believed the 100,000 number other than the big media outlets out to get Bush at all costs. Check out this analysis [msn.com] at Slate.com - not what one would consider a Bush-friendly source. It's statistics at its worst.
A fact-based, yet still not Bush-friendly source is iraqbodycount.net [iraqbodycount.net]. Their number is 25-28K.
Now, clearly this is
Patent Rights (Score:2, Interesting)
Re:Patent Rights (Score:2, Funny)
I'm betting that any goodies we get out of the deal, like warp drives and matter replicators, have already been patented by the aliens. They'll probably be expecting royalties.
New client (Score:3, Interesting)
Re:New client (Score:4, Informative)
Re:New client (Score:3, Interesting)
Re:New client (Score:1)
Re:New client (Score:1, Troll)
Blows the F@H client away on features, and it's an equally good cause, with (AFAICT) better project administration than F@H.
Re:New client (Score:4, Interesting)
I'm all for donating spare CPU cycles but I would rather it went to something that had a better chance of having a point like molecular biology research.
Re:New client (Score:5, Interesting)
Anyone doing radio astonomy is going to be listening on or near the 21cm "hydrogen band", as there's only "a very narrow frequency band" that works for radio astronomy at any distance. If you're going to send a signal to someone you know noting about, this is the one frequency range that you can be sure they'll be listening on, if they're listening at all. It's not just chosen arbitrarily.
Certainly, the chance of finding alien intelligence after we checked the easy targets is small - small enough that I'm happy SETI is orivately funded, not fighting for funds from the NSF. But for a volunteer effort, support what makes you happy to support.
Re:New client (Score:2)
I saved myself the grief: I stopped while still using the old client, because the bunch that ran the old system so abysmally poorly couldn't be counted on to run the new system any better. They had chronic problems with their network, with their feeds, with the servers that were supposed to accept results, and with their forums. What use is t
How about a free probing? (Score:5, Funny)
Re:How about a free probing? (Score:1, Funny)
Re:How about a free probing? (Score:2)
Re:How about a free probing? (Score:1)
Power usage? (Score:5, Interesting)
Re:Power usage? (Score:5, Insightful)
2. Lots.
The cost is just spread out over thousands of people, instead of having them all in one place.
Re:Power usage? (Score:1)
What about the cost to the environment? Ah yes, this is also spread out over many thousands (billions) of people.
Re:Power usage? (Score:5, Interesting)
From this link [tomshardware.com] a good average differential between a processor at load and idle is 40W. If you turn the computer off instead, that's maybe 80W. (Broad average over many computers).
Now Here [berkeley.edu] we see that 2million years of computing time has been used, so (times 40W/hr) that comes to 700,000MWHr.
No the 2000 U.S. consumption of energy was ~21 billion MWHr. (Here, and trust the government to use quadrillions of BTUs as a unit [doe.gov]). So to date, SETI has used 0.003% of U.S. annual energy consumption. And that's almost enough energy to power the City of Red Deer, Alberta [gov.ab.ca] for 17 months! Someone else can tell us how many libraries of congress you could have read with that much light.
Feel free to check my units and zeros, I've been wrong before, as long as someone can tell the Brits what a quadrillion is.
Re:Power usage? (Score:2)
So if you are worried about it simply don't search for aliens in summer.
Re:Power usage? (Score:2, Funny)
Nobody needs SETI. If you're looking for a real challenge, try to find intelligent life on this planet[1].
Charly
[1] And no, mice don't count.
Re:Power usage? (Score:1)
Re:Power usage? (Score:5, Informative)
Re:Power usage? (Score:2)
Re:Power usage? (Score:2)
Re:Power usage? (Score:2)
Yes, but that is not all...
Your CPU is cooled by pulling in cool air(relatively speaking) from outside your case and pushing the hotter air out the back. Then the A/C in your house needs to cool the hot air produced by the computer. So you will have to pay more money to run your home's A/C.
I love BOINC (Score:1, Informative)
Re:I love BOINC (Score:3, Informative)
From the Site:
Einstein@home is a program that uses your computer's idle time to search for spinning neutron stars (also called pulsars) using data from the LIGO and GEO gravitational wave detectors.
Resource hog (Score:1)
When using it, the laptop fans run all the time, and no doubt my power utilization is higher. As much as I'd like to help , I just can't justify it.
Well, that's sort of the point. (Score:5, Informative)
It, however, should NOT be a resource hog in the sense of Microsoft Office, in that it slows down other programs. These programs are designed to utilize any resources you aren't using, and immediately give them back if you need to use them. This is done by setting the priority of the process just over system idle. Any cycles that would be spent idle are spent on processing instead, but when a program wants cycles, it gives them up.
Re:Well, that's sort of the point. (Score:2, Informative)
Yes, I understand (and yes, I've tuned it properly). But that's not how it works. While it may
Re:Well, that's sort of the point. (Score:2)
The problem isn't that BIONC is taking up your resources, it's that those pretty graphics have to be loaded up and unloaded whenever the SS starts.
I don't have the SS on and have never seen _any_ impact on my computer performance.
Re:Well, that's sort of the point. (Score:2)
SETI was always more about feel-good-ness and "look how cool my computer is", than actually doing anything beneficial. It's like eating Rainforest Brand ice cream instead of flying to Brazil and standing in front of a bulldozer.
Re:why do the two have to be exclusive? (Score:2)
You can't crunch numbers for both at the exact same time. This, of course, is indicative in my belief that the SETI project is a complete waste of time anyway.
Perhaps.... (Score:2)
Re:Perhaps.... (Score:2)
Strange signal? (Score:2)
Re:Strange signal? (Score:1)
Well, obviously it occurred to you. However, Mr. Anderson from TA* is a mathematician, not a deep-thinking slashdot user like you and me.
-------
*If I were a cusser I'd write "TFA," but I'm not so I didn't just write that.
Re:Strange signal? (Score:1, Funny)
Straigten up and quit thinking the word fine is a bad word. Yes it is derogatory to say that is a fine woman but it is not in refrence to The Fine Article; unless of course there is a new line of seperatists articles liberals on the horizon.
Re:Strange signal? (Score:2)
Re:Strange signal? (Score:1)
Re:Strange signal? (Score:2)
SETI @ Home processes data that is sometimes several years old. The origin could be virtually anywhere in the sky by the time they get around to signal detection - did you actually think this was realtime analysis?
The data comes from scanning specific regions of the sky, so the origin is known, otherwise the whole SETI project would be only marginally useful.
I'm also not suggesting to locate a moving object in the sky, but am working on the assumption that the moving object transmitted a focussed tran
Re:Strange signal? (Score:2)
unless...
No, SETI researchers were puzzled because there is nothing visible at the location. Of course, maybe there is a Dyson spere
;-)
Yes, that is a tough one.
No, it would still come from one source.
True, and that would be a nice opener for the X-Files
There are quite a fe
Probably Virgo, maybe towards Libra (Score:2)
Well I took a look and that would give Virgo, maybe a bit towards Libra as the source. Virgo has several interesting and a few close(10 lyrs) stars.
return (Score:1)
so everybody who contributed gets an alien in return , and would you like fries with it?
How Timely (Score:5, Funny)
Maybe they've been hacked by Aliens who didn't want to be discovered.
"I for one welcome our new alien hacker overlords."
.
Re:How Timely (Score:1)
My real question about this is am I killing my laptop faster than I'm killing my desktops using these clients? I would guess yes. Unfortunately the laptop is the fastest machine and I'm a d.net stats.addict.
Re:How Timely (Score:2)
And, there are other BOINC projects you can choose, besides SETI.
Or, you can save a watt or two. I checked, and my best computer uses 110 watts when id
Re:How Timely (Score:1)
Furthermore the credits from one project to another still are scored equally, so you don't lose any headway in the standings when a project is idle.
Re:How Timely (Score:2)
Hm... (Score:2)
Re:Hm... (Score:1)
I thought so too. I was looking for more questions about SETI myself, but oh well. If anyone else is looking for an interview more about SETI and less about BOINC, here are the interview questions up front, so you can skip the 3-page interview if it doesn't appeal to you:
Re:Hm... (Score:2)
Re:Hm... (Score:3, Informative)
You have certainly waved off a huge amount of information and theory in just two sentences. So you're basically saying that even though we've only searched approximately 0.002%* of the sky for less than a decade and found nothing, this surely disproves the p
If they're out there: (Score:2, Insightful)
Projects like SETI at home are basically looking for signals someone is intentionally sending to us, at an "obvious" frequency and with signal structure dumbed down so a less sophisticated civilization (us, with near certainty) could recognize it as such.
If you believe that the speed of light is a law of nature that can't be trifled with, then no civilization out there would know of our existence unless they were within (prob. well within) about 100 light years. That really cuts down the available volume
Re:Hm... (Score:2)
Wow! You just turned SETI into a religion instead of a science.
New Project (Score:3, Funny)
Anyone want in?
K.
Re:New Project (Score:2, Funny)
I can't just go donating my computer time to anybody who comes up with a project.
Re:New Project (Score:1)
SETI@Home is crap since BOINC came into the pictur (Score:2, Interesting)
SETI was just fine with it's old client -- this may just be a how-to on how to loose a loyal following! SETI@Home no longer runs on my c
BOINC = generic distributed computing! (Score:2)
I work on
Re:SETI@Home is crap since BOINC came into the pic (Score:2)
Seti@home was not fine with the old client. There were easily exploitable ways of running up your CPU time that brought into question the validity of the results being returned. It became less a question of donating CPU time to science, and more of an attempt to show the world how big your geek-dick is. "I've got blah blah blah hours on Seti" started to become the equivilent of "I just bought a new H2"
BOINC is a huge improvement over the old client. It does require more RA
Re:SETI@Home is crap since BOINC came into the pic (Score:2)
Seti-Boinc is an object lesson in how to screw a good idea with incompetent design.
Right, I missed the O'Reiley book about "properly setting up massive distributed computing projects."
Tell me, what was so incompetent about the design? Or anything else about this project for that matter? Seti-classic is done. Period. there's nothing more to be learned from the project, you're just re-working the same units over and over. That phase of the project is dead. Move on.
Re:SETI@Home is crap since BOINC came into the pic (Score:2)
contributing cycles to any distributed projects?
Re:SETI@Home is crap since BOINC came into the pic (Score:2)
Re:SETI@Home is crap since BOINC came into the pic (Score:2)
Same here. But, old client (V3.08) works fine, at least at 4-5 computers that I have S@H running.
BTW, ~2800 units, ~28k hours.
Why do you expect to find anything? Time is vast! (Score:3, Interesting)
There probably several hundred stars in this volume, IMHO some of which will have/had intelligent life. But how long are they going to keep at it with directional RT transmitters?? I'd guess maybe 1000 years. But that's out of a 5 billion year stellar cycle! Not only is space vast, but so is time. Planetary evolutions _will_ be out-of-phase by millions & billions of years.
Just ask the FSM (Score:2)
Re:Why do you expect to find anything? Time is vas (Score:4, Informative)
The signal could be quite strong indeed, if based on someplace like Mercury, from just solar power. With just a 100m square array ET could be 200 light years out with your assumptions, and that's something a lone nutjob could set up given reasonable space trave technology. A government-sized effort could be several orders of magnitude better.
SETI is interesting precisely because it should be pretty easy to find any alien life that wants to be found, and yet we keep not finding it.
Re:Why do you expect to find anything? Time is vas (Score:2)
So how far along are they? (Score:2, Insightful)
Re:So how far along are they? (Score:2)
Next building over is Baker Labs (Score:1)
Amusingly, our structural predictions based on protein folding are just down the hallway from me, in the Baker Labs, which uses a lot of cheap Linux computers to get even better results.
I think Baker's predictions rank usually 2nd to 5th, and the Stanford predictions are below that rank.
It's great to see everyone trying to get all this done!
Good, but what's the results? (Score:2, Interesting)
It was noted above that while there are plenty of CPU sucking projects they don't seem to have end results that can actually be used in daily life.
OK, d.net proved the point by breaking crypto that was thought to be too strong. Fine, done that, why waste CPU cycles further?
SETI@Home -- okay, its cool to search for aliens, but lets be realistic here -- its cool, but not exactly useable.
Lots of effort, heck, lots is too small of a
I confess: Jodie Foster made me do it (Score:2, Funny)
Boinc was a bad move, IMHO (Score:2, Insightful)
SETI@Home has always had an inferior statistics system than Distributed.net, and I really think the client is also inferior. BOINC just makes it much less approachable. SETI classic and DNET both are things you can pretty seemlessly run on your parents computer, etc... BOINC requires a more elaborate registration procedure, forcing you to keep ahold of a ginormous string of
I wish BOINC could... (Score:3, Insightful)
I wish BOINC could also be designed to use graphics cards - ala the BrookGPU project - to help with the number crunching duties.*
Granted, it would require both Nvidia and ATi to donate with the efforts (especially ATi and their stingy Linux commitment).
I'd love to see some old machines with all their PCI card slots filled up with 3dfx Voodoo cards and the like helping future scientific endeavors.
*Don't get me wrong, I do enjoy the BOINC software rendering the SETI@home graphics courtesy of OpenGL, but I think there are more noble tasks the GPU could be harnessed to work on...
Re:I wish BOINC could... (Score:5, Informative)
So do I. In fact I keep looking for people to help us develop this.... To no avail.
:( Aparently the people who want this most don't have the ability to implement it, and the people who have the ability (assuming they exist) aren't interested.
If anyone wants to help, join the boinc_opt [berkeley.edu]mailing list and send a message.
BTW, David is the titular director of SETI@home, but currently has no managerial duties beyond the BOINC project.
Re:I wish BOINC could... (Score:2)
Interested, but I have no abilities other than a token financial donation and some spare 3dfx videocards...
You'd (I mean, I) think the graphics card companies would donate some services to help out with the task...
Re:I wish BOINC could... (Score:2)
We did get some financial support from a graphics card manufacturer and employed some students on the task for a summer. But corporate priorities change, or maybe they weren't happy with the rate of progress, and the manufacturer didn't make good on promises of subsequent support, which prompted the university to withdraw matching funds, which meant we really couldn't afford to work on it further...
Re:You realize how power inefficient that would be (Score:2)
Yes, there is the energy efficiency argument, but that logic excuses the energy/environmental costs in acquiring new equipment. If you buy a new videocard (or a new CPU) for this project, you increase demand for it and consequently, more of the videocards (or CPUs) are built. Making processors and related tec
read the whole article (Score:2)
Ive been a S@h user since oct 2001 (Score:3, Informative)
I see some comments about S@h's recent bugs, and come on its still somewhat in beta (as S@h classic still runs right next to it, new sign ups are forced to use the BOINC client but classic is still open to current members) thats no excuse, but it helps to explain some of the strain.
Its not really about seti@home anymore, they had a system set up that worked more or less for them since 99. What they are really doing is removing the enormous cost (enormous even after its been reduced from a direct super computer) of setting up a distributed computing network, up until boinc it was tons of different standards that each in house dev team had to make from scratch. boinc is a system that lowers the cost (in terms of time and knowledge) to enter the distributed market.
This is a mostly good thing, unless you have some n00bs like BURP (rendering project) that make a bug that nukes your local machine account info. This is mostly balanced out by the ability to run multiple projects at once, a good example is that seti@home has been down for about a week, but BOINC still runs and you can run other projects seamlessly.
In 5 years it will be even easier to enter the distributed market, you will never see BOINC or its derivatives take over classical supercomputers, but as the costs go down you will see much more innovative uses for this computing power.
cpu time for money? (Score:4, Interesting)
I have always been wondering, though, why *commercial* companies don't see the value in such distributed cpu systems? I mean, there are, for instance, commercial genetic-engineering companies, trying to solve the riddle of DNA strings... which usually costs a lot, for computertime on supercomputers. Now, it would seem to me that a system like boinc (but not exactly boinc, because I think it's not allowed for commercial use) would be financially a far better deal. Just give the 'users' some mild financial gain, and they will have a userbase by the millions in no time, while for the company itself it would still be cheaper then if they had to pay for regular supercomputer-time.
So, everybody (well, at least the capitalists
so why don't we see things like this, even after all these years?
Re:cpu time for money? (Score:2)
I investigated a commercial distributed possibility for signal processing using off cycles for seismic. A variety of issues popped up that made it a no go.
The logistics behind figuring out who gets paid for what is immense, especially for an application that's supposed to be non-intrusive. Couple that with "proprietary data" - end users want to know whats going on - and clients don't want to tell them.
The biggest stopper:
Terrabytes of data will take out your intranet even in off hours, and if you partitio
Re:cpu time for money? (Score:2)
Re:cpu time for money? (Score:2)
If I'm selling my CPU time I want to get at least what it costs me back, if not more.
But it's cheaper to setup a rack of quad-cpu blade servers than it is to pay people to run the software on their home computers and support the distribution of the data, and conceivably tech support for the home PC's. There's lots of overhead involved in the costs of running a PC and getting the data to that PC beyond the watts/cycle that the actual calculation costs.
Waste of good CPU cycles.... (Score:2)
What possible good is SETI@Home? Isn't working on Cancer or Folding proteins a much better use of the CPU time then trying to have some fantasy about Aliens trying to communicate with us?
It is very unlikely that we will ever find anything. If we do find it people will not believe it. There would probably be so little of the signal that it we would never understand it and it would be so old that likely the thing that sent it has long bee
What is the biggest volunteer computing project? (Score:2)
Re:Question... (Score:2)
Re:Question... (Score:2) | https://slashdot.org/story/05/08/29/1610208/interview-with-setihome-director-david-anderson | CC-MAIN-2017-04 | refinedweb | 4,101 | 71.44 |
SchunkMotionProtocol 0.1.3
Schunk Motion Protocol for Python 3
- Documentation:
-
- Code:
-
- Schunk Motion Protocol manual:
-
Disclaimer
This is not a commercial product and the author has no relation whatsoever to SCHUNK GmbH & Co. KG.
Use at your own risk!
Devices
Only 1 device was tested: Schunk PR-70 Servo Electric Swivel Unit.
Defaults for this device: RS232, baudrate=9600, module ID 11 (0x0B).
Other devices may or may not work.
Requirements
Python version 3.x is required. the RS232 protocol is implemented.
Installation
Using pip, you can download and install the latest release with a single command:
pip3 install --user SchunkMotionProtocol
If you want to install it system-wide for all users (assuming you have the necessary rights), you can just drop the --user option.
If you have only Python 3 installed on your system, you probably have to use pip instead of pip3.
To un-install, use:
pip3 uninstall SchunkMotionProtocol
If you prefer, you can also download the package from PyPI, extract it, change to the main directory and install it using:
python3 setup.py install --user
If you have only Python 3 installed on your system, you probably have to use python instead of python3.
If you want to get the newest development version from Github:
git clone cd schunk python3 setup.py install --user
Alternatively, you can just copy schunk.py to your working directory.
If you want to make changes to the code, you should type:
python3 setup.py develop --user
or, alternatively:
pip3 install --user -e .
… where -e stands for --editable.
Examples
This should get you started:
import schunk import serial mod = schunk.Module(schunk.RS232.RS232): super().__init__(schunk.RS232Connection( 0x0B, serial.Serial, port=0, baudrate=9600, timeout=1)) module1 = MySchunkModule() module1.move_pos(42)
- Author: Matthias Geier
- Download URL:
- Keywords: Schunk,RS232,servo,motor
- License: MIT
- Platform: any
- Categories
- Package Index Owner: spatialaudio, Matthias.Geier
- DOAP record: SchunkMotionProtocol-0.1.3.xml | https://pypi.python.org/pypi/SchunkMotionProtocol/0.1.3 | CC-MAIN-2017-22 | refinedweb | 319 | 58.79 |
title: ‘Breaking out your Django app for great good (This Old Pony #65)’ layout: newsletter published: true date: ‘2018-10-16T10:00:00.000Z’
Last week I told you that creating an open source reusable app was a good way of improving its quality. Some of you may have been disappointed, because the benefit is largely due to instrumental reasons which may not apply to your project. And further, creating a separate and open source version of functionality in your project turns out to be a non-trivial level of effort.
That’s okay, because I have good news! You can get many of the benefits without going through all the trouble of creating and publishing an open source package. You can get most of the benefits by simply pulling the functionality into it’s own app. And if you have multiple projects, you can still create and use an installable app without sharing it with the world.
In the Django Standalone App Fieldguide[0] I outline how one of the steps to pulling functionality out into a standalone app, i.e. one that’s published and downloadable on the Python package index, is creating a distinct, uniquely namespaced app in your own project. So for our purposes here you can stop there.
Let’s reiterate why you would do this, that is, what problems are you solving and what benefits should you expect, aside from more experience refactoring?
I’ve given some outlines on how to approach this in the most recent chapter, “Separating your app”.
What kind of obstacles have you faced in extracting code in your Django projects?
Wheel-installably yours
Ben
[0] Still in the editing process, including some content which is being embargoed until it can face minor editing: | https://wellfire.co/this-old-pony/breaking-out-your-django-app-for-great-good--this-old-pony-65/ | CC-MAIN-2019-18 | refinedweb | 294 | 60.95 |
Trigger custom commands from filesystem events.
Project description
Patrol
Trigger methods from changed files - e.g. selectively rebuild your project or run tests as soon as you hit the save button on your text editor or IDE.
Patrol works well with ProjectKey.
Use
To install:
pip install patrol
Example code:
import patrol def build(filenames): touch("output/build_started") time.sleep(2) touch("output/build_finished") def run_test(filenames): touch("output/test_started") time.sleep(30) touch("output/test_finished") patrol.watch([ patrol.Trigger( build, includes=["data/*", ], excludes=['data/exclude/*', 'output/*', ], ), patrol.Trigger( run_test, includes=["data/*", ], excludes=['data/exclude/*', 'output/*', ], reaper=patrol.Reaper(), # If triggered while method is in progress, this will stop it and start it again. fire_on_initialization=True, # When the watch is initiated, this trigger will also fire. ), ], directory=os.getcwd(), # By default it patrols the present working directory. lockfiles=[".git/index.lock", ], # This will wait until git has finished its operations before firing any triggers )
Features
- Patrol does not use polling to detect file changes. It uses libuv, which creates event driven hooks to filesystem events using epoll, kqueue or IOCP.
- You can queue up triggers when a specified lockfile is present - e.g. you can use to prevent triggers from firing until git operations are done.
- Patrol comes with a customized Reaper class that can be used to specify how a process is stopped.
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/patrol/ | CC-MAIN-2018-26 | refinedweb | 251 | 59.9 |
What is the status on virtfs? I am not sure if it is being maintained. Does anyone know?
- Luis ----- Original Message ----- From: "Danny Al-Gaaf" <danny.al-g...@bisect.de> To: "OpenStack Development Mailing List (not for usage questions)" <openstack-dev@lists.openstack.org>, ceph-de...@vger.kernel.org Sent: Sunday, March 1, 2015 9:07:36 AM Subject: Re: [openstack-dev] [Manila] Ceph native driver for manila Am 27.02.2015 um 01:04 schrieb Sage Weil: > [sorry for ceph-devel double-post, forgot to include > openstack-dev] > > Hi everyone, > > The online Ceph Developer Summit is next week[1] and among other > things we'll be talking about how to support CephFS in Manila. At > a high level, there are basically two paths: We discussed the CephFS Manila topic also on the last Manila Midcycle Meetup (Kilo) [1][2] > 2) Native CephFS driver > > As I currently understand it, > > - The driver will set up CephFS auth credentials so that the guest > VM can mount CephFS directly - The guest VM will need access to the > Ceph network. That makes this mainly interesting for private > clouds and trusted environments. - The guest is responsible for > running 'mount -t ceph ...'. - I'm not sure how we provide the auth > credential to the user/guest... The auth credentials need to be handled currently by a application orchestration solution I guess. I see currently no solution on the Manila layer level atm. If Ceph would provide OpenStack Keystone authentication for rados/cephfs instead of CephX, it could be handled via app orch easily. > This would perform better than an NFS gateway, but there are > several gaps on the security side that make this unusable currently > in an untrusted environment: > > - The CephFS MDS auth credentials currently are _very_ basic. As > in, binary: can this host mount or it cannot. We have the auth cap > string parsing in place to restrict to a subdirectory (e.g., this > tenant can only mount /tenants/foo), but the MDS does not enforce > this yet. [medium project to add that] > > - The same credential could be used directly via librados to access > the data pool directly, regardless of what the MDS has to say about > the namespace. There are two ways around this: > > 1- Give each tenant a separate rados pool. This works today. > You'd set a directory policy that puts all files created in that > subdirectory in that tenant's pool, then only let the client access > those rados pools. > > 1a- We currently lack an MDS auth capability that restricts which > clients get to change that policy. [small project] > > 2- Extend the MDS file layouts to use the rados namespaces so that > users can be separated within the same rados pool. [Medium > project] > > 3- Something fancy with MDS-generated capabilities specifying which > rados objects clients get to read. This probably falls in the > category of research, although there are some papers we've seen > that look promising. [big project] > > Anyway, this leads to a few questions: > > - Who is interested in using Manila to attach CephFS to guest VMs? > - What use cases are you interested? - How important is security in > your environment? As you know we (Deutsche Telekom) are may interested to provide shared filesystems via CephFS to VMs instead of e.g. via NFS. We can provide/discuss use cases at CDS. For us security is very critical, as the performance is too. The first solution via ganesha is not what we prefer (to use CephFS via p9 and NFS would not perform that well I guess). The second solution, to use CephFS directly to the VM would be a bad solution from the security point of view since we can't expose the Ceph public network directly to the VMs to prevent all the security issues we discussed already. We discussed during the Midcycle a third option: Mount CephFS directly on the host system and provide the filesystem to the VMs via p9/virtfs. This need nova integration (I will work on a POC patch for this) to setup libvirt config correctly for virtfs. This solve the security issue and the auth key distribution for the VMs, but it may introduces performance issues due to virtfs usage. We have to check what the specific performance impact will be. Currently this is the preferred solution for our use cases. What's still missing in this solution is user/tenant/subtree separation as in the 2th option. But this is needed anyway for CephFS in general. Danny [1] [2] -- To unsubscribe from this list: send the line "unsubscribe ceph-devel" in the body of a message to majord...@vger.kernel.org More majordomo info at __________________________________________________________________________ OpenStack Development Mailing List (not for usage questions) Unsubscribe: openstack-dev-requ...@lists.openstack.org?subject:unsubscribe | https://www.mail-archive.com/openstack-dev@lists.openstack.org/msg47116.html | CC-MAIN-2019-35 | refinedweb | 791 | 62.48 |
The WMI Command-line (WMIC) tool provides a simple command-line interface to WMI..
WMIC allows you to:
Browse the WMI schemas and query their classes and instances, usually by using aliases that make WMI more intuitive.
Work with the local computer, remote computers, or multiple computers by using a single command.
Customize aliases and output formats to suit your needs.
Create and execute scripts that are based on WMIC.
The WMI infrastructure is accessible as you use WMIC through intermediate facilitators called aliases. Aliases are used to capture the features of a WMI class that are relevant to some specific task, such as disk or network administration. Aliases can be used to provide better names for WMI classes, properties, and methods or to arrange properties in useful output formats. The output formats can include specific property values or be formatted in a manner that is appropriate to some specific presentation strategy or function. For example, an alias might have a BRIEF format that lists only property values that are essential for the identification of the objects visible through the alias. Management data is retrieved in XML format and processed by built-in or custom XSL output formats.
To start WMIC in interactive mode
On the taskbar, click Start, and then click Run.
In the Run dialog box, type WMIC, and then click OK.
The following appears, where root\cli is the default WMIC role: wmic:root\cli.
At the command prompt, enter an alias, command, or global switch, or enter /? for Help.
When you are done with WMIC in interactive mode, type Exit or Quit, and then press ENTER.
WMIC includes Help at the command line. At any level you can type /? and get additional details. By itself, /? provides the available global switches and the aliases that are available in the current role. When used after an alias, /? provides the verbs and switches available for that alias. After a verb, /? provides the details for that verb.
For example:
wmic:root\cli /?
Provides a list of the syntax and available aliases, including the process alias.
wmic:root\cli process /?
Displays options that are available for the process alias.
For more information about WMIC, see the Windows XP Help or the Help in the Windows Server 2003 family.
To use WMIC with SMS, try commands such as:
wmic:root\cli /namespace:\\root\SMS\site_MSO
wmic:root\cli PATH SMS_Collection
wmic:root\cli PATH SMS_R_System.LastLogonUserName='PTHOMSEN'
wmic:root\cli /namespace:\\root\cimv2
The last line is necessary to return WMIC to its normal namespace, as used in the predefined WMIC aliases.
Did you find this information useful? Please send your suggestions and comments about the documentation to
smsdocs@microsoft.com. | http://technet.microsoft.com/en-us/library/cc181088.aspx | crawl-002 | refinedweb | 449 | 58.08 |
53559/how-get-all-options-dropdown-using-python-selenium-webdriver
Hi Ankita, you can fetch all options from a dropdown using following commands in python selenium webdriver:
from selenium import webdriver
browser = webdriver.Firefox()
select_box = browser.find_element_by_name("month")
options = [x for x in select_box.find_elements_by_tag_name("option")]
for element in options:
print element.get_attribute("value")
Hey Joel, you can use following lines ...READ MORE
You can read innerHTML attribute to get source of ...READ MORE
Hello @Umesh, if you want to get ...READ MORE
Hey Paula, to get the tagnameomal, to get the text of ...READ MORE
Hi Piyush, if you want to scroll ...READ MORE
OR
Already have an account? Sign in. | https://www.edureka.co/community/53559/how-get-all-options-dropdown-using-python-selenium-webdriver?show=53648 | CC-MAIN-2019-47 | refinedweb | 112 | 53.27 |
OpenCV is a bunch of stuff mainly dealing with processing images and videos on your computer. This is a standard library for Computer Vision for Python tasks. In this article, I will introduce you to a tutorial on OpenCV with Python.
What is OpenCV?
Perhaps this is the fundamental question that comes to mind. Well, that means “Open Source Computer Vision Library” launched by some avid coders in 1999 to incorporate image processing into a wide variety of coding languages. OpenCV is not limited to Python only, it also supports C and C++.
Also, Read – Python Libraries for Machine Learning.
OpenCV with Python
My expertise is in Machine Learning and Python. So I will explain all the concepts of this computer vision library with context to Machine Learning and Python. So let’s get started with some fundamentals of OpenCV with python by looking at how it works with a practical example:
Code language: JavaScript (javascript)Code language: JavaScript (javascript)
import cv2 cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
The above script is to create a video capture, then insert it into a loop where the frames are played and displayed one by one with imshow, the conditional checks for the exit command, cap.release and then cv2.destroyAllWindows outside the loop then takes care of the final cleanup. The result should be a video stream with the default OpenCV user interface:
Colorspaces in OpenCV
There are several color spaces and transformations available, and the topic deserves its message. For now, let’s just turn the previous example into another color space:
Code language: PHP (php)Code language: PHP (php)
import cv2 cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() # Change colorspace: gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
Transformations in OpenCV with Python
You’ll find that most of the examples use a cascade (incremental steps) of transformations and operations in the main loop, so for example, here’s a more complex set:
Code language: PHP (php)Code language: PHP (php)
import cv2 cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() # --------CASCADE--------- # Convert to Greyscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Denoise (also try bluring, this is expensive ) denoised = cv2.fastNlMeansDenoising(gray, h=3, templateWindowSize=7, searchWindowSize=21) # Apply threshold thresholded = cv2.adaptiveThreshold(denoised, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) # Mirror image mirrored = cv2.flip(thresholded, 1) # --------***--------- cv2.imshow('frame', mirrored) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
User Interface Using OpenCV with Python
OpenCV also provides very simple User Interface tools that you can use to create prototypes, here is an example:
OpenCV with Python for Machine Learning
Beyond basic image and video manipulation, OpenCV is a popular method for machine learning and computer vision in python, once again there is a lot to offer, like the detection of objects:
Also, Read – How to Create a Package with Python?
I hope you liked this article on Computer vision with Python. Feel free to ask your valuable questions in the comments section below. You can also follow me on Medium to learn every topic of Machine Learning and Python. | https://thecleverprogrammer.com/2020/08/31/opencv-with-python-tutorial/ | CC-MAIN-2021-04 | refinedweb | 554 | 57.87 |
The QMailMessageListModel class provides access to a list of stored messages. More...
#include <QMailMessageListModel>
This class is under development and is subject to change.
Inherits QAbstractListModel.
The QMailMessageListModel class provides access to a list of stored messages.
The QQMailMessageListModel presents a list of all the messages currently stored in the message store. By using the setKey() and sortKey() functions it is possible to have the model represent specific user filtered subsets of messages sorted in a particular order.
The QMailMessageListModel is a descendant of QAbstractListModel, so it is suitable for use with the Qt View classes such as QListView to visually represent lists of messages.
The model listens for changes reported by the QMailStore, and automatically synchronizes its content with that of the store. This behaviour can be optionally or temporarily disabled by calling the setIgnoreMailStoreUpdates() function.
Messages can be extracted from the view with the idFromIndex() function and the resultant id can be used to load a message from the store.
For filters or sorting not provided by the QMailMessageListModel it is recommended that QSortFilterProxyModel is used to wrap the model to provide custom sorting and filtering.
See also QMailMessage and QSortFilterProxyModel.
Represents common display roles of a message. These roles are used to display common message elements in a view and its attached delegates.
Constructs a QMailMessageListModel with a parent parent.
By default, the model will match all messages in the database, and display them in the order they were submitted, and mail store updates are not ignored.
See also setKey(), setSortKey(), and setIgnoreMailStoreUpdates().
Deletes the QMailMessageListModel object.
Returns the QMailMessageId of the message represented by the QModelIndex index. If the index is not valid an invalid QMailMessageId is returned.
Returns true if the model has been set to ignore updates emitted by the mail store; otherwise returns false.
See also setIgnoreMailStoreUpdates().
Returns the QModelIndex that represents the message with QMailMessageId id. If the id is not conatained in this model, an invalid QModelIndex is returned.
Returns true if the model contains no messages.
Returns the QMailMessageKey used to populate the contents of this model.
See also setKey().
Signal emitted when the data set represented by the model is changed. Unlike modelReset(), the modelChanged() signal can not be emitted as a result of changes occurring in the current data set.
Sets whether or not mail store updates are ignored to ignore.
If ignoring updates is set to true, the model will ignore updates reported by the mail store. If set to false, the model will automatically synchronize its content in reaction to updates reported by the mail store.
If updates are ignored, signals such as rowInserted and dataChanged will not be emitted; instead, the modelReset signal will be emitted when the model is later changed to stop ignoring mail store updates, and detailed change information will not be accessible.
See also ignoreMailStoreUpdates().
Sets the QMailMessageKey used to populate the contents of the model to key. If the key is empty, the model is populated with all the messages from the database.
See also key().
Sets the QMailMessageSortKey used to sort the contents of the model to sortKey. If the sort key is invalid, no sorting is applied to the model contents and messages are displayed in the order in which they were added into the database.
See also sortKey().
Returns the QMailMessageSortKey used to sort the contents of the model.
See also setSortKey(). | https://doc.qt.io/archives/qtextended4.4/qmailmessagelistmodel.html | CC-MAIN-2019-26 | refinedweb | 565 | 57.47 |
:warning: This project is unmaintained experimental legacy code. It has been obsoleted by SwiftNIO which contains the recommended HTTP API of the Swift Server Work Group.
It remains here for historical interest only.
The following code implements a very simple "Hello World!" server:
import Foundation import HTTP func hello(request: HTTPRequest, response: HTTPResponseWriter ) -> HTTPBodyProcessing { response.writeHeader(status: .ok) response.writeBody("Hello, World!") response.done() return .discardBody } let server = HTTPServer() try! server.start(port: 8080, handler: hello) RunLoop.current.run()
The
hello() function receives a
HTTPRequest that describes the request and a
HTTPResponseWriter used to write a response.
Data that is received as part of the request body is made available to the closure that is returned by the
hello() function. In the "Hello World!" example the request body is not used, so
.discardBody is returned.
The following code implements a very simple Echo server that responds with the contents of the incoming request:
import Foundation import HTTP func echo(request: HTTPRequest, response: HTTPResponseWriter ) -> HTTPBodyProcessing { response.writeHeader(status: .ok) return .processBody { (chunk, stop) in switch chunk { case .chunk(let data, let finishedProcessing): response.writeBody(data) { _ in finishedProcessing() } case .end: response.done() default: stop = true response.abort() } } } let server = HTTPServer() try! server.start(port: 8080, handler: echo) RunLoop.current.run()
As the Echo server needs to process the request body data and return it in the reponse, the
echo() function returns a
.processBody closure. This closure is called with
.chunk when data is available for processing from the request, and
.end when no more data is available.
Once any data chunk has been processed,
finishedProcessing() should be called to signify that it has been handled.
When the response is complete,
response.done() should be called.
Full Jazzy documentation of the API is available here:
We are actively seeking feedback on this prototype and your comments are extremely valuable. If you have any comments on the API design, the implementation, or any other aspects of this project, please email the
swift-server-dev mailing list.
We also welcome code contributions. If you are developing on macOS, you may want to work within Xcode. This project uses the Swift Package Manager. To work on this project within Xcode you can run the Swift Package Manager command
swift package generate-xcodeproj to generate an
.xcodeproj to work on within Xcode.
This project is based on an inital proposal from @weissi on the swift-server-dev mailing list:
Provides a basic HTTP server that responds to incoming requests.
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics | https://swiftpack.co/package/swift-server/http | CC-MAIN-2022-27 | refinedweb | 424 | 51.55 |
On Tue, 24 Mar 2009 16:48:30 -0600, Wes James wrote: > On Tue, Mar 24, 2009 at 4:32 PM, Wes James <comptekki at gmail.com> wrote: >> On Tue, Mar 24, 2009 at 4:04 PM, Scott David Daniels >> <Scott.Daniels at acm.org> wrote: >>> Atul. wrote: >> >> <snip> >> >>> In your case, '\r' is a return (a single character), not two >>> characters long. I think its sad that 'C:\Thesis' doesn't cause an >>> error because there is no such character as '\T', but I am probably >>> excessively pedantic. >> >> \T might mean the same thing as \t (tab), but I thought it would be >> different... > > > I guess not: > > > > Wonder why when I do print "test\Ttest" vs print "test\ttest" \T just > get printed? Did you read the section you just linked to? It says so right there: ." Since there is no standard escape \T then it gets treated as a literal backslash + uppercase t. -- Steven | https://mail.python.org/pipermail/python-list/2009-March/530277.html | CC-MAIN-2016-44 | refinedweb | 156 | 91.92 |
I'm back again for some more homework help.
I just want to start off by saying thanks for assisting me in my last assignment. This one, I have to allow it to Enter a name, and enter grades for that name, and then it will display the average for that name. It should then ask for another name, until the user enters end for the name. Sorry for the horrible formatting, I'm working on getting better.
#include <iostream> #include <string> using namespace std; int main () { int sum = 0; int smallest = 100; int ct = 0; string name; int x; int bavg; int avg; cout << "Enter a name: " << endl; cin >> name; while (name != "end" && name != "END"){ //checks for the end cout << "Enter a test score (to stop press -999)" << endl; cin >> x; if ( x == -999){ goto name; //first time using this, not sure if this will work } //i think this should go to the string name?? if (x < 0 || x > 100){ //check cout << "You must enter a new value from 0 to 100: "; cin >> x; } //end of if check ct++; //+1 to # of items entered sum += x; //adds the grade entered to the previous amount of sum if (x < smallest) { //this checks for the smallest number entered smallest = x; } //end of if smallest cout << "Enter another test score: " << endl; cin >> x; if ( x == -999){ goto name; } cout << "The sum of the dataset is: " << sum << endl; cout << "The smallest number is: " << smallest << endl; cout << "The number of items in the dataset is: " << ct << endl; bavg = sum - smallest; //takes the sum and subtracts the smallest avg = bavg / ct; //takes the average and divides by the # of items //Displays the name and the average cout << "The student, " << name << ", had the following average with the" << "lowest score being dropped: " << avg << endl; //Get's a new name cout << "Enter a name: " << endl; cin >> name; } return 0; }
I think one of my problems is that the numbers stay in memory for those integers. So everytime I enter a new person, it still has the previous persons grades. I think I can fix this by setting the values back to their original value after it ask for a new name at the bottom of the while loop.
The goto statement I put in there, I have yet to test. I was just suggested that I should use this. Could someone explain to me how the goto works?
Other problems I'm having, are, it only allows me to enter one value for each name. What do you people suggest I do to get it to input more values until the user decides that is enough, and then it outputs the average and sum and such, then ask for a new name and repeats the process?
Thanks for any help | https://www.daniweb.com/programming/software-development/threads/109331/homework-help-loop-help | CC-MAIN-2017-30 | refinedweb | 462 | 67.83 |
I create a fully functional AI out of a Raspberry Pi - including voice recognition, facial recognition, and text-to-speech.
I create a fully functional AI out of a Raspberry Pi - including voice recognition, facial recognition, and text-to-speech.
Here is the list of my hardware components (as of 02/05/14):becausewhich works well although I can’t use power line codes with it. Note - if you want cheap X10 stuff, check out eBay.
Given.
Now how does it work? Lets find out!
I + "'")
The.
Now how does it work? Lets find out!
Once):
Now how does it work? Lets find out!
So for a face, I thought I would try making some sort of realtime voice animating system. I made a very very simple one in python. Here is an example of what it looks like and sounds like:
The source code is very simple. Get the whole code at my github page (the following excludes the saySomething function which is part of
mouth_function. Basically the following code opens a process to say something and at the same time tries to animate it with an open/closing mouth. The timing between the mouth open and mouth closed comes from an average timing I got from recording the Google TTS and recording how much time it takes to say a word and the amount of time between words. The other trick is to count the number of syllables in a word.
Python has a fast way of doing this using
nltk (coded below).
import pygame, sys, time, random from pygame.locals import * from time import * import curses from curses.ascii import isdigit import nltk from nltk.corpus import cmudict import os import thread import threading d = cmudict.dict() def nsyl(word): return [len(list(y for y in x if isdigit(y[-1]))) for x in d[word.lower()]] pygame.init() windowSurface = pygame.display.set_mode((500, 400), 0, 32) pygame.display.set_caption("Bounce") BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255,255,0) info = pygame.display.Info() sw = info.current_w sh = info.current_h y = 0 phrase = "Hi there. How are you doing"", 35) pygame.display.update() sleep(1) paragraph = str(sys.argv[1]) thread.start_new_thread( saySomething,(paragraph,"en",)) workingSentence = "" sleep(0.26) for phrase in paragraph.split("?"): for sentence in phrase.split("."): for word in sentence,220,50,30),0) myfont = pygame.font.SysFont("ComicSans", 17) workingSentence += word + " " label = myfont.render(workingSentence, 1, BLACK) windowSurface.blit(label, (5, 5)) pygame.display.update() syl = nsyl(word) syl = syl[0] sleep(0.185*float(syl)).0.16) sleep(1)
This. | https://schollz.com/blog/ai-bot/ | CC-MAIN-2022-27 | refinedweb | 444 | 70.39 |
So what is this Semantic Web, anyway? Where does the Web come in? So far you've shown us just a language for writing data.
(You do need to know this bit!)
log:semanticsand
log:includes
Life in the real world is full of data from different places. Rather than putting all the data into one big pot and believing it, rules often have to look specifically at which document said what.
Cwm has built-in functions to allow it to interact with the web. The concept of a formula - a set of RDF statements - allows it to consider separate sets of data.
The basic function which connects RDF to the web is
log:semantics. The
log:semantics of a document is the formula which one gets by
parsing a semantic web document. As it is a built-in function, when cwm needs
to evaluate it it will pick up the document (N3 or RDF/XML) and parse it,
returning the formula1.
{ <foo.rdf> log:semantics ?f } => { ?f a :InterestingFormula}.
Having got a formula, we can test what it says using
log:includes. One formula
log:includes a second
formula if for each statement in the second, there is a corresponding one in
the first. This the same pattern matching which happens with
log:implies rules: the names of variables do not have to
match.
So let's say we we have a concept of a semantic web home page for a person. We decide on the policy that if someone's home page says that they are a vegetarian, then we believe that they are a vegetarian.
@forAll :x.
{:x :homePage log:includes { :x a :Vegetarian }}=> { :x a :Vegetarian}.
Why didn't we use the
?x form there? Well, we have some
nested formulae. The variable x is quantified in the scope of the whole
document. The definition of ?x is that it is quantified in the scope of not
the immediate formula but the next enclosing formula. So we can't use it at
different levels of nesting. We are not asking whether the home page includes
"For all x, x is vegetarian". This is an example of how one must be explicit
about the scope of variables when they are used at more than one level.
log:notIncludes
Because a formula is a finite size, you can test for what it does
not say, with
log:notIncludes. Here, we have a rule
that is the specification for a car doesn't say what color it is then it is
black.
@forAll :car.
{ :car.auto:specification log:notIncludes {:car auto:color []}}
=> {:car auto:color auto:black}.
Note the use of [] here in the nested formula as a blank node. If the spec
said that a car had color green, then that would mean that the car had color
something, so we would say that the formula included
:car auto:color
[] . A statement with a [] in it you can think of as weaker version of
one with a value for the color.
This is a way to do defaults. Notation3 as it is doesn't have defaults,
because on the web, you can't say "if nothing says it is another color". You
can never know in the whole web whether anyone has given a color. Also, if we
start to just loosely talk about defaults in the sense of if you don't
already know a color, then different agents will end up drawing
different conclusions from the same data, which is not a good foundation for
a scalable web. So, you handle defaults by first running rules to work out
everything which is specified, and then on the result of that do a
notIncludes rule like that above to implement the default
values.
log:conclusion.
log:content,
log:n3String,
log:uri
The nice thing about
log:semantics is that it deals with all
the web protocols in one simple function. This is a simple, clean, view of
the web as a set of interwoven formulae.
It is possible also to get a little more involved, using the following functions which separate the looking up from the parsing.
log:uri
<> log:uri "".
log:content
log:parsedAsN3
log:N3String
One of the uses of this, as we will see in the next section, is to test the digital signature of a string before accepting the data encoded in it.
log:definitiveServiceand
log:definitiveDocument
There is some properties for which there is just a well-defined set of
values. The state codes of the US states is an example. There are 50 states,
and each has one state code and one state name. Once you know them, you know
them. Once you know where to look them up, you can resolve any query about
them. That's got to be useful. It is represented by giving, somewhere, a
log:definitiveDocument for a the property. This is metadata -
data about data. You have a lot of control over where cwm will look for
metadata, and how it will use it.
This behaviour is controllable in cwm by the --mode flags. By default cwm won't doing anything about it at all. (See:Cwm's --mode flags in manual page). When cwm runs with r and s mode flags, and it finds in the query it i strying to match a statement whose predicate has a definitive document, then it will read the document, and search it (alone) to resolve that query.
Therflag is necessary for any of this to work. This causes it to check for metadata in the working formula - the current dataset.
The s flag makes cwm also check for schemas. It does this only when trying to resolve a query. If the predicate is from a namespace it doesn't know, it will go to the web to see what it can learn. Unless the eflag is set, then it won't mind if there are any errors in this process, it will just abandon it.
Most vocabularies, ontologies, have all kinds of metadata which helps a query engine resolve questions posed using those terms. Much of the interesting semantic web development will be in seeing what kind of meta data is most useful to leave, and how best to use it. The definitiveDocument property is a simple one, and the simplest way of using it is to let cwm pick it up either from the current store or a schema.
For an example, look at this file expressing query involving US state information.
@prefix : <#>.
@prefix log: <>.
@prefix state: <data/USRegionState.n3#> .
@prefix city: <data/USCity.n3#>.
# Question: What cities are in states bordering Massachusetts?
{"MA"^state:code.state:borderstate^city:state city:name ?n}
=>{ ?n a :NAME_OF_CITY_IN_A_STATE_BORDERING_MASSACHUSETTS }.
Its a rather random example (think of a better one? let us know! ;-), to look up the states bordering Massachusetts, and specifically the names of major cities in that state. Massachusetts is identified as the state with state code "MA". So what happens if we load this into cwm and do a --think? Nothing. Cwm just prints out the file reformatted. Now run it in remote query mode with schema fetch:
cwm --mode=rse --think
and -- voila -- we get:
"Albany" a :NAME_OF_CITY_IN_A_STATE_BORDERING_MASSACHUSETTS .
"Amherst" a :NAME_OF_CITY_IN_A_STATE_BORDERING_MASSACHUSETTS .
"Avon" a :NAME_OF_CITY_IN_A_STATE_BORDERING_MASSACHUSETTS .
...
and so on.
To do more fancy things, you can run cwm in a mode which loads the
By now you should know how to publish tables of useful information on the semantic web. You should know how to use published data and semantic web services and SQL servers to answer parts of your queries. You are starting to get into some useful scalable stuff, and the next thing you know you'll be needing to reign in your system before it explores the whole world. You'll be needing to think about trust. Fortunately, you already have some of the tools: you can write rules which keep track of data from different places separately. Now all you need is some crypto ....
1. Of course, the value of this function depends on the real world, which can change. Many systems either assume that other documents won't change, or accept that the information derived from them will change with them. It is would also possible to model the time at which a given representation of a document was returned by a server, and what expiry date was given, and so on, and the reader is welcome to experiment with such schemes where they are needed. Cwm does not currently( 2003/2) provide the functionality of looking inside the HTTP response to extract the protocol headers which convey time-related information.
Gerd points to ..."Local Closed World" as a term for what definitiveDocument and log:notIncludes. are doing. Jeff Heflin Paper. | http://www.w3.org/2000/10/swap/doc/Reach | CC-MAIN-2015-48 | refinedweb | 1,458 | 73.07 |
Learn to use TPOT: An AutoML Tool
Get FREE domain for 1st year and build your brand new site
Reading time: 30 minutes | Coding time: 10 minutes
In this article, I will share some of my insights based on TPOT (Tree Base Pipeline Optimization Tool). I will explain this tool through a dataset I used.
What is TPOT?
T. We feed the data which is the train input and train output. It analyzes the data and tell us the best machine learning model for the purpose.
TPOT is open source and is a part of scikit learn library. It can be used for both regression and classification models. Implementation and loading of library is different for each.
Working of TPOT (Using a dataset)
It is like a search algorithm which usually searches best algorithm for the purpose. The final search results basically depends on performance means which algorithm providing greater accuracy than other algorithms.It also tunes some hyperparametres for better performances and evaluation. So it cannot be considered as a random search algorithm.
Now generally there are two types of TPOT:
- TPOT classifier
- TPOT regressor.
We will study working of each using a dataset.
TPOT Classifier
For the purpose we have taken a dataset of a bank data which contains information about their customers.
Data cleaning was performed to get the data into required form. After performing several function we get the data into required form.
Response Variable: default payment next month
Exploratory Variable: ID, Marriage, Age, Bill_AMT1...Bill_AMT5
train=df.drop('default payment next month',axis=1) test=df['default payment next month'] from sklearn.preprocessing import StandardScaler sc=StandardScaler() train=sc.fit_transform(train) from sklearn import model_selection x_train,x_test,y_train,y_test=model_selection.train_test_split(train,test)
Implementing TPOT Classifier
from tpot import TPOTClassifier from sklearn.metrics import roc_auc_score
The default TPOTClassifier arguments:
generations=100,
Our Model:
pot = TPOTClassifier( generations=5, population_size=20, verbosity=2, scoring='roc_auc', random_state=42, disable_update_check=True, config_dict='TPOT light' ) tpot.fit(x_train, y_train)
After running the model we get the result:
tpot_auc_score = roc_auc_score(y_test, tpot.predict_proba(x_test)[:, 1]) print(f'\nAUC score: {tpot_auc_score:.4f}')
Output:
0.660
To know the best model:
print('\nBest pipeline steps:', end='\n') for idx, (name, transform) in enumerate(tpot.fitted_pipeline_.steps, start=1): print(f'{idx}. {transform}')
Further you can perform other algorithms like GridSearchCV to tune the hyperparametres.
Results we got after using the algorithm told by tpot
TPOT Regressor
For this purpose we considered a dataset from RBI website.
We performed the data cleaning part and recieve the data in required form
Response Variable: Growth
from sklearn.preprocessing import StandardScaler sc=StandardScaler() df=sc.fit_transform(df) y=df[' Y-o-Y Growth in (7) (%)'] x=df.drop(' Y-o-Y Growth in (7) (%)',axis=1) from sklearn import model_selection x_train,x_test,y_train,y_test=model_selection.train_test_split(x,y)
Correlation of variable with response variable
Model Implementaion
from tpot import TPOTRegressor from sklearn.metrics import roc_auc_score tpot = TPOTRegressor( generations=5, population_size=50, verbosity=2, ) tpot.fit(x_train, y_train)
After running the model we get the results:
After using the algorithm told by TPOT we got excellent results
Useful Information about TPOT
There are some parametres on which tpot determine number of pipeline to be searched
generations: int, optional (default: 100)
Number of iterations to the run pipeline optimization process. Generally, TPOT will work better when you give it more generations(and therefore time) to optimize the pipeline. TPOT will evaluate POPULATION_SIZE + GENERATIONS x OFFSPRING_SIZE pipelines in total (emphasis mine).
population_size: int, optional (default: 100)
Number of individuals to retain in the GP population every generation.
Generally, TPOT will work better when you give it more individuals (and therefore time) to optimize the pipeline.
offspring_size: int, optional (default: None)
Number of offspring to produce in each GP generation. By default, offspring_size = population_size.
Algoriths included in latest tpot update:
‘sklearn.naive_bayes.BernoulliNB’: { ‘alpha’: [1e-3, 1e-2, 1e-1, 1., 10., 100.], ‘fit_prior’: [True, False] }, ‘sklearn.naive_bayes.MultinomialNB’: { ‘alpha’: [1e-3, 1e-2, 1e-1, 1., 10., 100.], ‘fit_prior’: [True, False] }, ‘sklearn.tree.DecisionTreeClassifier’: { ‘criterion’: [“gini”, “entropy”], ‘max_depth’: range(1, 11), ‘min_samples_split’: range(2, 21), ‘min_samples_leaf’: range(1, 21) }, ‘sklearn.ensemble.ExtraTrees.RandomForest.GradientBoostingClassifier’: { ‘n_estimators’: [100], ‘learning_rate’: [1e-3, 1e-2, 1e-1, 0.5, 1.], ‘max_depth’: range(1, 11), ‘min_samples_split’: range(2, 21), ‘min_samples_leaf’: range(1, 21), ‘subsample’: np.arange(0.05, 1.01, 0.05), ‘max_features’: np.arange(0.05, 1.01, 0.05) }, ‘sklearn.neighbors.KNeighborsClassifier’: { ‘n_neighbors’: range(1, 101), ‘weights’: [“uniform”, “distance”], ‘p’: [1, 2] }, ‘sklearn.svm.LinearSVC’: { ‘penalty’: [“l1”, “l2”], ‘loss’: [“hinge”, “squared_hinge”], ‘dual’: [True, False], ‘tol’: [1e-5, 1e-4, 1e-3, 1e-2, 1e-1], ‘C’: [1e-4, 1e-3, 1e-2, 1e-1, 0.5, 1., 5., 10., 15., 20., 25.] }, ‘sklearn.linear_model.LogisticRegression’: { ‘penalty’: [“l1”, “l2”], ‘C’: [1e-4, 1e-3, 1e-2, 1e-1, 0.5, 1., 5., 10., 15., 20., 25.], ‘dual’: [True, False] }, ‘xgboost.XGBClassifier’: { ‘n_estimators’: [100], ‘max_depth’: range(1, 11), ‘learning_rate’: [1e-3, 1e-2, 1e-1, 0.5, 1.], ‘subsample’: np.arange(0.05, 1.01, 0.05), ‘min_child_weight’: range(1, 21), ‘nthread’: [1] }
Limitation
TPOT sometimes take very long for the search of algorithm. Since it searches all algorithm, apply them on data we provided which can take long time. If we provide data without any preprocessing steps, it would take even more time as it first implement those steps and then apply the algorithms.
In some cases TPOT shows different results for same data provided. This happens when we work on complex dataset | https://iq.opengenus.org/tpot-python/ | CC-MAIN-2021-43 | refinedweb | 919 | 50.33 |
I really admire Portable Document Format (PDF) files. I remember the days when such files solved any formatting issues while exchanging files due to some differences in Word versions, or for other reasons.
We are mainly talking about Python here, aren't we? And we are interested in tying that to working with PDF documents. Well, you may say that's so simple, especially if you have used Python with text files (txt) before.
As we mentioned above, using an external module would be the key. The module we will be using in this tutorial is
PyPDF2. As it is an external module, the first normal step we have to take is to install that module. For that,!
PyPDF2 now can be simply installed by typing the following command (in Mac OS X's Terminal):
pip install pypdf2
Great! You now have
PyPDF2 installed, and you're ready to start playing with PDF documents.
Reading a PDF Document
The sample file we will be working with in this tutorial is sample.pdf. Go ahead and download the file to follow the tutorial, or you can simply use any PDF file you like.
Let's now go ahead and read the PDF document. Since we will be using
PyPDF2, we need to import the module, as follows:
import pypdf2
After importing the module, we will be using the PdfFileReader class. So, the script for reading the PDF document looks as follows:
import PyPDF2 pdf_file = open('sample.pdf') read_pdf = PyPDF2.PdfFileReader(pdf_file)
More Operations on PDF Documents
After reading the PDF document, we can now carry out different operations on the document, as we will see in this section.
Number of Pages
Let's check the number of pages in sample.pdf. For this, we can use the getNumPages() method:
number_of_pages = read_pdf.getNumPages() print number_of_pages
In this case, the returned value will be
1.
Page Number
Let's now check the number of some page in the PDF document. We can use the method
getPageNumber(page), Notice that we have to pass an object of type
page to the method. To retrieve a
page, we will use the
getPage(number) method, where
number represents the page number in the PDF document. The argument
number starts with the value
0.
Well, I know when you use
getPage(number) you already know the page number, but this is just to illustrate how to use those methods together. This can be demonstrated in the following script:
page = read_pdf.getPage(0) page_number = read_pdf.getPageNumber(page) print page_number
Go ahead, try the script. What output did you get?
We know that in
sample.pdf (the file we are experimenting with), we only have one page (number
0). What if we passed the number
1 as the page number to
getPage(number)? In this case, you will get the following error:
Traceback (most recent call last): File "test.py", line 6, in <module> page = read_pdf.getPage(1) File "/usr/local/lib/python2.7/site-packages/PyPDF2/pdf.py", line 1158, in getPage return self.flattenedPages[pageNumber] IndexError: list index out of range
This is because the page is not available, and we are using a page number out of range (does not exist).
Page Mode
The PDF page comes with different modes, which are as follows:
In order to check our page mode, we can use the following script:
page = read_pdf.getPage(0) page_mode = read_pdf.getPageMode() print page_mode
In the case of our PDF document (
sample.pdf), the returned value is
none, which means that the page mode is not specified. If you want to specify a page mode, you can use the method
setPageMode(mode), where
mode is one of the modes listed in the table above.
Extract Text
We have been wandering around the file so far, so let's see what's inside. The method
extractText() will be our friend in this task.
Let me show you the full script to do that, as opposed to what I was doing above in showing you only the required script to perform an operation. The script to extract a text from the PDF document is as follows:
import PyPDF2 pdf_file = open('sample.pdf') read_pdf = PyPDF2.PdfFileReader(pdf_file) number_of_pages = read_pdf.getNumPages() page = read_pdf.getPage(0) page_content = page.extractText() print page_content
I was surprised when I got the following output rather than that in
sample.pdf:
!"#$%#$%&%$&'()*%+,-%./01'*23%4 5'%1$#26%3/%7/))/8%&)/26%8#3"%3"*%313/9#&) %
paper.pdf. The output in this case was:
Medical Imaging 2012: Image Perception, Observer Performance, and Technology Assessment, edited by Craig K. Abbey, Claudia R. Mello-Thoms, Proc. of SPIE Vol. 8318, 83181I © 2012 SPIE · CCC code: 1605-7422/12/$18 · doi: 10.1117/12.912389Proc. of SPIE Vol. 8318 83181I-1Downloaded from SPIE Digital Library on 13 Aug 2012 to 134.130.12.208. Terms of Use:
But, where is the rest of the text in the page? Well, actually the
extractText() method seems not to be perfect, and some improvements need to be made. But, the goal here is to show you how to work with PDF files using Python, and it seems some improvements need to be made in the domain.
Conclusion
As we can see, Python makes it simple to work with PDF documents. This tutorial just scratched the surface on this topic, and you can find more details on different operations you can perform on PDF documents on the PyPDF2 documentation page.
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
| https://code.tutsplus.com/tutorials/how-to-work-with-pdf-documents-using-python--cms-25726 | CC-MAIN-2018-13 | refinedweb | 929 | 66.64 |
04 October 2012 03:30 [Source: ICIS news]
MELBOURNE (ICIS)--Korea Alcohol Industrial has increased its domestic ethyl acetate (etac) pricing for October, a company official said on Thursday.
The South Korean producer’s October etac price will be at won (W) 1,230/kg ($1,105/tonne) ex-works (EXW), up by W50/kg from September, the official said.
Its September etac price of W1,180/kg was itself a rollover from August.
Korea Alcohol, which operates an 85,000 tonne/year etac/butyl acetate (butac) swing plant in ?xml:namespace>
South Korean demand for etac in 2011 was estimated by market sources at 90,000-100,000 tonnes. Most of the 69,000 tonnes of etac imported in 2011 were from
($1 = W 1,113 | http://www.icis.com/Articles/2012/10/04/9600879/korea-alcohol-raises-domestic-etac-price-by-w50kg-for.html | CC-MAIN-2014-49 | refinedweb | 127 | 61.87 |
According to the W3Techs surveys, 94.1% of websites use images. Being able to deliver high quality images that are loaded fast, optimized for the correct screen size, and in the ideal format is a critical part of the user experience.
With Vercel you can optimize images at the Edge and dynamically serve different variations of your image, while reducing the file size, and optimizing the images quality. This is a great way to improve your website's loading speed, user experience and improve your Core Web Vitals.
With Image Optimization:
- Improved loading performance due to images being cached at the Edge
- Reduction in bandwidth usage, which saves you money
- Minimizing the risk of lost traffic due to slow page speeds
- Improving the overall visitor experience
Benefits
Images are often the first element people see when visiting a site. They can take up a large viewport area, and on mobile or tablet devices they can even take up the whole viewport width.
Having large images both in dimension and size can affect how people interact with your website if they are not properly optimized for different devices, and network speeds.
Consider an un-optimized image loaded when not in the viewport. The image is taking up unnecessary bandwidth, won't be viewed until the visitor scrolls to it, and can cause a delay in the loading of the page as a whole.
Imagine you have an e-commerce store and the page is too slow to load due to un-optimized product images, this can cause people to navigate away from your site, meaning a potential loss in revenue.
In addition to image size, image formats are often over looked, with many websites not optimizing for the different formats available, such as Webp or AVIF.
Edge Network Optimization
Vercel's Image Optimization can be used with both the Next.js and Nuxt.js image components. When these components are used, the images are cached at the Edge and shared across the Vercel Edge Network making them available to all visitors at their nearest point.
With Vercel's Image Optimization the benefits include:
- Images appear faster due to small file sizes
- The correct image sizes are served based on the device's screen size
- When used with either Next.js or Nuxt image components, a blur-up placeholder can be used to indicate the image is loading
- Images can be lazy-loaded to improve initial page load performance
Usage
Once deployed, the component will dynamically serve different variations of your image for common device screen sizes used by visitors on the web.
All the variations of your image requested by the component will automatically be prefixed depending on the framework:
- If using Next.js:
/_next/image?url=
- If using Nuxt.js:
/_vercel/image?url=
This /
/_vercel/image will be preserved.
Vercel creates a cache key using the following:
- Content hash for static images (or external URL for remote images)
- Query String parameters (
w,
q, etc.)
AcceptHTTP header
The
Accept HTTP header is normalized so that different browsers can utilize the same Edge Cache. using
next/image:
- counts the number of unique Source Images requested during each billing period. Since images are optimized on-demand, the Source Image is not counted until a request is made to optimize it at runtime. This means that usage can be lower if no one visited a page with an image in a given billing period. It also means there is an upperbound of Source Images which can be derived by the number of unique
src props for all
next/image components in your application.
See the common usages of
next/image listed below:
import img from './img.png'; <Image src={img} />at-most, counts as 1 Source Image if the image is requested during the billing period.
<Image src="/logo.png" width={100} height={100} />at-most, counts as 1 Source Image if the image is requested during the billing period.
<Image src={' width={100} height={100} />counts as N Source Images - one for each unique
pathrequested during the billing period.
<Image src={img} loader={myCustomerFunc} />counts as 0 Source Images since optimization is performed by a 3rd party image provider, not Vercel.
<Image src={img} unoptimized />counts as 0 Source Images since the image is never optimized.
At the start of a billing period, the Source Image count starts at zero. Deleting an image and making a new deployment will not impact the Source Image count for the current billing period if it has already been requested as it has already been counted. You won't see the Source Image count drop until the following billing period.
Next.js projects that configure the loader config or unoptimized prop will opt out of Vercel Image Optimization in favor of a 3rd party image provider. Therefore, the Usage page will show 0 Source Images each billing period. and Pricing
For information on the limits that are applicable to using Image Optimization, and the costs that they incur, please see the Limits and Pricing page.
Measuring Performance
Before you adopt Image Optimization in an existing project, enable Analytics for it.
This will allow you to measure real-world performance & user experience over time and compare the before and after Image Optimization. | https://vercel.com/docs/concepts/image-optimization | CC-MAIN-2022-21 | refinedweb | 874 | 50.87 |
9 Feb 22:02 2013
Re: EBImage: putting two images next to each others
Gregoire Pau <pau.gregoire@...>
2013-02-09 21:02:10 GMT
2013-02-09 21:02:10 GMT
Hello Simon, The method abind hasn't been overloaded in EBImage and returns an array, instead of an Image object, and loses the "colormode " property, which is needed by display() to render an image (since a multidimensional array could represent either a sequence of grayscale images or a color image). The array has to be recasted in an Image: the following code should work: > display(Image(abind( lena, lena, along=1 ), colormode=Color)) It should be easy to overload abind in EBImage. Cheers, Greg On Sat, Feb 9, 2013 at 4:58 AM, Simon Anders <anders@...> wrote: > Hi Andrzej (or anybody else who might know), > > if I have to Image objects with the same vertical size, how can I combine > them into one wide Image object, with the two images placed next to each > other? > > I tried the following: > > library( EBImage) > lena <- readImage(system.file("images"**, > "lena-color.png", package="EBImage")) > display( abind( lena, lena, along=1 ) ) > > This work, but Lena turns from colour to black&white. > > Thanks in advance > Simon > > > sessionInfo() > R version 2.15.2 (2012-10-26) > Platform: x86_64-pc] abind_1.4-0 EBImage_4.0.0 > > loaded via a namespace (and not attached): > [1] jpeg_0.1-2 png_0.1-4 tiff_0.1-3 tools_2.15.2 > > ______________________________**_________________ > Bioconductor mailing list > Bioconductor@... >**listinfo/bioconductor<> > Search the archives:.** > science.biology.informatics.**conductor<> > [[alternative HTML version deleted]] _______________________________________________ Bioconductor mailing list Bioconductor@... Search the archives: | http://permalink.gmane.org/gmane.science.biology.informatics.conductor/46282 | CC-MAIN-2014-35 | refinedweb | 268 | 55.34 |
inheritance and contstuctors problem
Gerry Giese
Ranch Hand
Joined: Aug 02, 2001
Posts: 247
posted
Dec 17, 2001 11:18:00
0
I had a weird problem today. I was experimenting with a framework library and came across a compile-timer error that deals with inheritance and constructors. I wrote up the following code to demonstrate the problem:
import java.util.Hashtable; public class DBQuery extends DBObject { String query = "select emp.name from emp, company where company.name='Greedy, Inc.'"; public String runQuery() { DBConnection conn = getConnection(); return conn.runQuery( query ); } public static void main (String [] args) { Hashtable hash = new Hashtable(); hash.put( "user", "bob" ); hash.put( "pass", "bob" ); DBQuery q = new DBQuery( hash ); System.out.println( "Result = [" + q.runQuery() + "]" ); } } // End of class DBQuery import java.util.Hashtable; public abstract class DBObject { String dbURL = "jdbc:thin:and:other:nonsense"; Hashtable dbSettings = null; DBConnection conn = null; //public DBObject() { } public DBObject( Hashtable hash ) { dbSettings = hash; conn = new DBConnection( (String)dbSettings.get("user"), (String)dbSettings.get("pass"), dbURL ); } public DBConnection getConnection() { return conn; } } // End of class DBObject public class DBConnection { public String user, pass, url; public DBConnection( String user, String pass, String url ) { this.user = user; this.pass = pass; this.url = url; } public String runQuery( String query ) { return "John"; } } // End of class DBConnection
BTW, yes, each is in a separate file. The javac compiler reported the following:
DBQuery.java:3: No constructor matching DBObject() found in class DBObject. public class DBQuery extends DBObject ^ DBQuery.java:18: Wrong number of arguments in constructor. DBQuery q = new DBQuery( hash );
If I go and uncomment the empty constructor in DBObject.java it gets rid of the first error. If I add an empty constructor to DBQuery.java, it does nothing. If I add the parameter "Hashtable h" to the empty constructor (and do nothing with it) then it compiles just fine.
My question is why do I need to add the constructors? Shouldn't DBQuery be allowed to call the public constructor extended from DBObject? Do all constructors for an abstract class need to be implemented in a subclass?
I want to enforce a rule that all objects extending DBObject must use the constructor with the Hashtable so that I know each one has a proper database connection at object creation time so there's no lag when calling getConnection(). If I have a default constructor that doesn't do setup a connection, then the object is in an unknown state and not very useable. Is there a way to do that? Or am I crazy to be thinking I can do this?
CJP (Certifiable Java Programmer), AMSE (Anti-Microsoft Software Engineer)
Author of
Posts in the Saloon
Cindy Glass
"The Hood"
Sheriff
Joined: Sep 29, 2000
Posts: 8521
posted
Dec 17, 2001 12:01:00
0
Constructors are not inherited. You do not have a constructor in the DBQuery class that takes a Hashtable.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Gerry Giese
Ranch Hand
Joined: Aug 02, 2001
Posts: 247
posted
Dec 17, 2001 12:34:00
0
Thanks, Cindy. While not quite what I was looking for in terms of explanation, it triggered something in my flu-delerious brain (I hate coding when I'm sick - I get brilliant flashes more often, but the basic stuff ends up worse than normal).
I left the empty constructor in DBOject commented out, but added a constructor to DBQuery accepting a Hashtable, and in it called super( hash ), which seems to have done the trick.
Seems kinda silly that you have to do this, though. Why wouldn't you want to inherit constructors?
Cindy Glass
"The Hood"
Sheriff
Joined: Sep 29, 2000
Posts: 8521
posted
Dec 17, 2001 12:49:00
0
Well for one thing - the rule is that the name has to match. If you inherit the parent classes constructor, it will not have the same name as the subclass.
If you allowed constructors to be inherited then they could be overridden. If that happened then you could not guarantee that the thing constructed would actually be a correctly formed object of the parent class.
What you did is exactly what the creators intended should be done.
Gerry Giese
Ranch Hand
Joined: Aug 02, 2001
Posts: 247
posted
Dec 18, 2001 11:09:00
0
Ok, that makes sense. I should probably go back and re-read a basic
java
book. Last time I did that was in a class that used Java 1.02 about 5 or so years ago! I've been using Java on and off since then, but only in the past year has it expanded enough to be truly useful for the type of work I do. Thanks again!
I agree. Here's the link:
subject: inheritance and contstuctors problem
Similar Threads
SQL ResultSet count Problem
Hashtable sort by key
Synchronization problem with session?!
String literals
Enumerators and Iterators
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/390636/java/java/inheritance-contstuctors | CC-MAIN-2015-06 | refinedweb | 830 | 64.51 |
Hello, I have been using VisAD for visualization apps and I really like it. For one situation I wanted a RangeSlider that would only allow endpoints from a range of tickmarked values, such as 1. to 100. in steps of 3.0. The most obvious way to do this involved a small change to a private method in the current source for RangeSlider. In the main class I replaced: private float gripToValue(int pos, int width) { return (((maxLimit - minLimit) * ((float) (pos - GRIP_WIDTH))) / (float) (width - (GRIP_WIDTH * 2))) + minLimit; } With: private float gripToValue(int pos, int width) { return adjustValue( (((maxLimit - minLimit) * ((float) (pos - GRIP_WIDTH))) / (float) (width - (GRIP_WIDTH * 2))) + minLimit ); } public float adjustValue(float val) { return val ; } And this allowed me to do what I need in a subclass. But this means that I need to include the original RangeSlider source, and to maintain it if it changes in future versions of VisAD. Is there a better way to create the RangeSlider I want that would not involve future code maintaince? Or would it be possible to have this sort of change incorporated into the standard distribution? Thanks, Paul __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software
visadlist information:
visadlist
visadarchives: | https://www.unidata.ucar.edu/mailing_lists/archives/visad/2003/msg00862.html | CC-MAIN-2019-04 | refinedweb | 204 | 59.84 |
I have a class called Sphere, and within it I have different attributes (actually just one at the time).
Sphere.cpp:
#include "sphere.h" Sphere::Sphere(double arg_r) { radius = arg_r; //Radius is defined in sphere.h as a double }
In my main class, I want to create a new "sphere". (Not sure if this is even right).
Then I want to pass this instance of Sphere to ExampleClass.
Main.cpp:
int main(int argc, char* argv[]) { Sphere sphere = Sphere(1.0); ExampleClass ex = ExampleClass(sphere); return 0; }
ExampleClass.cpp:
#include "exampleclass.h" #include "sphere.h" ExampleClass::ExampleClass(Sphere s) { // Some code that will use Sphere s }
I've tried doing this (or variations close to this) and haven't had any success. I was hoping someone couldn't straighten things out for me. | http://www.dreamincode.net/forums/topic/118925-new-to-c-creating-instances-passing-them/ | CC-MAIN-2017-13 | refinedweb | 133 | 70.19 |
In programming languages, identifiers are used for identification purpose. Or in other words, identifiers are the user-defined name of the program components. In C#, an identifier can be a class name, method name, variable name or a label.
Example:
public class GFG { static public void Main () { int x; } }
Here the total number of identifers present in the above example is 3 and the names of these identifiers are:
- GFG: Name of the class
- Main: Method name
- x: Variable name
Rules for defining identifiers in C#:
There are certain valid rules for defining a valid C# identifier. These rules should be followed, otherwise, we will get a compile-time error.
- The only allowed characters for identifiers are all alphanumeric characters([A-Z], [a-z], [0-9]), ‘_‘ (underscore). For example “[email protected]” is not a valid C# identifier as it contain ‘@’ – special character.
- Identifiers should not start with digits([0-9]). For example “123geeks” is a not a valid in C# identifier.
- Identifiers should not contain white spaces.
- Identifiers does not allowed to use as a keyword unless they include @ as a prefix. For example, @as is a valid identifier, but “as” is not because it is a keyword.
- C# identifers allow Unicode Characters.
- C# identifiers are case-sensitive.
- C# identifers cannot contain more than 512 characters.
- Identifiers does not contain two consecutive underscores in its name because such types of identifiers are used for the implementation.
Example:
Output:
The sum of two number is: 49
Below table shows the identifers and keywrods present in the above example:
This article is attributed to GeeksforGeeks.org
0 0 | https://tutorialspoint.dev/language/c-sharp/c-identifiers | CC-MAIN-2022-05 | refinedweb | 267 | 56.96 |
Created on 2012-11-03 12:42 by scoder, last changed 2020-01-29 00:38 by brett.cannon.
After compiling the stdlib with Cython with the attached script, modules that use circular imports fail to initialise. That includes os and posixpath, as well as shutil and tarfile. Example:
$ ./python -c 'import shutil'
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "tarfile.py", line 44, in init tarfile (tarfile.c:44135)
import shutil
File "shutil.py", line 14, in init shutil (shutil.c:22497)
import tarfile
File "<frozen importlib._bootstrap>", line 1556, in _find_and_load
RuntimeError: maximum recursion depth exceeded
I've tried this with the latest CPython 3.4 hg version, but I'm pretty sure it fails in Py3.3 as well.
I don't mean for this to sound rude, but this seems like a Cython issue and not one for the stdlib. Can you reproduce the problem without using Cython? The new per-module locking mechanism Antoine prevents this from being a problem normally, so it makes me think Cython is at fault here.
Well, it might be a legitimate issue, but due to the setup needed to reproduce, I would hope a Cython developer could do the diagnosis and possibly submit a patch.
Well, it's not like the setup was all that difficult. 1) Install the latest github master of Cython (they provide one-click archives that pip can install for you), 2) change into the CPython stdlib directory and run the script I attached, 3) execute "import os" in Python. You need to install Cython rather than just unpacking it because it uses 2to3 for installation in Py3.
Anyway, I ran gdb on it and it turns out that the exception is correct, there is an infinite recursion taking place. According to the (otherwise not very interesting) stack trace at the point where it raises the RuntimeError, the module init function of the first Cython module (say, "os") calls the builtin "__import__()" to import "posixpath". That triggers the load of that shared library and the execution of its module init function. Fine so far. However, that module init function then executes an import of "os" through "__import__()", which then runs the module init function of the "os" module again. Bug right here. It shouldn't try to reimport a module that it is already importing.
I could reduce the test case down to one line:
# reimport.py
import reimport
Compiling that with Cython gives the C code I attached. Build it, import it, see it fail. However, remember that fixing only this isn't enough, the import cycle might be nested arbitrarily deep.
Since it's quite possible that this has nothing to do with the frozen part of the importlib specifically, I'm removing that bit from the ticket title.
Are you sure this worked before 3.3?
Regardless, it seems you could fix this issue by adding a single line just after the PyModule_Create() call:
__pyx_m = PyModule_Create(&__pyx_moduledef);
#endif
if (PyDict_SetItemString(PyImport_GetModuleDict(),
__Pyx_NAMESTR("reimport"), __pyx_m))
goto __pyx_L1_error;
The fundamental issue is that an extension is inserted into sys.modules
only after its initialization function returns, so importing it recursively won't detect that it already exists.
(by contrast, a Python module is inserted into sys.modules before its code is executed inside the module's global namespace)
A simple test seems to confirm the problem already existed in 3.2.
Note that Py_InitModule4 in Python 2 did add the module object to sys.modules (by calling PyImport_AddModule) before returning, but PyModule_Create in Python 3 doesn't.
(PEP 3121 doesn't seem to mention PyModule_Create at all, strangely; it seems the PEP doesn't follow the implementation)
Hmm, we already do that for packages (i.e. when compiling __init__.py). Looks like this just needs to be done for all modules in Py3. And unless there is a compelling reason for Py_InitModule4() not to do it, I think it should be reverted to its Py2 behaviour.
I have detected a compatibility issue when reverting to the 2.x behaviour: extension modules which lie about their name in their PyModuleDef are broken. There are two such modules in 3.3: _io and _decimal.
Patch attached, anyway.. Only the loader would know the correct package, not the module creation code.
Also see issue 13429.
>.
That's possible (although I would expect a module to know in which package it's supposed to live).
Another solution would have been to pass the module object to the init function, instead of letting the init function create it, but it's a bit too late (or too early :-)) to change the extension module init signature again.
The problem is a) that the module does not necessarily know to which place it eventually gets installed (Cython relies on the distutils Extension not lying to it, for example, which people do from time to time), and b) that the call to Py_InitModule() only receives the plain module name, not the package path. And yes, as mentioned in the other issue, passing a pointer to a context description struct into the module init function would have been the right thing to change for Py3 and still is the right thing to change for Py4.
BTW, I can confirm that registering the module in sys.modules explicitly right after creation works around this issue. Given that Cython needs to know the FQMN at compile time anyway, this works for us. It still leaves the problem open for other extension code.
It sounds like Cython has its fix and CPython knows what should eventually be changed in Python 4 to bring extension module initialization closer to how Python module code is initialized.
Maybe we should add a warning in some documentation somewhere about this and then close the issue?
> Maybe we should add a warning in some documentation somewhere about
> this and then close the issue?
I don't really know where to add it, in the C API docs perhaps,
I was thinking somewhere in since this only comes up when you try to execute an import during extension module initialization that involves a circular import.
Agreed. Since it doesn't really fit into any specific function documentation, I would place it right at the top. Something like this:
"""
The following functions can be used by C code to call into Python's import machinery.
Note that Python 3 does not automatically register an extension module in sys.modules on creation (see module.html#initializing-c-modules). It is only added after running through the whole module init function. This means that a request to import the current module while its init function is still running (either directly or transitively by other modules) will try to reimport the module. If you cannot be sure that this will not happen, you have to register the newly created module yourself as follows, using the fully qualified module name::
PyObject *the_module = PyModule_Create(py_module_def);
if (the_module == NULL) { /* failure ! */ };
PyObject *sys_modules = PyImport_GetModuleDict();
if (sys_modules == NULL) { /* failure ! */ };
if (PyDict_SetItemString(modules, "the.package.and.module", the_module) < 0) { /* failure ! */ };
"""
Maybe it should add another comment that this is a major quirk in the runtime and say "sorry for being stupid here - I hope you can do better". Requiring the user to know the FQMN at build time because the import machinery fails to set it automatically is just embarrissing.
Then, after the first sentence in the module.html#initializing-c-modules section, I'd add this:
"""
Note that, starting with Python 3.0, the module creation functions no longer register the module in sys.modules. The import machinery will only do this after the module init function has run. If you need to run imports as part of your module init function and happen to know the fully qualified module name in your code, it is best to register the module yourself after creating it.
"""
I wonder if the code example shouldn't go on the "module" page.
The fully qualified name requirement is definitely a design flaw where init functions should just be given the module object with everything already set, just like what @importlib.util.module_for_loader does. Hopefully we can come up with a solution through your current discussion on python-dev.
As for the comment, yes at the top of the page makes sense. Whether example code should go somewhere else I don't know.
Is this issue resolved in any way?
Has there been a decision made on how to resolve it?
What's the status here? is trying to come up with a redesign of extension module loading and no one has submitted a patch for the documentation (although Stefan has inlined proposed wording in a comment).
Yes, the resolution of this issue will be to add documentation. Someone should turn Stefan's comment into a patch. | https://bugs.python.org/issue16392 | CC-MAIN-2021-25 | refinedweb | 1,476 | 63.8 |
Python is my favorite programming language. Its adaptability, readability, and coding speed are unique and make python a powerful choice in various projects, from data science projects to scripting and, of course, APIs.
Python is a popular choice for API development, not only because it is one of the most loved programming languages, but also because of its rich ecosystem of libraries and frameworks that serve that goal, libraries with immense popularity such as Django, Flask, and FastAPI.
But which framework should you use to build your APIs with Python? It’s 100% up to you, but there are important considerations to keep in mind. After all, some of these frameworks are different, even from the ideology.
- Django is an all-inclusive framework. It provides tools and modules for handling API requests, serialization, database connections, automatic admin UI generation, and so much more.
- Flask, on the contrary, is a minimalist framework, it provides only the necessary tools, but it extends its functionality with additional libraries and frameworks. The great part is, you decide exactly what you need for your project, nothing more.
- FastAPI is a relatively new framework. It makes use of newer python features such as type-hints, concurrency handling (with async), and it’s super fast.
I work a lot with Flask and FastAPI, and I love both. I love the flexibility and adaptability of these frameworks, and for today's article, we will be focusing on Flask.
Let’s get started! 🚀
Design Your API Endpoints with Proper Names and HTTP Verbs
An adequately designed API is easy and straightforward for developers to understand. By reading the URI and HTTP verb (more on this later), a developer can pretty much have a good understanding of what to expect to happen when calling a particular method.
But how does that work? Let’s start with naming URIs. In REST, we called
Resource to a first-level data representation. Naming these resources consistently throughout your API will turn out to be one of the best decisions for the long term.
Note that I highlighted consistently in the previous sentence, as it’s a key factor. Sure, there are particular ways to name your resources, and we will cover them, but being consistent is more important to the actual convention you choose.
Let’s start getting practical by modeling a simple eCommerce website with customers, orders, and a checkout process.
Our primary resource is
customers, which is a collection of the instance
customer. With this information, we can identify the collection resource by the URI
/customers or a single resource by using the URI
/customers/{customerId}. Subsequently, we can identify sub-resources such as
orders, and we can identify them as
/customers/{customerId}/orders, or a single order resource by
/customers/{customerId}/orders/{orderId}.
Best practices naming resources
- Use nouns in their plural form to represent resources, eg:
- ✅ Users of a system:
/users,
/users/{userId}
- ✅ User’s playlists:
/users/{userId}/playlists,
/users/{userId}/playlists/{playlistId}
- Use hyphens “-” to separate words and improve redeability
- ✅
/users/{userId}/-mobile-devices
- ❌
/users/{userId}/mobileDevices
- ❌
/users/{userId}/mobile_devices
- Use forward slashes “/’ to indicate hierarchy
- ✅
/users/{userId}/mobile-devices
- ❌
/users-mobile-devices/{userId}
- ❌
/users-mobile-devices/?userId={userId}
- Use only lowercase letters in URIs
- ✅
/users/{userId}/mobile-devices
- ❌
/Users/{userId}/Mobile-Devices
Now that we understand how to name resources, we need to think about actions. There are methods in our APIs that are procedural by nature and are not related to a specific resource, e.g., checkout, run, play, etc.
Best practices naming actions
- Use verbs to represent actions, e.g.:
- ✅ Execute a checkout action:
/users/{userId}/cart/checkout
- Same as resources, use hyphens, forward slashes, and lowercase letters.
One crucial point here is to differentiate between CRUD functions and actions, as both are actions. In REST, CRUD operations, such as Create, Read, Update and Delete, are handled through HTTP verbs and not by the URI.
But what are HTTP verbs or HTTP request methods?
HTTP defines a set of request methods to indicate an action to be performed for a resource (sounds familiar?). The list includes several, but we will be focusing on 5:
- GET: should be for data retrieval.
- POST: should be used to create a new resource.
- PUT: should be used to update information about a specific resource.
- DELETE: should be used to delete a particular resource.
- PATCH: should be used to update partial information about a particular resource.
Example for our eCommerce website
- ✅ GET
/users: lists of all users.
/users: creates a new user.
- ✅ PUT
/users/{userId}: updates a user.
- ✅ DELETE
/users/{userId}: deletes a specific user.
- ✅ PATCH
/users/{userId}: partially updates a user.
- ✅ GET
/users/{userId}/orders: lists of all orders for a particular user.
/users/{userId}/cart/checkout: runs the checkout process.
What you shouldn't do:
- ❌
/users/get-all
- ❌
/users/create
- ❌
/users/{userId}/list-orders
In any form of GET, POST, or another verb.
How to Properly Structure Your Application
I’d like to start this section by saying that there’s no one correct way to structure your application depending on application size, modules, requirements, or even personal preferences. This could vary. However, I’d like to introduce you to how my team structures Flask applications, and we used this setup for multiple production projects.
You can follow the explanation of the structure in the article, and you can also find this structure ready to use in the Flask API starter kit on github.
project/ api/ model/ __init__.py welcome.py route/ home.py schema/ __init__.py welcome.py service __init__.py welcome.py test/ route/ __init__.py test_home.py __init.py .gitignore app.py Pipfile Pipfile.lock
Let’s now break it down and explain each module.
All the application magic happens inside the API module (
/api), there, we split the code into 4 main parts:
- The
modelsare the data descriptor of our application, in many cases related to the database model. How each model is defined will heavily depend on the library you use to connect to your database.
- The
routesare the URIs to our application, where we define our resources and actions.
- The
schemasare the definitions for inputs and outputs of our API, what parameters are allowed, what information we will output. They correlate to our resources, but they are not necessarily the same as our models.
- The
servicesare modules that define application logic or interact with other services or the db layer. Routes should be as simple as possible and delegate all logic to the services.
Each endpoint in Flask can be defined on its own or by groups called blueprints. In my case, I like the grouping Blueprints provide, and I use them for each resource. Let’s take a look at what an example of our welcome route (
./api/route/home.py) would look like:
Let’s break all of it into 3 pieces:
home_api = Blueprint('api', __name__)
Here is where we declared our Blueprint, which we can consequently use to declare our endpoints or routes. In this case, our grouping is pretty basic, but we can do much more with grouping, like defining prefixes, resource folders, and more.
For example if we would like to have our
home blueprint always as a nested route of
/home-service, we could do:
home_api = Blueprint('api', __name__, url_prefix='/home-service')
Next we declare one route, but we split it in 2 parts:
@home_api.route('/') @swag_from({ 'responses': { HTTPStatus.OK.value: { 'description': 'Welcome to the Flask Starter Kit', 'schema': WelcomeSchema } } })
We use annotations on top of functions to convert them into endpoints and provide additional information, e.g., documentation information, more on that in the next section.
And finally, our route code, which is just a Python function.
def welcome(): """ 1 liner about the route A more detailed description of the endpoint --- """ result = WelcomeModel() return WelcomeSchema().dump(result), 200
Note that we don’t simply return a string or JSON object directly, but we use our schemas instead. In our example, I’m using flask-marshmallow serialization library for its purposes.
Build Your Documentation from the Code
You build your API, you shipped to production, and developers are eager to consume it, but how would they know what endpoints are available and how to use them? The simple answer is by reading the documentation.
The documentation can be built in 2 ways, you can open up an editor and write it “manually”, or you can use the code to generate your documentation. If you like the idea of automatic documentation, you will love swagger.
Swagger is an open-source specification that allows you to describe each element of your API so that any machine or system can interpret it and interact with it. Thanks to this specification, many tools have been developed to provide rich interfaces to make our documentation dynamic and interactive, but also to provide developers with tools to easily generate these swagger files.
For Flask, there are multiple libraries for automatic Swagger generation, but my favorite is flasgger. Flassger provides annotations and other tools to generate your documentation, and it also provides a pretty web interface where you can see each endpoint, its inputs, and outputs and even run the endpoints directly from the docs.
Here is an image of it in action:
It’s highly configurable and compatible with our serialization library by using an additional library called apispec. It’s all pretty easy to set up, but you can also make use of the Flask starter kit, and you will have it all done for you.
But once you have it up and running, where is the information taken for the docs? From 2 places:
Remember our swag_from function annotation? There we can provide detailed information about the inputs and outputs
@swag_from({ 'responses': { HTTPStatus.OK.value: { 'description': 'Welcome to the Flask Starter Kit', 'schema': WelcomeSchema } } })
We can also use string literals in functions to provide a description for the endpoint, similar to what we did here:
def welcome(): """ 1 liner about the route A more detailed description of the endpoint --- """
There are many more options and customizations; it’s all well documented on their official docs.
Testing
If you are like me, perhaps you hate writing tests, but if you are like me, you know it’s worth it. Testing, when done properly, increases efficiency and quality in the long run. They also reassure developers when making changes, refactoring, or building new features on existing systems.
Building tests shouldn’t be too hard, and it should happen naturally during development. I struggled a lot with it in the past because I’d always first develop the feature, the endpoint, or the function and then write the tests, just to get it done.
I’m not saying that approach is wrong, but there’s a better way. TDD, or test-driven development, it’s a concept idea where you write tests first, and just then you write the actual code we want to test.
How does it work? Let’s suppose we need to write a function that will add 2 numbers and return the result; exciting, right?
With TDD, our approach would be first to write the tests.
def test_answer(): assert sum_two_numbers(3, 5) == 8
Next, we run the tests, and it fails because our function doesn’t even exist yet. So next, we write our function:
def sum_two_numbers(num1, num2): return num1 * num2
Next, we rerun our tests, and they still fail. Our assertion fails, but why? It turns out that I made a simple mistake. As clumsy as I am, I put a * instead of a +; this would have been very hard to notice without our tests, but thanks god, we have them.
We fix our function, and now everything runs perfectly.
def sum_two_numbers(num1, num2): return num1 + num2
In the exercise we did, it sounds kind of silly, but with more complex functions and code mistakes happen, and having tests first will help a lot; I say that from experience.
Conclusion
Best practices can be different for different frameworks, problems to solve, or even people, there’s no one way of doing things right, and that’s something I love about programming. However, having basic principles to rely on when designing and developing APIs can help your team, and other developers consume your API products.
Being consistent in naming, separating concepts in modules or folders in your project, documenting directly from your code, and properly testing are just examples of things that can make your life easier, more productive, and take you to the next level.
I hope you enjoyed reading this article! | https://auth0.com/blog/best-practices-for-flask-api-development/ | CC-MAIN-2022-05 | refinedweb | 2,095 | 62.68 |
- Advertisement
Content count81
Joined
Last visited
Community Reputation50 Neutral
About jb-dev
- RankMember
Personal Information
- Role3D Artist
Game Designer
Programmer
- InterestsArt
Audio
Design
Programming
Social
- MiiMii1205
- GithubMiiMii1205
- SteamMiiMii1205
Recent Profile Visitors
The recent visitors block is disabled and is not being shown to other users.
Unity】.
Vaporwave Roguelite
jb-dev added images to a gallery album in Projects
Unity Weekly Updates #10 - yum ゝ彙ヶ
jb-dev posted a blog entry in Projects Of Some Degree Of InterestLast week I've worked on two things: Foods and Activated Items. I can safely say that my goal was achieved, and even surpassed. I've managed to add three working Activated Items and a whopping 9 foods in total. So let's dive right into it. Focus system crash course Before we dive right into activated items, we first have to know about the focus system. The focus system is like the classes or specializations system in most RPGs. Except that the focus system is actually quicker and is overall much more simpler than traditional RPG class system. (Because it's in a roguelike game and permadeath exists) In essence, each time the player uses those items, then its focus will shift through three poles: Vaporwave (Rogue/Assasins), Future Funk (Marksmen) and Hardvapor (Brawler). Having a certain focus can results in additional bonuses in certain stats, and can even give weapons and other items different type of bonuses and capacities. As of right now, no actual bonuses are implemented. This is because the focus system is primarily linked to the player's equipment... These aren't in the game just yet... Activated items If you played The Binding of Isaac, then you may be familiar with this concept. The idea is to have an item that can have an effect when manually triggered. Activated items work just like this: they are items that the player can activate. Most of the time, these give additional abilities to the player, like becoming temporarily invisible. Activated items can also have relic-like capacities that apply as long as the item is held, and can also have modifiers. Items can also have a focus alignment. Right now, only three of these are functional in the game. The Cellphone Alignment: Vaporwave This is an old piece of junk. It's supposed to represent an old Motorola brick phone. With this phone, the player is able to set up a one-way teleportation trip. First, the player needs to set up an exit point by activating it. This will create a weird sphere of spatial distortion Afterwards, when the player activates the item once more, they will be instantly teleported to it. Useful when you're in a huge level and want to get back to a specific room like a mall after getting more dosh. Here are it's modifiers: -5% ATK -10% HP Survival Gear Alignment: Hardvapor This activated item is supposed to represent a survival backpack. With this item, the player can sacrifice its health for foods. Here are its modifiers: -20% AGL -10% HP This Alignment: None This is this or at least my interpretation of it. In my head, an object always was a big red specular sphere. Maybe it's because I started making games with Game Maker? Perhaps... With This, the player can reroll all items in a 25 meters radius for 10$. Here are the modifiers: +25% LCK -10% HP Foods Foods are like temporary relics. They sometimes have capacities like relics and also have modifiers that are usually out of this world. When the player eats foods then a countdown is initiated. When the countdown is finished, all modifier and capacities given to the player are removed. Right now every food lasts for about 5 seconds. This will be individually tweaked based on things like modifiers and capacities... Here's a list of foods in the game: Pineapple This is a simple pineapple. Nothing special here Here are the modifiers: -10% LCK +25% ATK +50% DEF -10 AGL Banana A normal banana. Here are the modifiers: +75% LCK +68% DEF +50% AGL Lime A normal lime, cut in half. Here are the modifiers: +10% LCK +25% ATK +75% AGL -10% HP Pineaburger A burger made of a slice of pineapple. There's also a lettuce leave thrown in there for good measure. Here are the modifiers: -10% LCK +25% ATK +50 % DEF -10% AGL Double Deluxe A plain waffle topped with whipped cream and glazed with some kind of syrup (claimed to be raspberry, but sure doesn't taste like it) Here are the modifiers: +75% LCK +10% ATK -25% DEF +10% AGL +5% HP Instant Ramen A normal instant ramen bowl. chopstick included. Here are the modifiers: +50% ATK +50% AGL -25% HP Bento box A somehow 80s bento box, with crazy shapes, lines and colours. Comes with chopsticks. Here are the modifiers: +25% LCK +10% DEF -10% AGL +75% HP Toast Sandwich A somehow plain looking sandwich. It appears to have a heavily buttered toast in the middle. This is one of the food that can give you a capacity. When eaten, it gives the capacity to do a double jump. Here are the modifiers: -10% LCK +25% DEF -50% AGL -5% HP Minor updates There are now proper debug tools, such as spawning folders and so, making the testing phase so much quicker Resolved some bugs with mall inventory not being properly chosen Finally added relic/foods/equipment/weapon spawning to folders items. This means that the player can finally get good loot from folders. Fixed an infrequent bug that gives wrong orientation to some rooms (i.e. some breakable wall used to spawn perpendicular to the rooms) Added a bunch of things to add effects like 2d drop shadows and outline rendering Next week Next week I planned to add statuses to the game. Statuses like poisoned of stunned. There's already a list of statues that was previously prepared. Now it's just a matter of implementing those. Otherwise, if I have the time I'm probably going to continue the implementations of items/capacities... I also realized that while testing things out I just forget I'm testing and I just play the game (even though there's only one unfinishable level) I genuinely had fun... I wish this feeling will get bigger as this is developed.
Unity Weekly Updates #9 - Relic Mania
jb-dev posted a blog entry in Projects Of Some Degree Of InterestIn my previous update, I've said that the next step would be to integrate relics in the game. I'm proud to say that I've managed to implements some of the planned relics. What are Relics? If you played The Binding of Isaac, you may recall it's Passive Collectibles. Relics are the equivalent in this game. In other words, Relics are run-scoped upgrade the player either find or (if they're lucky) buys in malls. These give stats percentage bonus (i.e. +25% bonus in attack) and also give the player special capacities. What are Capacities? Capacities are passive (i.e. not explicit, or don't need special inputs) abilities the player gain. For example, one capacity could be the capacity to shoot laser beams at each attack. There's a science to it, though. They need considerable balance tweaks here and there just to make sure the game won't break with these capacities. Some capacities are linked to relics, and others not. For example, a capacity can be linked to a specific Item or even Foods. Right now, there are no items or Food in the game, so we'll talk about those in due time... Stats crash course Before we continue with the relics, we first need to understand stats. Stats are exactly what you think they are: just like in most RPG, they quantify the skills of a given entity. In the game, there are 5 base stats : Chance (or Luck if you're fancy): This stats dictates the probability of a player to have good things happen to them (e.x. good loots spawns after an enemy is killed or a lot of special rooms and tunnels are spawned). It also dictates your chance of doing a critical hit (when so, the total damage output are 50% stronger) Attack: it's self-explanatory. This simply gives how much damage is given at each hit Defence: Also self-explanatory. This simply says how much damage is subtracted from an attack Agility: This stats dictates how fast your character goes. there might be more in the future, but for now, it only affects this Vitality (or Health if you're fancy): This stat simply represents your maximal health. These make CADAV. I don't know if it's clever enough, but it's catchy. (Not as good as SPECIAL, but good enough) For each stat, there is two different type of bonus/malus. These are a unitary bonus (or simply bonuses) and a percentage bonus (or modifiers). Bonuses usually come with pieces of equipment (things like armour and/or weapons), while modifiers are usually applied with capacities as a counterweight. Relics List Here's a small list of relics that are fully functional as of today: Laser Gem The laser gem is a relic resembling an abstract transparent cube with an opaque core. When the player picks up that relic, it gives them the ability to fire penetrating laser beams that deal damage to enemies when the player attacks. When the laser collides with anything but entities (like enemies) it will be reflected. This can be a quite powerful tool to quickly dispatch large amounts of enemies. The beam itself last for about 10 seconds, and only 3 beams can be fired at a time. Here are the modifiers: -10% of Attack +5% of Luck Modern Computing This relic is also abstract, but it's nevertheless more meaningful than the previous relic. Both its name and its model references something really vaporwave. But I'll let you figure it out. When the player grabs this relic, a combo system is activated: for every enemy killed, drops that cames from defeated enemies will linearly increase in number. Of course, being a combo system, if the player is hit then the combo is reset. Here are the modifiers: -5% of Luck -4% of Attack Credit Card The credit card is a credit card. (I didn't know what you expected) With this cool relic, the player can actually purchase anything they want anywhere even if they lack the money for it. Buying an item without the needed money creates a debt in the player's funds. After each 10$ of debt, a random amount of negative modifiers are applied to the player's stats. When the player pays off their debts then these nerfs are progressively removed. Because of this special capacity, no base modifiers are applied when this relic is grabbed. DOUBLE-VISION This relic is rather abstract. It's actually a pair of eyes. When the player grabs this relic, every loot that are consumables (i.e bombs, keys or money) are doubled. Here are the modifiers: -5% of Attack -10% of Luck +5% of Agility Extension Cord This relic is simply a North American electric extension cord. There are two capacities attached to this relic. The first one simply makes the range of your attacks bigger. Its just actually the game resizing your weapons... Nothing special here. The second one is more a nerf than anything else: It slows down your attack speed by half. Here are the modifiers: -25% of Attack -25% of Agility Boxed Copy This relic is a Software box. It's supposed to mimic the Windows 9x boxes. With this relic, on the first successful hit by the player to an enemy, the latter has a chance to get "Boxed". When being "boxed", enemies are transformed into a similar box like the relic itself. However, that box is able to be opened by the player. It then spawns a random amount of consumables. It essentially one hit enemies if your lucky and gives you loot too. This only works on the first hit: subsequential hits won't work. Here are the modifiers: -25% of Attack Atk-booster 2000 This relic is a computer chip, presumably a CPU. It simply increases your attack speed by half. Here are the modifiers: -25% of Attack +10% of Agility Watch Out! This relic is a simple watch. With this one, you gain the ability to backstab other enemies. (not unlike the TF2 backstab) This means that if you hit their back they get one hit. In essence, this works by using the same algorithm that my vision field Here are the modifiers: -40% of Attack -25% of Health +5 of Agility Minor Updates Items that are in malls, along with relics and pieces of equipment, now rests on pedestals. These get removed when the item is picked up or otherwise get removed There's now a key collectible that can spawn with any type of loot. Picking these up simply increments the player's total amount of keys The Big Mall (the generic one) now has a chance to spawn a buyable relic in its inventory Fixed many bugs with a whole lot of things Thrown items now properly trigger AIs: they will look at the player that has thrown said projectiles rather than the projectile itself What's next? This week I'm planning to add more capacities and maybe add either Foods or Items in the game. Same goal as before: at least one Food or Item. Just to be clear: Items are like The Binding Of Isaac's Activated Collectibles except that they also change the player's stat and may also add passive capacities while the item is being held. As for food, think of relics, but temporary (a bit like Minecraft's potions). Here comes another big week I guess...
Unity Weekly Update #8 - Locked down
jb-dev posted a blog entry in Projects Of Some Degree Of InterestI've decided to change the frequency of these updates: most of the times, I just do some minor updates and graphical tweaks here and there. Therefore, if I do these updates weekly, then I'll have a lot more content to write about. So, yeah... Last week, I've been working on adding many different types of rooms in the level. You may or may not know that I use BPS trees to generate a level, and previously, only 5 types of rooms spawned in a level: starting rooms, ending rooms, normal rooms, tunnel rooms and Malls. It was very static and not flexible, so I've changed it to make it more dynamic. Malls Variations First, I've added two different variations for Malls: Blood Malls and Clothes Malls. These were originally planned and already built. Big Malls These are your typical type of Malls. You can find everything here. This is where, for example, you'll find hearts, keys and/or bombs. They were already in the game, but now they're more specialized (or generalized in this case) Blood Malls The Blood Malls specialized in bloody activities. (meaning that you'll mostly find a selection of weapons here) Clothes Malls The Clothes Malls are specialized in clothes, which in our case are actually pieces of equipment the player can have New Rooms Aside from these new type of malls, I've also added 3 new types of rooms. These rooms, however, are guarded by a locked door: the player must use a key to enter. In order to unlock a locked door, the player just needs to touch it. If the player has enough keys, then a key is used and the locked door disappears. There's also an event that triggers that can do things when the player unlocks the door (like revealing hidden models and what not) The Gym The gym is a room resembling some of these outside gyms you can see in some places. The player can use up to tree gym equipment to get a permanent stats bonus to a randomly selected stat. The prices of usages of these gym equipment doubles after each use. (i.e. if using one piece is 10$, then after buying it the others will cost 20$ and so on) I've planned that NPC would use non-interactive gym workstations for decoration, but it's not really important as of right now... The Bank The bank is not fully functional at the moment, but it still spawns. The idea is to give the player a way to store money persistently throughout runs. The player can then withdraw money (with a certain transaction fee) from that bank. That means that you can effectively get previously deposited money back when you'll need it the most. The Landfill The landfill gives you the opportunity to gain back previously thrown away pieces of equipment. Basically, the game stores the last three thrown away pieces of equipment. When the rooms spawn, it simply displays you those pieces of equipment. you can then pick them up for free. This, however, comes with a caveat: pieces of equipment that will be switched from a previously thrown away pieces of equipment won't reappear in another landfill. Also, once the landfill despawns, the items in that landfill will be discarded. (Think of it as a last chance opportunity) There aren't any props at the moment, but it's fully functional. Minor Tweaks Aside from that, there are also some minor tweaks: Bombs now damage the player if the latter is within its blast radius; Player jumps are now more precise: letting go of the jump button early makes a smaller jump than if it was held down longer; Ground detection (that was previously done with raycasting) now uses Unity's CharacterController.isGrounded property; When the player is hurt, a knockback is applied to him; The strength of said knockback is actually the total amount of damage the player took. Coins and money items now emit particles to help the player localize those important items; They're now keys (left) and bombs (right) counters in the HUD; The key one still needs a specific icon, but it's fully functional; There were many shader optimizations and adjustments: Many shaders were merged together and are now sharing most code; I've also changed the shaders so that we can use GPU instancing for most props, I also now use MaterialPropertyBlock for things like wetness; Also, now the palette texture and its palette index are now global variables, this effectively means that I only need to set these values once and everything else follows; A small "Sales" sign is placed in front of most types of malls. This sign has a random orientation and position each time it's spawned. ; Props that obstruct a passage are removed from the room; This way no prop can obstruct the room so that the player cannot exit it. Some rooms now spawn ferns instead of palm trees; Lianas also have different configurations based on which prop spawns. Next week Over the next week, I've planned to integrate the first relic. Relics are items that give the player capacities and stats boosts. It's common to have something similar in most roguelite and roguelike games. That type of thing needs to have a good abstraction in order to work: there are many different types of capacities that affect the player in radically different ways. There's a lot of work ahead. But I'm confident it'll be easy. Just need to get in the groove.:
Daily Update #6 - Dynamically colored decals
jb-dev commented on jb-dev's blog entry in Projects Of Some Degree Of InterestAfter thinking about it, I've could have gone with deferred decals, but I thought i didn't need that right now: most of my geometries are flat at the moment......
Algorithm The power of the vector cross product, or how to make a realistic vision field
jb-dev posted a blog entry in Projects Of Some Degree Of InterestIn the previous iteration of our game, we decided to use an actual cone as a way to make an AI "see". This implementation was hazardous, and it quickly became one of the hardest things to implement. We eventually were able to code it all, but the results were really static and not really realistic. Because of the reboot, I took the time to actually identify what constraint one's vision has. The visual field First of all, a cone isn't really the best in therm of collision checking. It required a special collider and could have potentially been a bottleneck in the future when multiple AI would roam the level. In actuality, the visual field can be represented as a 3D piece of a sphere (or more like a sector of a sphere). So we're gonna need to use a sphere in the new version. It's cleaner and more efficient that way. Here's how I've done it: foreach (Collider otherCollider in Physics.OverlapSphere(m_head.transform.position, m_visionDistance / 2, ~LayerMask.GetMask("Entity", "Ignore Raycast"), QueryTriggerInteraction.Ignore)) { // Do your things here } Pretty simple, really... Afterwards (not unlike our previous endeavour), we can just do a simple ray cast to see if the AI's vision is obstructed: // Do a raycast RaycastHit hit; if (Physics.Raycast(m_head.position, (otherPosition - m_head.position).normalized, out hit, m_visionDistance, ~LayerMask.GetMask("Entity", "Ignore Raycast"), QueryTriggerInteraction.Ignore) && hit.collider == otherCollider) { // We can see the other without any obstacles } But with that came another problem: if we use a sphere as a visual field, then the AI can surely see behind his back. Enters the cross product. Vectorial cross product The cross product is a vectorial operation that is quite useful. Here's the actual operation that takes place: \(\mathbf{c} = \mathbf{a} \times \mathbf{b} = ( \mathbf{a}_{y}\mathbf{b}_{z} -\mathbf{a}_{z}\mathbf{b}_{y}, \mathbf{a}_{z}\mathbf{b}_{x} -\mathbf{a}_{x}\mathbf{b}_{z}, \mathbf{a}_{x}\mathbf{b}_{y} -\mathbf{a}_{y}\mathbf{b}_{x} )\) This actually makes a third vector. This third vector is said to be "orthogonal" to the two others. This is a visual representation of that vector: As you can see, this is pretty cool. It looks like the translation gizmo of many 3D editors. But this operation is more useful than creating 3D gizmos. It can actually help us in our objective. Interesting Properties One of the most interesting properties of the cross product is actually its magnitude. Depending on the angle between our two a and b vectors, the magnitude of the resulting vector changes. Here's a nice visualization of it: As you can see, this property can be useful for many things... Including determining the position of a third vector compared to two other vectors. But, however, there's a catch: the order of our a and b vector matters. We need to make sure that we don't make a mistake, as this can easily induce many bugs in our code. The funnel algorithm In one of my articles, I've actually explained how pathfinding kinda works. I've said that the navigational mesh algorithm is actually an amalgamation of different algorithms. One of these algorithms is the Funnel algorithm, with which we actually do the string pulling. When the Funnel algorithm is launched, we basically do a variation of the cross product operation in order to find if a certain point lay inside a given triangle described by a left and right apexes. This is particularly useful, as we can actually apply a nice string pulling on the identified path. Here's the actual code: public static float FunnelCross2D(Vector3 tip, Vector3 vertexA, Vector3 vertexB) { return (vertexB.x - tip.x) * (vertexA.z - tip.z) - (vertexA.x - tip.x) * (vertexB.z - tip.z); } With this function, we get a float. The float in question (or more particularly its sign) can indicate whether the tip is to the left or to the right of the line described by vertexA and vertexB. (As long as the order of those vectors are counterclockwise, otherwise, the sign is inverted) Application Now, with that FunelCross2D function, we can actually attack our problem head-on. With the function, we can essentially tell whether or not a given point is behind or in front of an AI. Here's how I've managed to do it: if ( FunnelCross2D((otherTransform.position - m_head.position).normalized, m_head.right, -m_head.right) > 0 ) { // otherTransform is in front of us } Because this is Unity, we have access to directional vectors for each Transform objects. This is useful because we can then plug these vectors into our FunnelCross2D function and voilà: we now have a way to tell if another entity is behind or in front of our AI. But wait, there's more! Limit the visual angle Most people are aware that our visual field has a limited viewing angle. It happens that, for humans, the viewing angle is about 114°. The problem is that, right now, our AI viewing angle is actually 180°. Not really realistic if you ask me. Thankfully, we have our trusty FunnelCross2D function to help with that. Let's take another look at the nice cross product animation from before: If you noticed, the magnitude is actually cyclic in its property: when the angle between a and b is 90°, then the magnitude of the resulting vector of the cross product is literally 1. The closet the angle gets to 180° or 0°, the closest our magnitude get to 0. This means that for a given magnitude (except for 1), there are actually 2 possible a and b vector configurations. So, we can then try to find the actual magnitude of the cross given a certain angle. Afterwards, we can store the result in memory. m_visionCrossLimit = FunnelCross2D(new Vector3(Mathf.Cos((Mathf.PI / 2) - (m_visionAngle / 2)), 0, Mathf.Sin((Mathf.PI / 2) - (m_visionAngle / 2))).normalized, m_head.right, -m_head.right); Now we can just go back to our if and change some things: if ( FunnelCross2D((otherTransform.position - m_head.position).normalized, m_head.right, -m_head.right) > m_visionCrossLimit ) { // otherTransform is in our visual field } Then we did it! the AI only reacts to enemies in their visual field. Conclusion In conclusion, you can see how I've managed to simulate a 3D visual field using the trustworthy cross product. But the fun doesn't end there! We can apply this to many different situations. For example, I've implemented the same thing but in order to limit neck rotations. it's just like previously, but with another variable and some other fancy codes and what not... The cross product is indeed a valuable tool in the game developer's toolset. No doubt about it.
objects not moving as directed until they fall and hit something
jb-dev replied to ethancodes's topic in General and Gameplay Programming@ethancodes does the original ball get its velocity changed? If not, maybe you could try debugging it with breakpoints. If you don't know how, Unity has a tutorial on this matter. For example, you could just put breakpoints before and after the velocity change and see if your balls' velocity changes at all.
Unity Daily Update #3 - AESTHETIC++
jb-dev posted a blog entry in Projects Of Some Degree Of InterestToday was kind of a slow day: I had many things to do, so development was kind of light... Nevertheless, I've still managed to do something... I've added a way to highlight items through emission (not unlike how we did it previously) and make enemies blink when they get hurt. It wasn't really hard: because this is Unity, the surface shader got us covered. It was just one simple line of code. #ifdef IS_EMISSIVE o.Emission = lerp(fixed3(0, 0, 0), _EmissionColor.rgb, _EmissionRatio); #endif
objects not moving as directed until they fall and hit something
jb-dev replied to ethancodes's topic in General and Gameplay ProgrammingHave you tried with a ForceMode2D parameter too? (Like, right after the force) If so, then maybe there's somewhere else during the frame that just removes your previously set velocity... I do kind of the same thing (except in 3D). I instantiate rigidbodies and add a force to them...
- Advertisement | https://www.gamedev.net/profile/257799-jb-dev/ | CC-MAIN-2018-39 | refinedweb | 4,763 | 62.68 |
Distilled • LeetCode • Binary Search
- Pattern: Binary Search
- [33/Medium] Search in Rotated Sorted Array
- [34/Medium] Find First and Last Position of Element in Sorted Array
- [162/Medium] Find Peak Element
- [278/Easy] First Bad Version
- [362/Medium] Design Hit Counter
- [410/Hard] Split Array Largest Sum
- [528/Medium] Random Pick with Weight
- [774/Hard] Minimize Max Distance to Gas Station
- [825/Medium] Friends Of Appropriate Ages
- [875/Medium] Koko Eating Bananas
- [1011/Medium] Capacity To Ship Packages Within D Days
- [1060/Medium] Missing Element in Sorted Array
- [1231/Hard] Divide Chocolate
- [1283/Medium] Find the Smallest Divisor Given a Threshold
- [1482/Medium] Minimum Number of Days to Make \(m\) Bouquets
- [1539/Easy] Kth Missing Positive Number
- [1891/Medium] Cutting Ribbons
- Further Reading
Pattern: Binary Search
- This section introduces:
- First Bad Version
- Search in Rotated Sorted Array
- Find First and Last Position of Element in Sorted Array
- Median of Two Sorted Arrays
- Another popular case to apply is when you are asked to find the maximum of the smallest value or the minimum of the largest value. Let’s take Split Array Largest Sum as an example to illustrate how to deal with this kind of problem.
-is still qualified.
- The following image shows the steps to apply binary search:
- So the pseudocode is:
while l < r: mid = l + (r-l)//2 if count(mid) > m: l = mid + 1 else: r = mid return l
- Picking
mid:
- When picking the
mid
land
r. When we select the former one using
l+(r-l)/2, we want to make sure to avoid
l = midbecause that might lead to infinite loop. For example when there are two elements
[0,1]and
mid=0, then
lbecomes mid and the iteration goes again and again.
- Similarly, when we select the latter one using
r-(r-l)/2, we want to avoid
r=mid.
Picking
land
r:
- Depends on the context!
- Lower bound
- For example, when the question asks for the lower bound, if
midworks, then
rshould be mid not
mid-1because
midmight be the answer! And when
middoes not work,
lshould be
mid+1because we are sure the
midis not the answer and everything that falls one
mid‘s left won’t work either.
- Upper bound
- Similarly, we can assign values to
land
ras below.
- Overall, the way we select
midand assign values to
land
ris determined by which we are looking for: lower bound vs. upper bound.
- How to choose
mid,
l, and
r:
[33/Medium] if it is in
nums, or -1 if it is not in
nums.
You must write an algorithm with
O(log n)runtime complexity.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4
- Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1
- Example 3:
Input: nums = [1], target = 0 Output: -1
- Constraints:
1 <= nums.length <= 5000
-104 <= nums[i] <= 104
All values of nums are unique.
nums is an ascending array that is possibly rotated.
-104 <= target <= 104
- See problem on LeetCode.
Solution: Binary Search
- Background:
- We have an ascending array, which is rotated at some pivot. Let’s call the rotation the inflection point (
IP).
- One characteristic the inflection point holds is:
arr[IP] > arr[IP + 1]and
arr[IP] > arr[IP - 1].
- If we rotated an array
[0, 1, 2, 3, 4, 7, 8, 9]to
[7, 8, 9, 0, 1, 2, 3, 4], the inflection point (where the numbers go from monotonically increasing to decreasing or vice-versa),
IPnumber 9 (in terms of the pivot , this would be index
5).
- One thing we can see is that values until the
IPare ascending. And values from
IP + 1until end are also ascending (hint: binary search).
- Also the values from
[0, IP]are always bigger than
[IP + 1, n].
- Intuition:
- We can perform a Binary Search.
- If
A[mid]is bigger than
A[left]we know the inflection point will be to the right of us, meaning values from
a[left] ... a[mid]are ascending.
- So if
targetis between that range we just cut our search space to the left. Otherwise go right.
- The other condition is that
A[mid]is not bigger than
A[left]meaning
a[mid] ... a[right]is ascending.
- In the same manner we can check if
targetis in that range and cut the search space correspondingly.
class Solution: def search(self, nums: List[int], target: int) -> int: if not nums: return -1 low, high = 0, len(nums) - 1 while low <= high: mid = (low + high) // 2 if target == nums[mid]: return mid # left portion is sorted, i.e., left is strictly increasing. # inflection point to the right of mid. if nums[low] <= nums[mid]: if nums[low] <= target <= nums[mid]: high = mid - 1 else: low = mid + 1 # left portion is unsorted, i.e., right is strictly increasing. # inflection point to the left of mid. else: if nums[mid] <= target <= nums[high]: low = mid + 1 else: high = mid - 1 return -1
Complexity
- Time: \(O(\log{n})\) where \(n\) is \(len(nums)\)
- Space: \(O(1)\)
[34/Medium] Find First and Last Position of Element in Sorted Array
Given an array of integers
numssorteds is a non-decreasing array.
-109 <= target <= 109
- See problem on LeetCode.
Solution: Binary Search
- Explanation:
search():
find the lowest index of target num in nums if there is target num in nums lo = lowest index of target hi = lowest index of target if there is no target num in nums if there is higher num than target in nums lo = lowest index of the first higher num than target in nums hi = lowest index of the first higher num than target in nums if there is no higher num than target in nums lo = len(nums) hi = len(nums)
- after
lo = search(target), hi = search(target+1)-1:
if there is more than one target num lo = lowest index of target hi = (lowest index of the first higher num than target)-1 (highest index of target) then, lo < high elif there is only one target num lo == high else if there is only higher number than target in nums lo = lowest index of the first higher num than target (at least target+1 or higher) hi = lowest index of the (target+1) - 1 then, lo > high if there is only lower number than target in nums lo = len(nums) hi = len(nums)-1 then, lo > high
def searchRange(self, nums, target): def binarySearchLeft(A, x): left, right = 0, len(A) - 1 while left <= right: mid = (left + right) / 2 if x > A[mid]: left = mid + 1 else: right = mid - 1 return left def binarySearchRight(A, x): left, right = 0, len(A) - 1 while left <= right: mid = (left + right) / 2 if x >= A[mid]: left = mid + 1 else: right = mid - 1 return right left, right = binarySearchLeft(nums, target), binarySearchRight(nums, target) return (left, right) if left <= right else [-1, -1]
- Same approach; compressed version:
class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: def search(x): lo, hi = 0, len(nums) while lo < hi: mid = (lo + hi) // 2 if nums[mid] < x: lo = mid+1 else: hi = mid return lo lo = search(target) hi = search(target + 1)-1 return [lo, hi] if lo <= hi else [-1, -1]
Complexity
- Time: \(O(\log{n})\)
- Space: \(O(1)\)
[162/Medium] Find Peak Element
-2^31 <= nums[i] <= 2^31 - 1
nums[i] != nums[i + 1] for all valid i.
- See problem on LeetCode.
Solution: Binary search
class Solution: def findPeakElement(self, nums: List[int]) -> int: left = 0 right = len(nums)-1 # handle condition 3 while left < right-1: mid = (left+right) // 2 if nums[mid] > nums[mid+1] and nums[mid] > nums[mid-1]: return mid if nums[mid] < nums[mid+1]: left = mid+1 else: right = mid-1 # handle condition 1 and 2 return left if nums[left] >= nums[right] else right
Complexity
- Time: \(O(\log{n})\)
- Space: \(O(1)\)
Solution: One-liner
class Solution: # @param nums, an integer[] # @return an integer def findPeakElement(self, nums): return nums.index(max(nums))
Complexity
- Time: \(O(n)\)
- Space: \(O(1)\)
[278/Easy] First Bad Version
Problem
-versions
[1, 2, ..., n]and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool
isBadVersion(version)which
Solution: Binary search
# The isBadVersion API is already defined for you. # def isBadVersion(version: int) -> bool: class Solution: def firstBadVersion(self, n: int) -> int: """ :type n: int :rtype: int """ r = n-1 l = 0 while l <= r: mid = l + (r-l)//2 # or (l + r)//2 if not isBadVersion(mid): l = mid+1 else: r = mid-1 # returning left here because we need the first bad version return l
Complexity
- Time: \(O(\log{n})\)
- Space: \(O(1)\)
Solution: Bisect
# The isBadVersion API is already defined for you. # def isBadVersion(version: int) -> bool: import bisect class Solution(dict): def firstBadVersion(self, n: int) -> int: return bisect.bisect_left(self, True, 1, n) def __getitem__(self, key): return isBadVersion(key)
Complexity
- Time: \(O(\log{n})\)
- Space: \(O(1)\)
[362/Medium] Design Hit Counter
Problem.
- Implement the
HitCounterclass:
HitCounter()Initializes the object of the hit counter system.
void hit(int timestamp)Records a hit that happened at timestamp (in seconds). Several hits may happen at the same timestamp.
int getHits(int timestamp)Returns the number of hits in the past 5 minutes from timestamp (i.e., the past 300 seconds).
- Example 1:
Input ["HitCounter", "hit", "hit", "hit", "getHits", "hit", "getHits", "getHits"] [[], [1], [2], [3], [4], [300], [300], [301]]
- Output
[null, null, null, null, 3, null, 4, 3] Explanation HitCounter hitCounter = new HitCounter(); hitCounter.hit(1); // hit at timestamp 1. hitCounter.hit(2); // hit at timestamp 2. hitCounter.hit(3); // hit at timestamp 3. hitCounter.getHits(4); // get hits at timestamp 4, return 3. hitCounter.hit(300); // hit at timestamp 300. hitCounter.getHits(300); // get hits at timestamp 300, return 4. hitCounter.getHits(301); // get hits at timestamp 301, return 3.
- Constraints:
1 <= timestamp <= 2 * 109
All the calls are being made to the system in chronological order (i.e., timestamp is monotonically increasing).
At most 300 calls will be made to hit and getHits.
- See problem on LeetCode.
Solution: Deque
class HitCounter(object): def __init__(self): """ Initialize your data structure here. """ from collections import deque self.num_of_hits = 0 self.time_hits = deque() def hit(self, timestamp): """ Record a hit. @param timestamp - The current timestamp (in seconds granularity). :type timestamp: int :rtype: void """ if not self.time_hits or self.time_hits[-1][0] != timestamp: self.time_hits.append([timestamp, 1]) else: self.time_hits[-1][1] += 1 self.num_of_hits += 1 def getHits(self, timestamp): """ Return the number of hits in the past 5 minutes. @param timestamp - The current timestamp (in seconds granularity). :type timestamp: int :rtype: int """ while self.time_hits and self.time_hits[0][0] <= timestamp - 300: self.num_of_hits -= self.time_hits.popleft()[1] return self.num_of_hits
Complexity
- Time: \(O(\log{n})\)
- Space: \(O(1)\)
Solution: Binary Search
- Two step process:
- Add each timestamp in a list for
hit().
- For each timestamp in getHits(), find the index that (
timestamp-300) would be inserted at (rightmost index that is) using binary search. The difference of current length of the timestamps list and that index would be the answer.
- Why rightmost index?
- See the following example:
- If
values(timestamps) = [1,301], and we look to do
getHits(301), we would try and find where
(301-300)=1should be inserted. If we’re looking for the left most value, the index would be 0 and the ans would
len(values)-idx = 2-0 = 2, which is wrong for the questions’ constraints.
- The timestamp 5 minutes is a hard bounds, which means if we go back 300 seconds for time 301, the 1s is actually the 301st second, which puts it outside our bound.
- So, we would actually find the rightmost index where this value should be inserted at as that would be a value, that is within our bounds.
- So going through the example above, when we find the rightmost
idxto insert 1 at in
[1,301], we would get 1, and the answer would
len(values)-idx = 2-1 = 1.
- Intuition:
- Store the incoming timestamps in an array.
- Timestamps are monotonically increasing, so the resulting array will be sorted in increasing order. Once you’d like to get the number of hits within the last 300 seconds, find the cutoff index at timestamp - 300 in the sorted array.
- The timestamps to the right of this cutoff occurred within the 300 seconds.
- The length of the array minus the cutoff index gives you the count of these timestamps within 300 seconds. Done!
- Note the benefit of keeping all recorded hits:
- Other solutions argue for a queue where all the timestamps with difference greater than or equal to 300 are removed from the queue. This approach is not favorable in a real-world context.
- From a design perspective, it os better to present an extendable solution that is able to run more summary statistics (e.g hits in last 15 minutes, average hits, etc.). Once you’ve removed the hits from your queue, these will be impossible to calculate (except you’ve stored them somewhere beyond the machines memory).
- Using inbuilt bisect library:
(Using inbuilt bisect library) 32ms: class HitCounter: def __init__(self): self.values = [] def hit(self, timestamp: int) -> None: self.values.append(timestamp) def getHits(self, timestamp: int) -> int: right = len(self.values) left = bisect.bisect_right(self.values, timestamp-300) return right-left
- Implementing Binary Search for Rightmost Value:
class HitCounter: def __init__(self): self.values = [] def hit(self, timestamp: int) -> None: self.values.append(timestamp) def __findIdx(self, target): l = 0 r = len(self.values) while l < r: m = (l + r) // 2 if self.values[m] > target: r = m else: l = m + 1 return l def getHits(self, timestamp: int) -> int: right = len(self.values) left = self.__findIdx(timestamp- 300) return right-left
Complexity
- Let
nbe the number of times hit(). Alternatively, its the number of timestamps inserted in the list.
- Time:
hit()->
O(1).
getHits()->
O(logn).
- Space: \(O(n)\)
[410/Hard] Split Array Largest Sum
Problem
Given an array
numswhich consists of non-negative integers and an integer
m, you can split the array into
mnon-empty continuous subarrays.
Write an algorithm to minimize the largest sum among these
msubarrays.
Example 1:.
- Example 2:
Input: nums = [1,2,3,4,5], m = 2 Output: 9
- Example 3:
Input: nums = [1,4,4], m = 3 Output: 4
- Constraints:
1 <= nums.length <= 1000
0 <= nums[i] <= 106
1 <= m <= min(50, nums.length)
- See problem on LeetCode.
Solution: Binary Search
class Solution: def splitArray(self, nums: List[int], m: int) -> int: """ :type nums: List[int] :type m: int :rtype: int """ def split(nums, largest_sum): """ Given the largest_sum returns the number of pieces. """ pieces = 1 tmp_sum = 0 for num in nums: if tmp_sum + num > largest_sum: tmp_sum = num pieces += 1 else: tmp_sum += num return pieces # pieces is number of pieces for a given largest_sum # For pieces = len(nums), the largest_sum is max(nums) # for pieces = 1, the largest_sum is sum(nums) # We are looking for p=m, as we go from p=1 to p=len(nums) the # largest sum goes from max(nums) to sum(nums) (which is our search space) low = max(nums) # m = len(nums) high = sum(nums) # m = 1 # if pieces > m high is small while low < high: mid = (low + high) // 2 # or mid = low + (high - low) // 2 pieces = split(nums, mid) if pieces > m: # the largest_sum is small, we have too many pieces and we can merge some of them # we have more pieces than m, which means largest sum needs to increase so set low to mid+1 low = mid + 1 else: # mid works so cap high to mid high = mid return low
Complexity
- Time: \(O(n\log{m})\) where \(m = sum(nums)\) and \(nums\) is the input array containing \(n\) items.
- Space \(O(1)\)
[528/Medium] Random Pick with Weight
Problem
You are given a 0-indexed array of positive integers
wwhere
w[i]describes the weight of the
i^thindex.
You need to implement the function
pickIndex(), which randomly picks an index in the range
[0, w.length - 1](inclusive) and returns it. The probability of picking an index
iis
w[i] / sum(w).
- For example, if w =
[1, 3], the probability of picking index
0is
1 / (1 + 3) = 0.25(i.e.,
25%), and the probability of picking index 1 is
3 / (1 + 3) = 0.75(i.e.,
75%).
Example 1:
Input ["Solution","pickIndex"] [[[1]],[]] Output [null,0] Explanation Solution solution = new Solution([1]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
- Example 2:
Input ["Solution","pickIndex","pickIndex","pickIndex","pickIndex","pickIndex"] [[[1,3]],[],[],[],[],[]] Output [null,1,1,1,1,0] Explanation Solution solution = new Solution([1, 3]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: [null,1,1,1,1,0] [null,1,1,1,1,1] [null,1,1,1,0,0] [null,1,1,1,0,1] [null,1,0,1,0,0] ...... and so on.
- Constraints:
1 <= w.length <= 104
1 <= w[i] <= 105
pickIndex will be called at most 104 times.
- See problem on LeetCode.
Solution: Normalize weights, sample N uniformly and pick based on testing if N <= Weight
- Normalize the weights in the initial w list to ratios
- i.e.,
[1, 3, 3, 1] --> [1 / 8, 3 / 8, 3 / 8, 1 / 8], for a general list […i…] —> [… i / sum(list) …]
- This give us the frequency of each index
- Take these new weights and put them on a number line from 0 –> 1 by adding to each element all of the previous elements
- i.e. [1/8, 3/8, 3/8, 1/8] –> [1/8,4/8,7/8,1], for a general list […i…] —> [… i + sum(all previous)…]
- Note this will always mean list[-1] = 1
- This gives us a number line to test a random variable on
- Generate a random number between 0, 1
- Find the section of the number line the random number falls into and return its index
- The while loop effectively gives us each index with its correct probability
Pseudocode: 1. Initialize class. 2. Get a list of all unique values. 3. Normalize weights. 4. Put weights on the number line. 5. If a uniform variable falls in the range of a value that value is returned.
import random class Solution: def __init__(self, w: List[int]): self.w = w # 1. calculate relative frequency denom = sum(self.w) for i in range(len(self.w)): self.w[i] = self.w[i] / denom # 2. put relative frequencies on the number line between 0 and 1 # Note self.w[-1] = 1 for i in range(1, len(self.w)): self.w[i] += self.w[i-1] def pickIndex(self) -> int: # this is where we pick the index N = random.uniform(0, 1) # test each region of the number line to see if N falls in it, if it # does not then go to the next index and check if N falls in it # this is guaranteed to break because of previous normalization for index, weight in enumerate(self.w): if N <= weight: return index # OR # index = 0 # while index < len(self.w): # if N <= self.w[index]: # return index # index += 1 # OR # flag = 1 # index = -1 # # while flag: # index +=1 # if N <= self.w[index]: # flag = 0 # # return index
Solution: Binary search
class Solution: def __init__(self, w: List[int]): s = sum(w) self.weight = [w[0]/s] for i in range(1, len(w)): self.weight.append(self.weight[-1]+w[i]/s) def pickIndex(self) -> int: l, r, seed = 0, len(self.weight)-1, random.random() while l < r: m = (l+r)//2 if self.weight[m] <= seed: l = m+1 else: r = m return l
Complexity
- Time: \(O(n + n) = O(2n) = O(n)\)
- Space: \(O(1)\)
[774/Hard] Minimize Max Distance to Gas Station
Problem
You are given an integer array
stationsthat represents the positions of the gas stations on the
x-axis. You are also given an integer
k.
You should add
knew gas stations. You can add the stations anywhere on the x-axis, and not necessarily on an integer position.
Let
penalty()be the maximum distance between adjacent gas stations after adding the
knew stations.
Return the smallest possible value of
penalty(). Answers within
10-6of the actual answer will be accepted.
Example 1:
Input: stations = [1,2,3,4,5,6,7,8,9,10], k = 9 Output: 0.50000
- Example 2:
Input: stations = [23,24,36,39,46,56,57,65,84,98], k = 1 Output: 14.00000
- Constraints:
10 <= stations.length <= 2000
0 <= stations[i] <= 108
stations is sorted in a strictly increasing order.
1 <= k <= 106
- See problem on LeetCode.
Solution: Binary Search
- The hint is that “answers within 10^-6 of the true value will be accepted as correct”. Because binary search may not find exact value but it can approach the correct answer.
- To use binary search to find the smallest possible value of penalty distance, initialize
left = 0and
right = the distance between the first and the last station.
countis the number of gas station we need to make it possible.
if count > k, it means
midis too small to realize using
kstations.
if count <= k, it means
midis possible and we can continue to find a bigger one.
- When
left + 1e-6 >= right, it means that the answer is within
10^-6of the true value.
class Solution: def minmaxGasDist(self, stations: List[int], k: int) -> float: left, right = 1e-6, stations[-1] - stations[0] while left + 1e-6 < right: mid = (left + right) / 2 count = 0 for a, b in zip(stations, stations[1:]): count += math.ceil((b - a) / mid) - 1 if count > k: left = mid else: right = mid return right
Complexity
- Time: \(O(n\log{m})\) where \(m = stations[N - 1] - stations[0]\) and \(stations\) is the input array containing \(n\) items.
- Space \(O(1)\)
[825/Medium] Friends Of Appropriate Ages
Problem
There are
npersons on a social media website. You are given an integer array
ageswhere
ages[i]is the age of the
i-thperson.
A person
xwill not send a friend request to a person
y(
x != y) if any of the following conditions is true:
age[y] <= 0.5 * age[x] + 7
age[y] > age[x]
age[y] > 100 && age[x] < 100
Otherwise,
xwill send a friend request to
y.
Note that if
xsends a request to
y,
ywill not necessarily send a request to
x. Also, a person will not send a friend request to themselves..
Complexity
- Time: \(O(\log{n})\)
- Space: \(O(n)\)
Solution: Dictionary with
{age: num_members}, iterate for each age group and check conditions
- Algorithm:
- Step 1: construct a dictionary with age as key and number of members in that age group as values. This can be done using
Counterin the
collectionsmodule.
- Step 2: iterate for every age group (not every person!) say “me”
- Step 3: for every age group check condition take (“age”,”me”) pair and check if the conditions asked are satisfied with
age<= 0.5 * me +7 age>me 3rd condition is always false so we can omit it.
- Step 4:
- Here we have 2 cases.
- Case (a): if your age is different from the other age
- For e.g., 16, 15, 15 then 15->16 and 15->16, i.e., 2*1 which is
age_count * me_count
- Case (b): if your age is same as other age
- For e.g., 16, 16 then 16<->16 i.e., 2.
- This would be same as number of edges in a graph with n vertices where each edge considered 2 times which is
2*nC2which would be
me_count*(me_count-1)
from collections import Counter class Solution: def numFriendRequests(self, ages: List[int]) -> int: count = 0 # Step 1 ages_dict = Counter(ages) # Step 2 for me in ages_dict: my_age_count = ages_dict[me] # Step 3 for age in ages_dict: if not (age <= 0.5 * me + 7 or age > me): # Step 4: case (a) if age != me: count += ages_dict[age]*my_age_count # Step 4: case (b) else: count += int(my_age_count*(my_age_count-1)) return count
Complexity
- Time: \(O(n)\)
- Space: \(O(n)\)
Solution: Binary Search with Counter
- Algorithm:
- Sort by age
- index
iperson will not send friend request to
ages[i]+1, ages[i]+2….
- index
iperson will not send friend request to elements whose age is less than (
0.5 * ages[i] + 7)
- Using binary search we can find upper and lower limit, persons which fall in this range, can send friend requests (remove 1,
i-thperson itself)
import bisect from collections import Counter class Solution: def numFriendRequests(self, ages: List[int]) -> int: ages.sort() counts = Counter(ages) total = 0 for age in counts: min_age = 0.5 * age + 7 # or age / 2 + 7 left = bisect.bisect_right(ages, min_age) right = bisect.bisect_right(ages, age) total += max(0, right - left - 1)*counts[age] # you cannot have negative count return total
Complexity
- Time: \(O(n)\)
- Space: \(O(n)\)
Solution: Binary Search without a Counter
import bisect from collections import Counter class Solution: def numFriendRequests(self, ages: List[int]) -> int: ages.sort() count = 0 for age in ages: left = bisect.bisect_right(ages, (0.5 * age) + 7) right = bisect.bisect_right(ages, age) count += max(0, right - left - 1) # you cannot have negative count return count
Complexity
- Time: \(O(n)\)
- Space: \(O(1)\)
[875/Medium] Koko Eating Bananas
Problem
Koko loves to eat bananas. There are
npiles of bananas, the
i-thpile has
piles[i]bananas. The guards have gone and will come back in
hhours.
Koko can decide her bananas-per-hour eating speed of
k. Each hour, she chooses some pile of bananas and eats
kbananas from that pile. If the pile has less than
kbananas, she eats all of them instead and will not eat any more bananas during this hour.
Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.
Return the minimum integer
ksuch that she can eat all the bananas within
hhours.
Example 1:
Input: piles = [3,6,7,11], h = 8 Output: 4
- Example 2:
Input: piles = [30,11,23,4,20], h = 5 Output: 30
- Example 3:
Input: piles = [30,11,23,4,20], h = 6 Output: 23
- Constraints:
1 <= piles.length <= 104
piles.length <= h <= 109
1 <= piles[i] <= 109
- See problem on LeetCode.
Solution: Binary search
- Binary search between
[1, max(piles)]to find the result.
- Note that
ceil(p / m)is equal to
(p + m - 1) // m.
class Solution: def minEatingSpeed(self, piles: List[int], h: int) -> int: # bananas-per-hour rate can vary between 1 and max(piles) l, r = 1, max(piles) while l < r: m = (l + r) // 2 # the ceil is present because if pile has less than `k` bananas, # Koko eats all of them instead and will not eat any more bananas during this hour. if sum(ceil(num_bananas_in_pile / m) for num_bananas_in_pile in piles) > h: # the number of hours needed are beyond what's permissible, i.e., the bananas-per-hour rate is less than needed l = m + 1 else: r = m return l
Complexity
- Time: \(O(n\log{m})\) where \(m = max(piles)\) and \(piles\) is the input array containing \(n\) items.
- Space \(O(1)\)
[1011/Medium] Capacity To Ship Packages Within D Days
Problem
A conveyor belt has packages that must be shipped from one port to another within
daysdays.
The
i-thpackagedays.
Example 1:
Input: weights = [1,2,3,4,5,6,7,8,9,10], days =.
- Example 2:
Input: weights = [3,2,2,4,1,4], days = 3 Output: 6 Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4
- Example 3:
Input: weights = [1,2,3,1,1], days = 4 Output: 3 Explanation: 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1
- Constraints:
1 <= days <= weights.length <= 5 * 104
1 <= weights[i] <= 500
Solution: Binary Search
- Binary search doesn’t sound like a natural fit when this problem is first encountered. We might want to automatically treat weights as search space and then realize we’ve entered a dead end after wasting lots of time. In fact, we are looking for the minimal one among all feasible capacities.
- The underpinning idea behind this problem is that if we can successfully ship all packages within
Ddays with capacity
m, then we can definitely ship them all with any capacity larger than
m. Now we can design a condition function, let’s call it
feasible, given an input capacity, it returns whether it’s possible to ship all packages within
Ddays. This can run in a greedy way: if there’s still room for the current package, we put this package onto the conveyor belt, otherwise we wait for the next day to place this package. If the total days needed exceeds
D, we return
False, otherwise we return
True.
- Next, we need to initialize our boundary correctly. Obviously capacity should be at least
max(weights), otherwise the conveyor belt couldn’t ship the heaviest package. On the other hand, capacity need not be more than
sum(weights), because then we can ship all packages in just one day. In other words. the lower bound is
max(A)for binary search, while the upper bound is
sum(A).
class Solution: def shipWithinDays(self, weights: List[int], D: int) -> int: def feasible(capacity): days = 1 local = 0 for w in weights: local+=w if local>capacity: local = w days+=1 if days>D: return False return True left, right = max(weights), sum(weights) while left < right: mid = left + (right-left)//2 if feasible(mid): right = mid else: left = mid + 1 return left
- Same approach; rehashed:
class Solution: def shipWithinDays(self, weights: List[int], D: int) -> int: left, right = max(weights), sum(weights) while left < right: mid, need, cur = (left + right) / 2, 1, 0 for w in weights: if cur + w > mid: need += 1 cur = 0 cur += w if need > D: left = mid + 1 else: right = mid return floor(left)
Complexity
- Time: \(O(n\log{m})\) where \(m = sum(weights)\) and \(weights\) is the input array containing \(n\) items
- Space \(O(1)\)
[1060/Medium] Missing Element in Sorted Array
Problem
Given an integer array
numswhich is sorted in ascending order and all of its elements are unique and given also an integer
k, return the
k-thmissing number starting from the leftmost number of the array.
Example 1:
Input: nums = [4,7,9,10], k = 1 Output: 5 Explanation: The first missing number is 5.
- Example 2:
Input: nums = [4,7,9,10], k = 3 Output: 8 Explanation: The missing numbers are [5,6,8,...], hence the third missing number is 8.
- Example 3:
Input: nums = [1,2,4], k = 3 Output: 6 Explanation: The missing numbers are [3,5,6,7,...], hence the third missing number is 6.
- Constraints:
1 <= nums.length <= 5 * 104
1 <= nums[i] <= 107
nums is sorted in ascending order, and all the elements are unique.
1 <= k <= 108
Follow up: Can you find a logarithmic time complexity (i.e.,
O(log(n))) solution?
- See problem on LeetCode.
Solution: Linear scan
class Solution: def missingElement(self, nums: List[int], k: int): for i in range(1, len(nums)): # number of missing elements between one index and the prior diff = nums[i] - nums[i-1] - 1 if diff >= k: return nums[i-1] + k else: k -= diff return nums[-1] + k
- Similar approach:
class Solution: def missingElement(self, nums: List[int], k: int) -> int: #Approach: # Step 1: find maximum possible kth number provided we had only one digit in array. # if will be (nums[0] + k) # Step2: nums[0] + k would have been the answer if there were no other digits, but if we have than we need to find number of digits which are less than nums[0] + k. # what is the kth missing number for single digit x, it is x + k ans = nums[0] + k # if length is one then x + k will be the answer if len(nums) == 1: return ans # if length is greater than one, we try to find how many numbers are less than # the maximum possible kth missing number (x+k) # whenever we encounter that there exist a number that is less than (x+k) we increase the (x+k) by 1 # as soon as our ans (x+k) is greater than any number in the list, we return ans. for currentNum in nums[1:]: if currentNum > ans: return ans if currentNum <= ans: ans += 1 return ans
Complexity
- Time: \(O(n)\)
- Space \(O(1)\)
Solution: Binary Search
- The idea is to find the first index that has more missing elements than
kusing binary search.
- For an input of
nums = [4,7,9,10], let’s consider the number of missing elements at the second index. They are
[5,6], i.e., 2 missing elements. This can be written as:
num[1] - num[0] - 1. For index
i, this can be generalized to
nums[i] - nums[0] - i.
- Finally, to get the first missing element, you can do
num[0] + k + 0. Generalizing this, you get
num[i] + k + i.
class Solution: def missingElement(self, nums: List[int], k: int) -> int: def calculateMissings(i): return nums[i] - nums[0] - i left, right = 0, len(nums) # find the first index that has more missing elements than `k` using binary search # i.e., the lower bound while left < right: middle = (left + right) // 2 # select the middle element in the array and compare it against the target if calculateMissings(middle) < k: left = middle + 1 else: right = middle return nums[0] + k + left - 1
- To understand the choice of
leftand
right, check out Shawnlyu: Binary Search – Find Upper and Lower Bound or Medium: Binary Search — Find Upper and Lower Bound
Complexity
- Time: \(O(n\log{n})\)
- Space \(O(1)\)
[1231/Hard] Divide Chocolate
Problem
You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array sweetness.
You want to share the chocolate with your
kfriends so you start cutting the chocolate bar into
k + 1pieces using
kcuts, each piece consists of some consecutive chunks.
Being generous, you will eat the piece with the minimum total sweetness and give the other pieces to your friends.
Find the maximum total sweetness of the piece you can get by cutting the chocolate bar optimally.
Example 1:
Input: sweetness = [1,2,3,4,5,6,7,8,9], k = 5 Output: 6 Explanation: You can divide the chocolate to [1,2,3], [4,5], [6], [7], [8], [9]
- Example 2:
Input: sweetness = [5,6,7,8,9,1,2,3,4], k = 8 Output: 1 Explanation: There is only one way to cut the bar into 9 pieces.
- Example 3:
Input: sweetness = [1,2,2,1,2,2,1,2,2], k = 2 Output: 5 Explanation: You can divide the chocolate to [1,2,2], [1,2,2], [1,2,2]
Solution: Binary Search
class Solution: def maximizeSweetness(self, sweetness: List[int], k: int) -> int: left, right = 1, sum(sweetness) // (k + 1) while left < right: mid = (left + right + 1) // 2 cur = cuts = 0 for chunk in sweetness: cur += chunk if cur >= mid: cuts += 1 cur = 0 if cuts > k: left = mid else: right = mid - 1 return right
- Note that in this question, we want to find the maximum total sweetness. We have to find the rightmost value, so we use
int mid = (left + right + 1)/2and
if (condition passed) left = mid; else right = mid - 1. For a question like Capacity to Ship Packages Within D Days, we want to find the leftmost value. So we have to use something like
int mid = (left + right) / 2and
if (condition passed) right = mid; else left = mid + 1.
Complexity
- Time: \(O(n\log{m})\) where \(m = sum(sweetness)\) and \(sweetness\) is the input array containing \(n\) items
- Space \(O(1)\)
[1283/Medium] Find the Smallest Divisor Given a Threshold
Problem
Given an array of integers
numsand an integer
threshold, we will choose a positive integer
divisor, divide all the array by it, and sum the division’s result. Find the smallest
divisorsuch that the result mentioned above is less than or equal to
threshold.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example:
7/3 = 3and
10/2 = 5).
The test cases are generated so that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6 Output: 5 Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
- Example 2:
Input: nums = [44,22,33,11,1], threshold = 5 Output: 44
- Constraints:
1 <= nums.length <= 5 * 104
1 <= nums[i] <= 106
nums.length <= threshold <= 106
- See problem on LeetCode.
Solution: Binary Search
- If
sum > threshold, the divisor is too small.
- If
sum <= threshold, the divisor is big enough.
class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: l, r = 1, max(nums) while l < r: m = (l + r) // 2 if sum(math.ceil(num / m) for num in nums) > threshold: # or if sum((num + m - 1) // m for num in nums) > threshold: l = m + 1 else: r = m return l
Note that
(p + m - 1) / mis equal to
ceil(p / m).
Same approach; rehashed:
- If a number is large enough, it will definitely have a result less than threshold; we need to find the smallest number that can do this.
- How to check whether a given number can make the result less than or equal to
threshold?
- Just do a one pass on
numsand see if the sum of the
ceilof each division is less than or equal to
threshold.
- If given
midis a ok number, then we want to see if a smaller number can do the same thing, so
- if
ok(mid)is
True:
r = mid-1
- else:
l = mid+1
class Solution: def smallestDivisor(self, nums: List[int], threshold: int) -> int: def ok(mid): ans = 0 for num in nums: ans += math.ceil(num / mid) if ans > threshold: return False return True l, r = 1, int(1e6) while l <= r: mid = (l+r) // 2 if ok(mid): r = mid - 1 else: l = mid + 1 return l
Complexity
- Time: \(O(n\log{m})\) where \(m = max(A)\) and \(A\) is the input array containing \(n\) items
- Space \(O(1)\)
[1482/Medium] Minimum Number of Days to Make \(m\) Bouquets
Problem
You are given an integer array
bloomDay, an integer
mand an integer
k.
You want to make
mbouquets. To make a bouquet, you need to use
kadjacent flowers from the garden.
The garden consists of
nflowers, the
i-thflower will bloom in the
bloomDay[i]and then can be used in exactly one bouquet.
Return the minimum number of days you need to wait to be able to make m bouquets from the garden. If it is impossible to make m bouquets return
-1.
Example 1:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 1 Output: 3 Explanation: Let us see what happened in the first three days. x means flower bloomed and _ means flower did not bloom in the garden. We need 3 bouquets each should contain 1 flower. After day 1: [x, _, _, _, _] // we can only make one bouquet. After day 2: [x, _, _, _, x] // we can only make two bouquets. After day 3: [x, _, x, _, x] // we can make 3 bouquets. The answer is 3.
- Example 2:
Input: bloomDay = [1,10,3,10,2], m = 3, k = 2 Output: -1 Explanation: We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
- Example 3:
Input: bloomDay = [7,7,7,7,12,7,7], m = 2, k = 3 Output: 12 Explanation: We need 2 bouquets each should have 3 flowers. Here is the garden after the 7 and 12 days: After day 7: [x, x, x, x, _, x, x] We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent. After day 12: [x, x, x, x, x, x, x] It is obvious that we can make two bouquets in different ways.
- Constraints:
bloomDay.length == n
1 <= n <= 105
1 <= bloomDay[i] <= 109
1 <= m <= 106
1 <= k <= n
- See problem on LeetCode.
Solution: Binary Search
- If
m * k > n, it’s impossible, so return
-1.
- Otherwise, we deem it a possible task, so we can binary search the result.
left = 1is the smallest number of days,
right = max(bloomDay)is big enough to make
mbouquets.
- Next, we are going to binary search in range
[left, right].
- Given
middays, we can know which flowers blooms.
- Now the problem is, given an array of
Trueand
False, find out how many adjacent
Truebouquets are there in total.
- If
bouq < m,
midis still small for
mbouquet. So we set
left = mid + 1.
- If
bouq >= m,
midis big enough for
mbouquet. So we set
right = mid
class Solution: def minDays(self, bloomDay: List[int], m: int, k: int) -> int: if m * k > len(bloomDay): return -1 left, right = 1, max(bloomDay) while left < right: mid = (left + right) // 2 flow = bouq = 0 for a in bloomDay: flow = 0 if a > mid else flow + 1 if flow >= k: flow = 0 bouq += 1 if bouq == m: break if bouq == m: right = mid else: left = mid + 1 return left
Complexity
- Time: \(O(n\log{m})\) where \(m = max(bloomDay)\) and \(bloomDay\) is the input array containing \(n\) items
- Space \(O(1)\)
[1539/Easy] Kth Missing Positive Number
Problem
Given an array
arrof positive integers sorted in a strictly increasing order, and an integer
k.
Find the
k-thpositive integer that is missing from this array.
Example 1:
Input: arr = [2,3,4,7,11], k = 5 Output: 9 Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
- Example 2:
Input: arr = [1,2,3,4], k = 2 Output: 6 Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
- Constraints:
1 <= arr.length <= 1000
1 <= arr[i] <= 1000
1 <= k <= 1000
arr[i] < arr[j] for 1 <= i < j <= arr.length
- See problem on LeetCode.
Solution: Maintain a count for number of missed values
- We could go one by one from 1 and check if the number contained in the list (converting
ato set for faster checking) and maintain a counter for the number of missed values.
class Solution: def findKthPositive(self, a: List[int], k: int) -> int: s = set(a) cnt = 0 for i in range(1, max(s)): if i not in s: cnt += 1 if cnt == k: return i return max(s) + k - cnt
Complexity
- Time: \(O(L+\max(a))\) time, where L is the length of the array assuming Python set takes \(O(1)\) time insert or look up an element (the average case for a hash table). \(L\) for building the set and max(a) for the number of set queries.
- Space \(O(1)\)
Solution: Maintain a count
- Since the array is sorted, we could do better by going one pass over the array instead.
class Solution: def findKthPositive(self, a: List[int], k: int) -> int: cnt = 0 j = 0 for i in range(1, max(a)): if i < a[j]: cnt += 1 if cnt == k: return i else: j += 1 if j >= len(a): break return a[-1] + k - cnt
Complexity
- Time: \(O(max(a))\)
- Space \(O(1)\)
Solution: Maintain a count between adjacent integers
- We do not need to increase the numbers one by one. All numbers between two adjacent integers in
acan be updated to the counter at once.
class Solution: def findKthPositive(self, a: List[int], k: int) -> int: cnt, prev = 0, 0 for x in a: old_cnt = cnt cnt += x - prev - 1 if cnt >= k: return prev + k - old_cnt prev = x return a[-1] + k - cnt
Complexity
- Time: \(O(n)\) where \(n = len(arr)\)
- Space \(O(1)\)
Solution: Maintain a count between adjacent integers
But wait… Do we really need a counter? If there is no missing number, the
a[i]should just be
i+1. If there is a single missing number before
a[i],
a[i]should be just
i+2. So on so forth. In general, if there are m missing numbers up to
a[i],
a[i] = i + m + 1. So, when we see
a[i], we know there are
a[i]-i-1missing numbers up to it. If
a[i]-i-1 >= kor
a[i] > i+k, the
k-thmissing value must be between
a[i-1]and
a[i].
On the other hand, if there have already been
inumbers in
a, the
k-thmissing value must be at least
k+i. We show that
k+iis actually the value we are looking for. First,
a[i] > i+k, so
i+kcannot be
a[i]. Neither can it be any
a[j], j > i, because
ais increasing and
a[j] > a[i] > i+k. Can
i+kappear before
a[i]? If that is the case, say
i+k = a[j]for some
j < i, then we will have a[j] =
i+k > j+k. That means we would have found an earlier location
jthat triggers the
a[j] > j+kcriterion, and we would have stopped over there.
The above analysis gives us this clean 4 lines of code:
class Solution: def findKthPositive(self, a: List[int], k: int) -> int: for i, x in enumerate(a): if x > i + k: return i + k return len(a) + k
Complexity
- Time: \(O(n)\) where \(n = len(arr)\)
- Space \(O(1)\)
Solution: Binary Search
- Assume the final result is
x, and there are
mnumbers present in the range of
[1, x]. Binary search the
min range
[0, len(A)].
- If there are
mnumbers present, that is
A[0], A[1] .. A[m-1], the number of missing under
A[m]is
len(A[m]) - 1 - m.
- If
A[m] - 1 - m < k,
mis too small, we update
left = m.
- If
A[m] - 1 - m >= k,
mis big enough, we update
right = m.
- Note that when we exit the while loop,
l = r, which equals to the number of missing numbers.
- So the
K-thpositive number will be
l + k.
class Solution: def findKthPositive(self, arr: List[int], k: int) -> int: l, r = 0, len(arr) while l < r: m = (l + r) // 2 if arr[m] - 1 - m < k: l = m + 1 else: r = m return l + k
Complexity
- Time: \(O(\log{n})\) where \(n = len(arr)\)
- Space \(O(1)\)
[1891/Medium] Cutting Ribbons
Problem
You are given an integer array
ribbons, where
ribbons[i]represents the length of the
i-thribbon, and an integer
k. You may cut any of the ribbons into any number of segments of positive integer lengths, or perform no cuts at all.
- For example, if you have a ribbon of length 4, you can:
- Keep the ribbon of length 4,
- Cut it into one ribbon of length 3 and one ribbon of length 1,
- Cut it into two ribbons of length 2,
- Cut it into one ribbon of length 2 and two ribbons of length 1, or
- Cut it into four ribbons of length 1.
Your goal is to obtain
kribbons of all the same positive integer length. You are allowed to throw away any excess ribbon as a result of cutting.
Return the maximum possible positive integer length that you can obtain k ribbons of, or 0 if you cannot obtain k ribbons of the same length.
Example 1:
Input: ribbons = [9,7,5], k = 3 Output: 5 Explanation: - Cut the first ribbon to two ribbons, one of length 5 and one of length 4. - Cut the second ribbon to two ribbons, one of length 5 and one of length 2. - Keep the third ribbon as it is. Now you have 3 ribbons of length 5.
- Example 2:
Input: ribbons = [7,5,9], k = 4 Output: 4 Explanation: - Cut the first ribbon to two ribbons, one of length 4 and one of length 3. - Cut the second ribbon to two ribbons, one of length 4 and one of length 1. - Cut the third ribbon to three ribbons, two of length 4 and one of length 1. Now you have 4 ribbons of length 4.
- Example 3:
Input: ribbons = [5,7,9], k = 22 Output: 0 Explanation: You cannot obtain k ribbons of the same positive integer length.
- Constraints:
1 <= ribbons.length <= 105
1 <= ribbons[i] <= 105
1 <= k <= 109
Solution: Binary search
- The crux of the problem is implementing Binary Search.
- The goal is to figure out what the maximum length of a ribbon could be so that we get
kribbons of that max length.
- One way to think of it would be that the ribbon length could be anywhere from 1 to the max length of the a ribbon available in the list.
- So what we do is go through the list (using Binary Search since we need to optimize linear search), find the
midof the given array and then iterate through the list testing the length with each element and summing the number of ribbons that can be made with the mid value. Then change
midaccordingly.
class Solution: def maxLength(self, ribbons: List[int], k: int) -> int: # impossible case: when total length sum of all ribbons are less than `k` s = sum(ribbons) if s < k: return 0 # The minimum length of the ribbon that we can cut is 1 start = 1 # The maximum length of the ribbon can be the maximum element in the list end = max(ribbons) # In this binary search, we are trying to go through the origin list and figure out which integer(from 1 -> ribbon of max length) is the deired length for the the target k pieces while(start <= end): mid = start + (end - start) // 2 res = 0 for i in ribbons: res += i // mid # If the value is >= target, we know that there could be a larger integer that will satisfy the same conditon if res >= k: start = mid+1 else: # If lesser than k, then there could be a value lesser than the mid that could satisfy the condition end = mid -1 return end
Complexity
- Time: \(O(n\log{m})\) where \(m = max(ribbons)\) and \(ribbons\) is the input array containing \(n\) items
- Space \(O(1)\) | https://aman.ai/code/binary-search/ | CC-MAIN-2022-40 | refinedweb | 8,549 | 68.4 |
the isthmus in the VM
By John.Rose-Oracle on Mar 17, 2014
This is a good time to consider new options for a “native interconnect” between code managed by the JVM and APIs for libraries not managed by the JVM.
Notably, Charles Nutter has followed up on his JVM Language Summit talk (video on this page) by proposing JEP 191, to provide a new foreign function interface for Java. To access native data formats (and/or native-like ones inside the JVM), there are several projects under way including David Chase’s data layout package, Marcel Mitran’s packed object proposal, and Gil Tene’s object layout project.
This article describes some of the many questions related to native interconnect, along with some approaches for solving them. We will start Project Panama in OpenJDK to air out these questions thoroughly, and do some serious engineering to address them, for the JDK.
Let us use the term native interconnect for connections between the JVM and “native” libraries and their APIs. By “native” libraries I simply mean those routinely used by programmers of statically compiled languages outside the JVM.
the big goal
I think the general, basic, idealistic goal is something like this:
If non-Java programmers find some library useful and easy to access, it should be similarly accessible to Java programmers.
That ideal is easy to state but hard to carry out.
The fundamental reason is simple—the languages are different.
C++ programmers use the
#include statement for pulling in APIs,
but it would be deeply misguided to try to add
#includes to
the Java language.
For more details on how language differences affect
interconnection, see the discussion below.
Happily, this is not completely new ground, since managed languages
(including Lisp, Smalltalk, Haskell, Python, Lua, and more)
have a rich history of support for native interconnect.
Most subtly, even if all the superficial differences could be adjusted, the rules for safe and secure usage of Java differ from those of the native, statically-compiled languages. There is a range of choices for ensuring that a native library gets safely used. The main two requirements are to make VM-damaging errors very rare, and (as a corollary) to make intentional attacks very difficult. We will get into more details below.
Besides safety, Java has a distinctive constellation of “cultural” values and practices, notably the features which provide safety and error management. So, the access to C APIs must be be adapted to the client language (Java) by means of numerous delicate compromises and engineering choices to preserve not only the “look and feel” of Java expressions but also their deeper cultural norms. By using the metaphor of culture, I don’t imagine a “Java way of life”, but I observe that there are “Java ways” of coding, which differ interestingly from other ways of coding. Cultural awareness becomes salient when cultures meet and mix.
Anyway, to get this done, we need to build a number of different artifacts, including Java libraries, JVM support mechanisms, tools, and format specifications. A number of possibilities are enumerated below.
why this is difficult
First, let’s survey some of the main challenges to full native interconnect.
syntax: Since the languages differ, Java user code for a native API will differ in syntax from the corresponding native user code, sometimes surprisingly. For example, Java 8 lambdas are very different in detail from C function pointers, although they sometimes have corresponding uses. Java has no general notions corresponding to C macros or C++ templates.
naming: Different languages have different rules for identifier formation, API scoping (packages vs. namespaces), and API element naming. Languages even have differing kinds of names: Java has distinct name spaces for fields and methods, while C++ has just members.
data types: Basic data types differ. Booleans, characters, strings, arrays differ between the languages C++ uses pointers, sometimes for information hiding, sometimes for structurally transparent data. Java uses managed references, which always have some hidden structure (the object header). And so on. A user-friendly Java interconnect to a native API needs to adjust the types of API arguments and return values to reduce surprises.
storage management: Many native libraries operate through pointers to memory, and they provide rules for managing that memory’s lifetime. Java and native languages have very distinct tactics for this. Java uses garbage collection and C++ libraries usually require manual storage management. Even if C++ were to add garbage collection, the details would probably be difficult to reconcile. A safe Java interconnect to a native API needs to manage native storage in a way that cannot crash the JVM.
exceptions: As with storage management, languages differ in how they handle error conditions. C++ and Java both have exceptions, but they are used (and behave) in very different ways. For example, C++ does not mandate null pointer exceptions. C APIs sometimes require ad hoc polling for errors. A user-friendly Java interconnect to a native API needs a clear story for producing exceptions, which is somehow derived from the native library’s notion of error reporting.
other semantics: Java’s strings are persistent (used to be called “immutable”) while C’s strings are directly addressable character arrays which can sometimes change. (And C++ strings are yet another thing.)
performance: Code which uses Java primitives performs on a par corresponding C code, but if an API exchanges information using other types, including strings, boxing or copying can cause performance “potholes”. I expect that value types will narrow the gap eventually for other C types, but they are not here yet.
safety: I’m putting this last, but it is the most difficult and important thing to get right. It deserves its own list of issues, but the gist of it is the JVM as a whole must continue to operate correctly even in the face of errors or abuse of any single API. The next section examines this requirement in detail.
safety first
The JVM as a whole must continue to operate correctly when native APIs are in use by various kinds of users.
no attacks from untrusted code: Untrusted code must not be allowed to subvert the correct operation of the JVM, even if it makes very unusual requests of native APIs available to it. This implies that many native APIs must be made inaccessible to untrusted code.
no privilege escalation from untrusted code: Untrusted users should not be able to access files, resources, or Java APIs via native APIs, if they would not already have access to them via Java code.
no crashes: It must be difficult for ordinary user code, and impossible for untrusted code, to crash the JVM using using a native API. Native API calls which might lead to unpredictable behavior must be detected and prevented in Java code, preferably by throwing exceptions. Pointers to native memory must be checked for null before all use, and discarded (e.g., set to null) when freed.
no leaks: It must be difficult or impossible for ordinary user code to use a native API to use memory or other system resources in a way that they cannot be recovered when the user code exits. Native resources must be used in a manner that is scoped
no hangs: It must be difficult or impossible for ordinary user to cause deadlocks or long pauses in system execution. Pauses for JVM housekeeping, like garbage collection, must not be noticeably lengthened because of waits for threads running native code.
rare outages: Even if code is partially or fully trusted, errors that might lead to crashes, leaks, or hangs must be detected before they cause the outage, almost always.
no unguarded casts: If privileged Java code must use cast-like operators to adjust its view of native data or functions, the casting must be done only after some kind of check has proven that the cast will be valid. This implies that native data and functions must be accessed through Java APIs that fully describe the native APIs and can mechanically check their use.
From these observations, it is evident that there are at least three trust levels that are relevant to native interconnect: untrusted, normal, and privileged.
Java enforces configurable security policies on untrusted code, using APIs like the security manager. This ensures that untrusted code cannot break the system (or elevate privileges) even if APIs are abused.
Normal code is the sort of code which can run in a JVM without a
security manager set. Such code might be able to damage the JVM,
using APIs like
sun.misc.Unsafe, but will not do so by accident.
As a practical way to reduce risk, we can search normal code
for risky operations, which should be isolated, and review their use
for safety.
I think many of the tricky details of native interconnect are related to this concept of privileged code. Any system like the JVM that enforces safety invariants or access restrictions has trusted, privileged code that performs unsafe or all-access operations, such as file system access, on behalf of other kinds of code.
Put another way, privileged code is expected to be in the risky business. It is engineered with great care to conform to safety and security policies. It supports requests from non-privileged code—even untrusted code—after access checks on behalf of the requester. Privileged code needs maximum access to native APIs of the underlying system, and must use them in a way that does not propagate that access to other requesters.
engineering privileged wrapper code
In the present discussion, we can identify at least two levels of binding from Java code to native APIs: a privileged “raw access” to most or all API features, and a wrapped access that provides safety guarantees that match the cultural expectation of Java programmers.
So let’s examine the process of engineering the wrapper code that stands between normal Java users and native APIs.
In current implementations of the JDK, native APIs are wrapped in hand-written JNI wrapper code, written in C. In particular, all C function calls are initiated from JNI wrappers.
(There is plenty of other privileged code written both in Java and C++.
Much Java code in packages under
java.lang and
sun is privileged
in some way. Most of it is not relevant to the present subject.)
Ideally, wrapper code should be constructed or checked mechanically when possible.
In the present system, the
javah tool assists, slightly, in bridging between
Java APIs and JNI code. JNI wrapper code is checked by the native C compiler.
And that is about all. Surely Java-centered tools could do more.
On the other hand, as we saw above, bringing the languages together is hard. No tool can erase the cultural differences between Java and native languages. There will always be ad hoc adjustment to reduce or remove hazards from native APIs. Such adjustments will usually be engineered by hand in privileged code, as they are today in JNI wrapper code.
We must ask ourselves, why bother to build new mechanisms for native interconnect when JNI wrappers already do the job? If manual coding will always be required, perhaps it is better to do the coding in the native language, where (obviously) the native APIs are most handy. In that case, there would be no need for Java code ever to perform unsafe operations. Isn’t this desirable?
I think the general answer is that we can improve on the trade-offs provided by the present set of tools and procedures. Specifically, by using more Java-centered tools and procedures, we can improve performance. Independently of performance, we can also decrease the engineering costs of safety.
better performance without compromising safety
Safety will always trade against performance, but—as Java has proven over its lifetime—it is possible with care to formulate and optimize safety checks that do not interfere unacceptably with performance.
Classic JNI performance is relatively poor, and some of the reasons are inherent in its design. JNI wrappers are created and maintained by hand, which means that the JVM cannot “see into” them for optimizing them.
If the JNI wrappers were recoded in Java (or some other transparent representation) then the JVM could much better optimize the enforcement of safety checks. For example, a program containing many JNI calls could be reorganized as one which grouped the required safety checks (and other housekeeping) into a smaller number of common blocks of code. These blocks could then be optimized, amortizing the cost of safety checks across many JNI calls.
Analogous optimizations of lock coarsening or boxing elimination are possible because all the operations are fully transparent to the JVM. By comparison, there is much unnecessary overhead around native calls today.
This sort of optimization is routine when the thing being called can be broken down into analyzable parts by the JIT compiler. But C-coded JNI wrappers are totally opaque to it. The same is currently true of the wrappers created by JNR, but they are regular enough in structure that the JIT can begin to optimize them.
In my opinion, a good goal is to continue opening up the representation of native API calls until the optimized JIT code for a native API call is, well, optimal. That is, it can and should consist of a direct call to the native API, surrounded by a modest amount of housekeeping, and all inlined and optimized with the client Java code.
Making this happen in the compiler will require certain design adjustments. Specifically, the metadata for the native API must be provided in a form suitable for both the JVM interpreter and compiler. More precisely, it must support both execution by the JVM interpreter and/or first-level JIT, and also optimizing compilation by the full JIT. This implies that the native API metadata must contain some of the same kind of information about function and data shape that a C compiler uses to compile calls within C code.
lower engineering costs for safety
I also think that coding more wrapper logic in Java instead of C will provide more correctness at a lower engineering cost. Although wrapper code in C has the advantage of direct access to native APIs, the code itself is difficult to write and to review for correctness. C programmers can create errors such as unsafe casts in a few benign-looking keystrokes. C-oriented tools can flag potential errors, but they are not designed to enforce Java safety norms.
If direct access to C APIs were available to Java code, all other aspects of wrapper engineering would be simpler and easier to verify as correct. Java code is safer and more verifiable than C code. If written by hand, it is often more compact and simple than corresponding C code. Routine aspects of wrapper engineering could be specified declaratively, using specialized tools to generate Java code or bytecode automatically. Whether Java wrapper code is created manually or automatically, it is subject to layers of safety checking (verifying and dynamic linking) that C code does not enjoy. And Java code (both source files and class files) can be easily inspected by tools such FindBugs.
The strength of such an automated approach can be seen in the work noted by JEP 191, the excellent JNR project. For a quick look at a “hello world” type example from JNR, see Getpid.java. Although the emphasis on JNR is on function calling, integrated native interconnect to functions, data, and types is also possible.
Side note: My personal favorite example of automated language integration is an old project that integrated C++ and Scheme on Solaris. The native interconnect was strong enough in that system to allow full interactive exploration of C++ APIs using the Scheme interpreter. That was fun.
One way we can improve on the safe use of these prior technologies is to provide more mechanical infrastructure for reasoning about the safety of Java application components. It should be possible to create wrapper libraries that internally use unsafe native APIs but reliably block their users from accessing those APIs. To me this feels like a module system design problem. In any case, it must be possible to correctly label, track, review, and control both unsafe code and the wrapper code that secures it.
wrapper tactics
A likely advantage of Java-based wrappers is easier access to good engineering tactics for wrapping native APIs. Here are a few examples of such tactics:
- exception conversion: Error reporting conventions specific to native languages or APIs can be converted to Java exceptions.
- pointer handles: Native pointers which can or must be freed can be stored in Java wrapper objects which nullify the saved pointer when it is freed, and check for this state as needed.
- wrapper objects: Native data can be encapsulated inside Java objects to mediate access by providing a safe view. The object can use an internal handle field to manage native lifetime.
- (Future wrapper values: In cases where stateless wrappers can do the job, value types are likely to provide provide cheaper encapsulation in the future. This would be the case with primitive types not in Java, such as unsigned long or platform specific vectors. When native lifetime is not an issue, value types could also provide encapsulating views of native pointers, structs, and arrays.)
- resource scoping: APIs which require critical sections or paired primitives can be mapped to the Java try-with-resources syntax or refactored into a callback driven style (using lambdas).
- language feature mapping: Corresponding types and operations can usually be mapped according to simple conventional rules. For example, a C
char*can usually be represented by a Java
Stringobject at an API boundary. (But, these mappings must be tunable on a case-by-case basis.)
- static typing: The Java type system can represent a wide variety of type shapes.
- design rule checking: Ad hoc usage rules for native APIs can be enforced as executable assertions in code wrapped around the unchecked native API.
- interfaces: Every transfer of control or data into or out of a native API can (and should) be mediated through a Java interface. In this way fully abstract API shapes can be presented directly to the (unprivileged) end user without exposing sensitive implementations.
Most of these tactics can be made automatic or semi-automatic within a code generation tool, and apply routinely unless manually disabled. This will further reduce the need for tricky hand-maintained code.
Interfaces are particularly useful for expressing groups of methods, since they express (mostly) pure behavior rather than Java object implementation. Also, interfaces are easy to compose and adapt, allowing flexible application of many of the above tactics.
As used to represent an extracted native API, an interface would be unique to that API. Uses of such interfaces would tend to be in one-to-one correspondence with their implementations. In that case JVMs are routinely able to remove the overhead of method selection and invocation by inlining the only relevant implementation.
questions to answer, artifacts to build
A native interconnect story will supply answers to a number of related questions:
How do we simplify the user experience for Java programmers who use C and C++ APIs? (The benchmark is the corresponding experiences of C and C++ programmers, as well as the experiences of today’s JNI programmers.)
What appropriate tools, APIs, and data formats support these experiences? Specifically, how is API metadata produced, stored, loaded, and used? How are native libraries named and loaded?
What appropriate JVM and JDK infrastructure works with native API elements (layouts, functions, etc.) from Java code (interpreter and JIT)?
How performant are calls and data access to native libraries? (Again, the benchmark is the corresponding experiences of C and C++ programmers, as well as the experiences of today’s JNI programmers.) enjoyed by their primary users (programmers of C, C++, Fortran, etc.).
What are the definite, reliable safety levels available for using native libraries from Java? This includes the question: What is the range of options between automatic, perhaps unsafe import, and engineered hand-adjustments?
What are the options for managing portability? This includes the use of platform-specific libraries, and a story for switching between platform-specific bindings and portable backup implementations.
Answering these questions affirmatively will require us to build some interesting technology, including discrete and separable projects to enable these functions:
- native function calling from JVM (C, C++)
-
Project Panama in OpenJDK will provide a venue for exploring these projects. Some of them will be closely aligned with OpenJDK JEPs, notably JEP 191, allowing the Project to incubate early work on them.
Other inspiration and/or implementation starting points include:
- the Java Native Runtime package and the libffi native call binder
- Java data layout packages
- JVM support for new layouts (IBM packed objects, Sun Labs Maxine hybrids, Arrays 2.0)
- metadata-based native API extractors (WinRT metadata)
- existing JVM infrastructure (class files, SA, JNI, sun.misc.Unsafe)
A native header file import tool scans C or C++ header files and provides raw native bindings for privileged Java code. Such tools exist already for other languages, and can get colorful names like SWIG or Groveller.
For the present purposes, I suggest a simpler name like
jextract.
A high-quality implementation for Java could start with an
off-the-shelf front end like libclang.
It would apply Java-oriented rules (with hand-tunable defaults)
and produce some form of metadata, such as loadable class files.
A toolchain that embodies many of these ideas could look something like this:
/-----------| /-----------| | stdio.h | | stdio.java | |------------| |------------| | | v | |------------| | | jextract | <-----/ |------------| | v /-----------| | stdio.jar | /------------| |------------| | userapp.jar| | |------------| v | |------------| | | jvm | <--------/ /---------| | | <--------------| libc.dll | |------------| |----------|
The
stdio.java file would contain hand-written adjustments to the raw API from the header file.
The
stdio.jar file would contain automatically gathered metadata from the header file,
plus the results of compiling
stdio.java.
The contents of
stdio.java could be straight Java code for the user-level API,
but could also be annotations to be expanded by a code generation step in the extraction process.
The code in
userapp.jar would access the features it needs from
stdio.jar.
The implementations of these interfaces would avoid C code as much as possible,
so that the JVM’s JIT can optimize them suitably.
Side note: The familiar header file I am picking on is actually unlikely to need this full treatment. In a more typical case, a whole suite of header files would be extracted and wrapped.
For bootstrapping or pure interpretation, a minimum set of trusted primitives are required in the JVM to perform data access and function call. these would be coded in C and also known to the JIT as intrinsics. They can be made general enough to implement once in the JVM, rather than loaded (as JNI wrappers are loaded today) separately for each native API. For example, JNR uses a set of less than 100 specially designed JNI methods to perform all native calls; these methods are collectively called jffi.
Building such toolchains will allow cheaper, faster commerce between Java applications and native APIs, much as the famous Panama Canal cuts through the rocky isthmus that separates the Atlantic and Pacific Oceans.
Let’s keep digging.
Appendix: preserving Java culture
Let’s go back to the metaphor of culture as it applies to the world of Java programming.
Here is a list of benefits about Java that programmers rely on, which any design for native interconnect must preserve. As a group, these features support a set of basic programming practices and styles which allow programmers great freedom to create good code. They can be viewed as the basis of a programming “culture”, peculiar to Java, which fosters safe, useful, performant, maintainable code.
Side note: This list contains many truisms and will be unsurprising to Java users. Remember that culture is often overlooked until two cultures meet. I am writing this list in hopes it will prove useful as a checklist to help analyze design problems with native interconnect, and to evaluate solutions. Also, I am claiming that the sum total of these items underlies a unique programming culture or ecosystem to Java, but not that they are individually unique to Java.
-.
All of these benefits are familiar to Java programmers, perhaps even taken for granted. The corresponding benefits for a native language like C++ are often more complex, and require more work and care from the native programmer to achieve.
A good native interconnect story will provide ways to reliably dispose of this work and care before it gets to the end user coding Java to a native API.
This requires native APIs to be acculturated to Java by the artful creation of wrapper code, as noted above.
It would be really great, if Project Panama would also be designed to include easy access to Objective-C APIs, beside C and C++ APIs.
Objective-C is in widespread use these days.
Posted by guest on March 19, 2014 at 02:42 AM PDT #
speaking of easy of use there are
they both focus on easy of use and bridj fixes some awful performance issues of jna ... but speaking of the performance (I mean real performance)
1. SLOW callbacks from native to java
2. lack of structs&layout control in java (it kills!!!)
check structs, pointers to structs, fixed arrays in .NET problem was solved years ago... and in java we have to go off-heap and do all the nasty tricks :(... it's a shame :(
even go-lang has better integration with C :)
Posted by Nick Evgeniev on March 22, 2014 at 09:52 PM PDT #
This reminds me distinctly of a certain project that Sun did back in the day, addressing all the same concerns:
Are you leveraging that excellent piece of work in Panama?
Good luck John!
Posted by guest on June 17, 2014 at 10:03 AM PDT #
Do you know the gluegen2 tool from JOGL2 ? This seems to be really similar to the jextract tool and has already been used to map a complex API (OpenGL all versions). Even if this tool do no focus on safety it seems to be quiet easy to add protection on the shared runtime code.
Posted by davidcl on June 24, 2014 at 09:03 AM PDT # | https://blogs.oracle.com/jrose/entry/the_isthmus_in_the_vm | CC-MAIN-2016-36 | refinedweb | 4,380 | 52.8 |
ploy_fabric 1.1.0
Plugin to integrate Fabric with ploy.
Installation
ploy_fabric is best installed with easy_install, pip or with zc.recipe.egg in a buildout.
Once installed, it’s functionality is immediately usable with ploy.
Commands
The plugin adds the following commands to ploy.
- do
Runs a Fabric task with simplified syntax for arguments. You can just put positional arguments on the command line behind the task name. For keyword arguments user the name=value syntax. For example:
ploy do something arg key=value
- fab
- Runs a Fabric task and passes on command line options to Fabric. This basically reflects the fab script of Fabric.
Options
Instances only get the new fabfile option to specify which file to look in for tasks. The location is relative to ploy.conf.
Instance methods
For the Python side, each instance gains the do(task, *args, **kwargs) method. The task argument is the name of a task from the Fabric script which should be run. The remaining arguments are passed on to that task.
Another helper added to each instance is a context manager accessible via the fabric attribute on instances. With that you can switch to a new ssh connection with a different user in your Fabric tasks:
from fabric.api import env, run def sometask(): run("whoami") # prints the default user (root) with env.instance.fabric(user='foo'): run("whoami") # prints 'foo' if the connection worked run("whoami") # prints the default user (root)
All changes to the Fabric environment are reverted when the context manager exits.
Fabric task decorator
With ploy_fabric.context you can decorate a task to use a specific user with a separate connection. All changes to the Fabric environment are reverted when the context manager exits. This is useful if you want to run a task from inside another task.
from fabric.api import env, run from ploy_fabric import context @context # always run with the default user def sometask(): run("whoami") # prints the default user (root) @context(user=None) # always run with the default user (alternate syntax) def someothertask(): env.forward_agent = True run("whoami") # prints the default user (root) @context(user='foo') # always run as foo user def anothertask(): env.forward_agent = False run("whoami") # prints the default user (user) someothertask() assert env.forward_agent == False
Fabric environment
The Fabric environment has the following settings by default.
- reject_unknown_hosts
- Always set to True, ssh connections are handled by this plugin and ploy.
- disable_known_hosts
- Always set to True, handled by ploy.
- host_string
- The unique id of the current instance, only manipulate if you know what you do!
- known_hosts
- Path to the known_hosts file managed by ploy.
- instances
- Dictionary allowing access to the other instances to get variables or call methods on.
- instance
- The current instance to access variables from the config attribute or other things and methods.
- config_base
- The directory of ploy.conf.
Any option of the instance starting with fabric- is stripped of the fabric- prefix and overwrites settings in the environment with that name.
Changelog
1.1.0 - 2014-10-27
- Require Fabric >= 1.4.0 and vastly simplify the necessary patching. [fschulze]
- Close all newly opened connections after a Fabric call. [fschulze]
- Add context manager and decorator to easily switch fabric connections. [fschulze]
1.0.0 - 2014-07-19
- Added documentation. [fschulze]]]
- Author: Florian Schulze
- License: BSD 3-Clause License
- Categories
- Package Index Owner: fschulze, tomster
- DOAP record: ploy_fabric-1.1.0.xml | https://pypi.python.org/pypi/ploy_fabric | CC-MAIN-2017-30 | refinedweb | 564 | 58.58 |
#include "num.h"
#include "util.h"
#include "scalar_8x32.h"
Go to the source code of this file.
Add two scalars together (modulo the group order).
Returns whether it overflowed.
Conditionally add a power of two to a scalar.
The result is not allowed to overflow.
Clear a scalar to prevent the leak of sensitive data.
If flag is true, set *r equal to *a; otherwise leave it.
Constant-time. Both *r and *a must be initialized.
Conditionally negate a number, in constant time.
Returns -1 if the number was negated, 1 otherwise
Compare two scalars.
Convert a scalar to a byte array.
Access bits from a scalar.
All requested bits must belong to the same 32-bit limb.
Access bits from a scalar.
Not constant time.
Convert a scalar to a number.
Compute the inverse of a scalar (modulo the group order).
Compute the inverse of a scalar (modulo the group order), without constant-time guarantee.
Check whether a scalar, considered as an nonnegative integer, is even.
Check whether a scalar is higher than the group order divided by 2.
Check whether a scalar equals one.
Check whether a scalar equals zero.
Multiply two scalars (modulo the group order).
Multiply a and b (without taking the modulus!), divide by 2**shift, and round to the nearest integer.
Shift must be at least 256.
Compute the complement of a scalar (modulo the group order).
Get the order of the group as a number.
Set a scalar from a big endian byte array.
The scalar will be reduced modulo group order
n. In: bin: pointer to a 32-byte array. Out: r: scalar to be set. overflow: non-zero if the scalar was bigger or equal to
n before reduction, zero otherwise (can be NULL).
Set a scalar from a big endian byte array and returns 1 if it is a valid seckey and 0 otherwise.
Set a scalar to an unsigned integer.
Shift a scalar right by some amount strictly between 0 and 16, returning the low bits that were shifted off.
Find r1 and r2 such that r1+r2*2^128 = k.
Find r1 and r2 such that r1+r2*lambda = k, where r1 and r2 or their negations are maximum 128 bits long (see secp256k1_ge_mul_lambda).
Compute the square of a scalar (modulo the group order). | https://doxygen.bitcoincore.org/scalar_8h.html | CC-MAIN-2021-17 | refinedweb | 386 | 79.16 |
This Java Assert Tutorial Explains all about Assertions in Java. You will learn to Enable & Disable Assertions, how to use Assertions, Assert Examples, etc:
In our earlier tutorials, we have already discussed exceptions in Java. These are the errors that are caught at runtime. Similar to exceptions there are some other constructs that we can use at compile time to test the correctness of code. These constructs are called “Assertions”.
In this tutorial, we will discuss Assertions in Java in detail. We can define an Assertion as a construct that allows us to test the correctness or clarity of assumptions that we have made in our Java program.
=> Take A Look At The Java Beginners Guide Here.
What You Will Learn:
Assertions In Java
Thus when we are executing assertion in a program, it is assumed to be true. If it becomes false or fails then JVM will throw an AssertionError.
We use assertions during development for testing purposes. At runtime, assertions are disabled by Java.
How do assertions differ from normal exceptions?
Unlike normal exceptions, Assertions are mainly useful to check the logical situations in a program about which we have doubts. Also contrary to normal exceptions that also can be thrown at run-time, assertions are disabled at run-time.
Assertions can be used in the places in the code where the developer has maximum control like they can be used as parameters to private methods. Assertions can also be used with conditional cases. Similarly, conditions at the start of any method can contain assertions.
However, assertions should not be taken as a replacement for error messages. Neither the assertions should be used in public methods, for example, to check arguments. Most importantly we should not use assertions on command-line arguments in Java.
In Java, assertions are disabled by default. So for assertions to work in a Java program, we have to first enable the assertions.
Enable Assertions In Java
To enable assertions, we have to do it from the command line.
Following is the general syntax for enabling Assertion in Java.
java –ea: arguments
or
java –enableassertions: arguments
As an example, we can enable assertions for a particular class as shown below:
java –ea TestProgram
or
java –enableassertions TestProgram
Here, TestProgram is a class for which the assertion is to be enabled.
When the condition is true in the assert statement in the program and assertions are enabled, then the program will execute normally. When the condition is false and assertions are enabled, then the program throws AssertionError and the program stops.
There are various variations for enabling assertions using the command line.
#1) java –ea
When the above command is given in the command line, then the assertions are enabled in all classes except for system classes.
#2) java –ea Main
The above command enables assertion for all classes in the Main program.
#3) java –ea TestClass Main
This command enables assertions for only one class – ‘TestClass’ in the Main program.
#4) java –ea com.packageName… Main
The above command enables assertion for package com.packageName and its sub-packages in the Main program.
#5) java –ea … Main
Enables assertion for the unnamed package in the current working directory.
#6) java –esa: arguments OR java –enablesystemassertions: arguments
The above command enables assertions for the system classes.
Disabling Assertions
We can also disable assertions through the command line.
The general syntax to disable assertions in Java is:
java –da arguments
OR
java –disableassertions arguments
Similarly to disable assertions in System classes, we use the following syntax:
java – dsa: arguments
OR
java –disablesystemassertions:arguments
“assert” Keyword In Java
Java language provides the keyword “assert” that allows developers to verify the assumptions they have made for the program or state of the program.
So we can use the “assert” keyword to provide assertions in Java to verify conditions that might otherwise prevent the program from working smoothly.
The keyword “assert” is used from Java 1.4 but remains the little known keyword in Java. When we use the assert keyword in Java, we have to do so in an Assert statement.
Assert Statement In Java
In Java, the assert statement starts with the keyword ‘asset’ followed by a Boolean expression.
The assert statement in Java can be written in two ways:
- assert expression;
- assert expression1: expression2;
In both the approaches, the expressions used with the Assert keyword are the Boolean expressions.
Consider the following statement as an example.
assert value >= 10 : “greater than 10”;
Here, the assert statement checks for a condition and if the condition is true, a message is printed. Thus we can also have assertions with our message.
How To Use Assert In Java
So far, we have discussed the assert keyword and assert statement in Java. Now, let us consider an example to demonstrate how to use assert in Java.
To add assertions, we have to simply add an assert statement as follows:
public void setup_connetion () { Connection conn = getConnection (); assert conn != null; }
We can also give the above assert differently as shown below:
public void setup_connection () { Connection conn = getConnection (); assert conn != null: “Connection is null”; }
Both the above code constructs check if the connection returns a non-null value. If it returns a null value, then JVM will throw an error – AssertionError. But in the second case, a message is provided in the assert statement so this message will be used to construct AssertionError.
In the second case with assertions enabled, the exception will look like:
Exception in thread "main" java.lang.AssertionError: Connection is null at line numbers…
Assert Example In Java
Let’s implement an example of using Assertions in Java.
public class Main { public static void main(String[] args) { try { System.out.println("Testing Assertions..."); assert true : "We don't see this."; assert false : "Visible if assertions are ON."; } catch (AssertionError e) { e.printStackTrace(); } } }
Output
The above output is given when the assertions are not enabled. If the assertion was enabled, then the second message (assert false) will be displayed.
Now let’s demonstrate another example. Note that here we have enabled the assertion in Java on our machine where we are running this program.
class Main { public static void main(String args[]) { String[] weekends = {"Friday", "Saturday", "Sunday"}; assert weekends.length == 2; System.out.println("We have " + weekends.length + " weekend days in a week"); } }
Output
As the weekend length doesn’t match the length specified in the assert statement, the above exception is thrown. If the assertion was disabled, then the program would have displayed the message specified instead of assert exception.
Why Are Assertions Used In Java?
We use assertions in our Java program to make sure that the assumptions we have made in our program are correct.
For example, if we want to make sure that the code that seems to be unreachable is indeed unreachable. Or we want to make sure that any variable has a value in a specified range.
When we make such an assumption, we provide assertions to make sure that they are indeed correct.
Frequently Asked Questions
Q #1) Does assert throw an exception Java?
Answer: Assert usually throws “AssertionError” when the assumption made is wrong. AssertionError extends from Error class (that ultimately extends from Throwable).
Q #2) What happens when an assert fails in Java?
Answer: If assertions are enabled for the program in which the assertion fails, then it will throw AssertionError.
Q #3) What does an assert return in Java?
Answer: An assert statement declares a Boolean condition that is expected to occur in a program. If this Boolean condition evaluates to false, then an AssertionError is given at runtime provided the assertion is enabled.
If the assumption is correct, then the Boolean condition will return true.
Q #4) Can we catch the assertion error?
Answer: The AssertionError thrown by the assert statement is an unchecked exception that extends the Error class. Thus assertions are not required to declare them explicitly and also there is no need to try or catch them.
Q #5) How do you assert an exception?
Answer: To assert an exception we declare an object of ExpectedException as follows:
public ExpectedException exception = ExpectedException. none ();
Then we use it’s expected () and expect message () methods in the Test method, to assert the exception, and give the exception message.
Conclusion
With this, we have concluded this tutorial on assertions in Java. We have discussed the definition and purpose of assertions in Java. To use assertion in Java program we have to first enable them to use the command line.
We explored the various ways using which we can enable assertions at the program level, package level, directory level, etc. Assert keyword and assert statements in Java and their detailed syntax with programming examples was discussed. The assert keyword and asset statements help us to use assertions.
We saw that an AssertionError is given when an assertion fails. Assertions in Java are mostly used at compile time and they are by default disabled at runtime.
Furthermore, assertions are mostly used in the JUnit framework of Java in which we write the test cases to test applications.
=> Read Through The Easy Java Training Series. | https://www.softwaretestinghelp.com/assertions-in-java/ | CC-MAIN-2021-17 | refinedweb | 1,523 | 56.25 |
Python List Regex
I have a list from a stock web scraper looking like this: [......', 'xlnx>XLNX<', 'yhoo>YHOO<']
how can I get the dictionary with only the quotes? I know this is simple but I could use some help. Thanks
import urllib import re base_url = '' content = urllib.urlopen(base_url).read() list = re.findall('(.*)/a>', content) print list
Answers
You have a list, not a dictionary. Also you shouldn't name your variable list as it is the name of a built-in.
>>> content ['xlnx>XLNX<', 'yhoo>YHOO<'] >>> tickers = [] >>> for s in content: ... tickers.append(''.join(i for i in s if i.isupper())) ... >>> tickers ['XLNX', 'YHOO']
Need Your Help
Should my PHP functions accept an array of arguments or should I explicitly request arguments?
socket.send working only once in python code for an echo client
python sockets network-programmingI have the following code for an echo client that sends data to an echo server using socket connection: | http://unixresources.net/faq/12333628.shtml | CC-MAIN-2019-13 | refinedweb | 159 | 66.84 |
Hi, I’m Jane. Everyone I know spends their free time browsing the internet… whether it’s catching up on the news, reading friends’ blog, or looking for that perfect web deal, book, person. But scanning a site to see what you’ve read versus what’s new can be tiring. And it’s frustrating to find that there’s nothing new to read after all that work. With the IE7 Beta 2 Preview, we added a convenient way interacting with the internet: Subscribing to feeds.
Feeds are a different format of the website’s content that allows software to determine if there is something new available. It can range from a new article on msnbc.com, a new movie release on Netflix, or a new journal entry on a friend’s blog. With IE7 Beta 2 Preview, you can subscribe to your favorite websites’ feed and read new updates directly in the browser.
1. Feed Discovery Button – The Feed Discovery button tells you if there is a feed detected on the webpage you’re looking at. It lives on the Command Bar and lights up when a feed is found. Clicking on it takes you to the Feed Reading Page.
2. Feed Reading Page – This is the view of the feed for reading. When you subscribe to a feed, you can determine the new content versus the content that you’ve seen before. We also have controls for inline search, sorting, and filtering to quickly get to the content that is interesting to you.
3. Feed list – The list of feeds that are you subscribed sits next to your favorites. A feed is bold if there is new content available for you.
There are 4 parts to the feed reading experience: discovering, subscribing, reading, and managing. If you want to find more, read the next two posts and subscribe to the Team RSS blog.
Part 2: Discovery and Subscribe
– Jane
Very nice. I have been playing around with the subscriptions and just recently exported my OPML file from SharpReader and imported into IE7 without a hitch!
I also posted on flickr a shot of the RSS feeds view, after clicking on it. It renders very nicely!
Heres to a slick preview! well done.
quick question about the feeds in IE7… will we be able to edit/mod/create our own "views" for displaying the feeds in IE, such as will custom XSLT styles and the like?
just curious 😉
enough about rss please! is there nothing more important in ie7b2?!?!
Dymonaz,
You’ll have to keep watching the blog. I’m sure something will show up soon that will fulfill your expectation.
– Al Billings [MSFT]
Add "title" attributes to your images when posting. This isn’t the 1998 Internet anymore!
IE7 is supposed to be promoting Web Standards!
Yeeesh!
Why not expand the rss bookmarks in the box and allow drop down in the toolbar? This makes scanning the contents much faster
I love how the Favorite center works, with separeted bookmarks and feeds. Hope to see the + button and home button integrated into it for space saving.
But I wonder why the RSS button isnt in the addressbar like FireFox and Opera have it? Seems like a better place instead of taking up space from the tabs.
Also, will it be possible to move the buttons (home rss tools etc) to another toolbar in the final version?
probably another stupid question… but when i subscribe to an RSS feed in IE7B2, and go into the favorites, click on Feeds and select one… does it simply load the linked feed in the active tab for a person to view?
or does it retain the posts, download them in the background, allowing subscriptions to be archived and searched against?
/puts away curious hat
The first time a user visits a website with a feed available, a dialog box should pop up saying something like:
"This website has a feed available to let you know when it is updated. You can access this by clicking…"
As things stand, I can see lots of users being completely oblivious to this feature because they don’t tend to go clicking around the interface when they are trying to read a page.
It’s okay but it would be great with some minor changes.
1) For feeds, allow me to read folders with many feeds all at once, specifically, allow me to see all unread feeds. THIS IS CRUCIAL!
2) Allow me to move between different feeds while in feed view, not by selecting a new feed through favourites center.
3) If haven’t tested this thoroughly, but please allow for pictures in feeds, it makes them alot better!
Thanks if you have feedback, or do anything about these issues.
I am very impressed with the way WebFeeds are parsed and made easy to read and subscribe to but I think the UI of the Favorites Center is seriously flawed.
Having separate folders for Favorites and Feeds is an interesting idea but actually trying to begin to work with separate sets of folders quickly made it possible for me to conclude that it was not such a good idea after all.
As implemented, you have introduced redundancy in the UI. You have now required people to create and manage two separate trees of directory resources with no way to borrow names and structure from one another so as to avoid yet more redundancy.
Information glut is information glut and as implemented the Favorites Center does little to improve on a most serious information management concern.
Each directory in the tree has to be named somehow. Its difficult enough for any of us to create a well thought out taxonomy. Worse yet for two taxonomies which are used to classify and manage essentially the same thing; a URI.
There’s no direct search for Favorites and Feeds in IE either. I can’t tell you how many times I’ve need to find which directory I’ve stored a Favorite in simply because of the complexity of creating and managing a taxonomy. At least Windows Desktop Search comes to the rescue but it can be a distraction to go elsewhere to get something done.
I would have paid special attention to this if I were on the dev team. As so much noise has been made about improving the user experience I was surprised to observe you’ve replicated the same lame implementation for creating and managing the lame implementation by two.
On a final note, I also observed that IE7 does not display the XML of a feed in a tree anymore. I’ve always found it useful to read the tree as it was useful for copy and paste operations but now when viewing source for a feed we get unformatted serialized text.
"Why not expand the rss bookmarks in the box and allow drop down in the toolbar? This makes scanning the contents much faster"
I agree. I’d rather scan feed Headlines in the browser than on a webpage. It’s quicker and easier to scan through on a whim than having to open a webpage to read extra large text. At least have it as an option "Read Feed Headlines in Browser" or "Read Feed Headlines on Webpage Format".
Who cares if some FireFoxer or Mac person says you’re copying. You’re catching up, so you’re going to copy things. What’s msot important is giving people flexibility with these new things with an array of options.
BEFORE I FORGET… Feeds from my my website will not update in IE 7, but they update fine in FireFox and Maxthon… Is there something extra I have to add to the code for IE 7 to read these?
How secure is IE7 compared to Firefox 1.5? can anybody comment? . Please post on my page.. if you can..
Is there anyway in which IE 7 can read the feeds in the exact order I put them in my XML document? I put them in a specific order to be read in that order and haven’t come across anyway in which they be shown in that exact order. FireFox and Maxthon do this by default. I was wondering if there was something I was missing.
Typo:
"we added a convenient way interacting with the internet"
I think I found a "feature" of the RSS Feeds that I can’t quite explain, it seems that building web pages under ASP.NET 2.0 using master pages, placing the rss link tag in the master page does not enable the rss icon on the toolbar. I have tested the link in a static html file and it works but not when embeded in the master page. Anyone have any ideas? I have the link on my site if anyone wants to check it out and see for themselves.
– Will
I am unable to subscribe to any feed on IE 7 at home. I get "Unknown feed error" when I try. Not a very descriptive error message. On a machine at work, I can subscribe to feeds with no problem. Any debugging thoughts would be approeciated.
At long last, Microsoft’s giving users an RSS reader in Internet Explorer 7. The recently released preview of Beta 2 has a fairly polished implementation of it, and there’s an excellent post on Microsoft’s IE Blog about it, complete with…
Nice Feature, but how can I, for example, refresh all subscriptions in OneClick?
So, If I want to refresh all subscriptions — i must click on all ones and Press Refresh
Not good
The feeds section definately requires a sync or refresh function for the entire tree. I have over 50 feeds in my tree that requires each one to be right clicked on and refreshed. Interestingly enough, when I imported the OPML from feeddemon, the links all auto-refreshed.
Also with the feeds, a number of the new items next to the feed title would be great, as well as the ability to select specific items on the feed as read rather than changing the status of the feed by simply viewing it, but they are nice to haves. The fact that I can see the feeds using this type of function is way ahead of where IE6 was.
PingBack from
can anyone read the feed ??
I don’t think that just bolding a feed when it has new info is enough.
How about a "sparkle" icon next to the feed (as well as making it bold) when there’s been new stuff added?
I have a few problems using the rss functionality.
First, when a page begins loading, the rss button lights up, as if it has discovered a feed, whereas it really hasnt, and there are no feeds or links to feeds on that page.
Second, the search box that comes on the rss reading page desperately needs a hide button. It gets on top of the wide images in some of the posts! if you really want to repro the problem on *any* feed, simply zoom to, say, 500% and you will know.
Other than that, great functionality. Please add the refresh all feeds button though.
Thanks for reading this
I was wondering if ie 7 could include a new rss feed update in the task bar area where your clock and windows messenger appears (sorry forgot the name of the area). It could use the rss button and have a bubble box appear when info was availible from an rss feed.
It is sometimes useful to view RSS feeds in their XML format the way IE6 did. While the view that IE7 offers is pretty, I wish there were a quick way for me to choose to view the RSS the IE6 way.
We have to stop all these gradients, Microsoft — this is getting out of hand. You do not need to use 4+ color palletes for your application designs, and white space is an important element of design; there’s no need to fuddle it with gradients. That’s a rookie designer trick because their afraid of negative space — but it kills their experience in the end. How many times do I have to point out your poor design over the years?
Stop letting middle management and developers design, free your talent or hire professionals. It’s not that complex. This application is growing more and more an eye sore everyday.
I’m testing an (unfortunately private) feed setup, and while the feeds seem to validate, IE7 refuses to render them.
Must feeds have the .xml or .rdf file extension?
PingBack from
Well, I’m checking out IE7b2 and I’m glad to see some of the improvements. The encorporation of rss feeds is nice, but sadly IMNSHO totally worthless, just like Firefox/etc.’s Livebookmarks implementation.
I really would recommend that you guys try to ape the Safari implementation of RSS notification, particularly in the bookmarks bar so that you can see your feeds grouped into folders and a # of new articles, e.g.:
MSIEBlog (5)
to indicate there are 5 unread articles in that feed.
Similarly, in the feed -view- it helps immensely within Safari to check the "Show unread feeds in different colour" this way you can scroll down just as far as you need to and ignore previously read feeds.
Simply polling to see if a site has feeds, but not providing the user any direct notification of what feed or how many articles are unread, and similarly not providing the user with a distinction between read and unread articles, IMNSHO makes feeds as currently implemented into IE7b2, pretty worthless, just as Firefox/Moz/etc. livebookmarks is to me.
Sticking it into the browser is -great-, but doing a complete barebones implementation, when a few minor tweaks make it useful is unfortunate.
Unless I’m missing something, but so far I can’t seem to find any acceptably usable feed views or notification/differentiation mechanisms.
I prefer the way RSS is implemented in FF I can simply look in my bookmarks and see all the topics for the feed I have subscribed to. With IE7 I have no idea what topics are current without loading the feed.
I cannot seem to use this feature. everytime I click on the orange RSS icon All I ever get is the following error message.
"Internet Explorer cannot display this feed"
Any ideas as to what I am doing wrong?
PingBack from.
Oops. Please read as following:
…!
…
The Feeds Discovery Button in IE7 takes the form of a toolbar button on the Command Bar that’s there all the time. Why??? That doesn’t make sense at all! You’re only going to need something like that when the browser detects RSS feeds on a web site, so it doesn’t need to be there 24/7. It ends up taking valuable real estate.
If the Feeds Discovery Button should be anywhere, it should be within the address bar. Specifically, at the left end of it. And it should only appear when needed (i.e. when IE7 detects RSS feeds on a web site). It makes more sense that way.
I agree with some of the people with the proposed option of a view where you could view all unread.
It would be nice if i could organize my feeds by a topic (such as IE7, or ASP.NET) and then view/search all of my unread items for the entire folder (which comprises several feeds).
Something similar to RSS Bandit’s interface would work great.
What is IE7’s criteria for a valid RSS feed?
I had a simple RSS2 feed that worked in firefox but not recognized in IE7.
does it require definition of some obscure namespace?
any tech docs I can refer to?
hi forgetfoo –
stylesheets: we currently do not support customizing feed stylesheets.
subscribed feeds: when you subscribe to a feed, background sync is started for the feed and keeps the last 200 items for a feed (you can change the # of items for a given feed through the properties dialog). when you select it in the feed list, you are a seeing a collection of new items and the items that you’ve seen before.
– jane kim [ MSFT]
The default feed refresh interval is set to 1 day. 24 hours seems to be a long time for many of the feeds I like. Is there a way to change the global setting so that all feeds are added at a user perferred interval. Or, could you please add a Feed property page to Tools for management and properties. Right mouse clicking each feed is hard. 🙁
Thanks
It is snowing outside, I have a cup of coffee playing with new IE7! I have installed yesterday. It has…
I would love for the abilities in reading RSS to be like reading mail in outlook, so for example:
1) be able to mark a feed (ex/ Internet Explorer Team Blog) read or unread
2) flag a news piece for priority
3) auto view ability by hitting header
This is great thanks.
MrDale –
By default, the items within a feed are ordered by the publish time provided by the publisher. I think you are running into a situation where the publish time is not defined.
We plan on changing to filter to just the unread items in the future.
– Jane Kim [MSFT]
Alexander –
When there are new items to read in your feed list, the feed view button within the favorites menu display a gleam.
– Jane Kim [MSFT]
Sushovan –
Your first issue with the feed button lighting before the page is fully loaded is a known issue and will be fixed.
Your second issue of zoom not working properly with the feed controls is also a known issue.
thanks for using the product!
– Jane Kim [MSFT]
Alex –
could you provide the url to the bank’s login screen on:
thanks! – Jane Kim [MSFT]
Keith Combs –
I hear you on this. We are implementing a global setting to change the feed’s sync setting easily from the Feed Settings dialog.
– Jane Kim [MSFT]
Are there any plans to go away from using RunDLL to access the internet when updating feeds? I posted this on an earlier comment page, but since this directly addresses feeds, I thought I’d post it here too.
The problem: ie7 is using rundll to access the internet and retrieve feed updates. Because rundll does not identify the caller, those of us using a software firewall see only rundll attempting to access the internet. It doesn’t tell us who is trying to run it or necessarily where it’s going. This could be a MAJOR security hole because rundll can be run indescriminately by any application (good or evil) on your computer. By allowing rundll unfettered access to the internet, you’re basically inviting anyone to use it as a bridge to excute potentially nefarious code. Since IE7 is using it all the time (it seems to try to run more frequently the more feeds you have), it becomes a calculated risk every time I decide to allow it out. The first few times it ran, I ran a virus checker to make sure someone hadn’t infiltrated my machine. This could all be handled easily if IE7 ran the dll directly or shipped with a FeedExec application so at least we know what’s going on. Sure, users like me would notice an upsurge in the number of times it hits the net, but we’d know it could be trusted to not be some hijacker.
Any plans to change this before the release?
For some reason, the RSS reader has, more or less, totally malfunctioned in IE7 Beta 2. All my RSS feeds could be read when I first started using this browser. Now? Most of the links aren’t displaying properly at all!
This is for me! By the time you read this message, I’ll have uninstalled IE7 Beta 2 and have gone back to IE6. I’ve had it with these dumb bugs! See ya
Jane,
Unfortunately, such pages are available right after login, not before. 🙁
Can I have someone to contact me about the problem, so we could discuss means to achieve the pages in private? For known reasons I cannot post my bank details right here.
Please email me on alex @ bytegems . com
Thanks!
Is there a way to sync feeds using the Windows Live Favorites feature. It would be great to simply sync feeds used during th day to other machines that you use throughout the day. Thanks
PingBack from
If you go to i.e. you notice at the top right:
Displaying 100 / 100
Although there are way more than a 100 items.
Hello Jane,
I’ve got XML this bank’s site response with. It’s RSS + XSLT. IE7 fails to show it rendered.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="news.xsl"?>
<rss version="2.0" xmlns:
<support/>
<version buildNum="610" buildDate="Wed Feb 08 19:01:43 EET 2006"/>
<logged sessioncount="606" visitscount="1"/>
<locale language="ru">
<date id="20060209T16:57:41" traditional="09.02.2006">09 фев 2006,Чт 16:57:41</date>
</locale>
//etc.
To whom I can forward it?
Winpooch sez:
The following process:
..system32rundll32.exe (1788)
Is trying to do this:
File::Write (..TasksSystem_Feed_Sync_Scheduler.job)
I agress with Simon: archive…418.aspx#526941
I love the feature. One thing that annoys me to no end is this, though:
– open a feed from your favorites
– scroll down a few page fulls to a post you like
– click on a link (this opens the link in the same page and replaces the feed)
– you read the page and then click the ‘back’ button to go back to the feed
You would expect to be back to the same location in the feed page. Instead, you’re taken to the top of the feed forcing you to find where exactly you were on that page.
Feed discovery seams to be broken when the page is loaded in a frame. When the page is loaded in the top frame it works fine.
If I had an optional viewer pane splitting my feed window into upper and lower halfs, it could really serve the purpose of the large window. All links would need a rewrite to point to the main tabbed area, but it would be easier to navigate.
PingBack from
PingBack from
PingBack from
free myspace music song codes videos
PingBack from
PingBack from
PingBack from
PingBack from
PingBack from
PingBack from | https://blogs.msdn.microsoft.com/ie/2006/02/02/part-1-hello-feeds/ | CC-MAIN-2017-13 | refinedweb | 3,785 | 71.34 |
iPortalCallback Struct Reference
[Crystal Space 3D Engine]
When a sector is missing this callback will be called. More...
#include <iengine/portal.h>
Inheritance diagram for iPortalCallback:
Detailed Description
When a sector is missing this callback will be called.
If this callback returns false then this portal will not be traversed. Otherwise this callback has to set up the destination sector and return true. The given context will be either an instance of iRenderView or else 0.
This callback is used by:
Definition at line 131 of file portal.h.
Member Function Documentation
Traverse to the portal.
It is safe to delete this callback in this function.
The documentation for this struct was generated from the following file:
Generated for Crystal Space 2.0 by doxygen 1.6.1 | http://www.crystalspace3d.org/docs/online/new0/structiPortalCallback.html | CC-MAIN-2015-11 | refinedweb | 128 | 59.09 |
NAME
INIT CLUSTER - Initialize Slony-I cluster
SYNOPSIS
INIT CLUSTER [ID = integer] [COMMENT = 'string']
DESCRIPTION
Initialize the first node in a new Slony-I replication cluster. The initialization process consists of creating the cluster namespace, loading all the base tables, functions, procedures and initializing the node, using “schemadocinitializelocalnode(integer, text)” [not available as a man page] and “schemadocenablenode(integer)” [not available as a man page]. ID The unique, numeric ID number of the node. COMMENT = 'comment text' A descriptive text added to the node entry in the table “sl_node” [not available as a man page]. For this process to work, the SQL scripts of the Slony-I system must be installed on the DBA workstation (the computer currently executing the slonik utility), while on the system where the node database is running the shared objects of the Slony-I system must be installed in the PostgreSQL library directory. Also the procedural language PL/pgSQL is assumed to already be installed in the target database.
EXAMPLE
INIT ‘blow up’ past the typical maximum name length of 63 characters.
LOCKING BEHAVIOUR
This command creates a new namespace and configures tables therein; no public objects should be locked during the duration of this.
VERSION INFORMATION
This command was introduced in Slony-I 1.0 3 December 2011 SLONIK INIT CLUSTER(7) | http://manpages.ubuntu.com/manpages/precise/en/man7/SLONIK_INIT_CLUSTER.7.html | CC-MAIN-2016-36 | refinedweb | 218 | 50.36 |
A recent project I have been working on lead me to using BitBucket for source code management. I mainly used Subversion in the past and know how to use that over a distributed system. BitBucket has a very nice REST API, and I thought of how to take advantage of this API to enable issues to be created. Beyond that, I wanted issues to be created automatically when an issue occurs in one of my Django applications.
I have already begun developing the API and logging.Handler sub-class to work with BitBucket. The source code is public and available on my BitBucket under the project Python BitBucket API. Have a look and let me know what you think of it so far. I am trying to create a Pythonic API, whereas each BitBucket object is a Python object, which can be saved back and edited via it's properties. A concept similar to Django models. Here is an example of how to create a new issue using this:
from api import API api = API("kveroneau", "**password**") issue = api.new_issue("kveroneau", "python-bitbucket") issue.title = "Testing Python API" issue.content = "Hello World!\nLine 2" json = issue.save()
Every property available on bitbucket for an issue is available as an attribute on this Issue object, so you can set everything from the Milestone to the Priority. Here is how you can read in all the issues on your project:
from api import API api = API("kveroneau", "**password**") issues = api.get_issues("kveroneau", "python-bitbucket") for issue in issues: print "Issue title: %s" % issue.title print "Issue priority: %s" % issue.priority print "Issue content:\n%s\n\n" % issue.content
See, very simple, straightforward, and most of all, easy to understand. This is how all Pythonic APIs should be. Leave any comments below on what you think of this API, and please download a copy of api.py and take it for a spin. | http://pythondiary.com/blog/Aug.09,2012/working-bitbucket-api.html | CC-MAIN-2016-26 | refinedweb | 321 | 67.35 |
QML elements over device's status bar
I am facing a problem when the device's keyboard is shown. The elements go over the device's status bar as in the images.
I have already tried to use the
Flickabletype but it does not work. Every time the keyboard appears, it push the app elements over the status bar.
PS: The problem occurs in both Android and iOS.
Here is the code:
import QtQuick 2.4 import QtQuick.Window 2.2 import QtQuick.Controls 1.3 Window { visible: true property int larguraTela: 360 property int alturaTela: 640 width: larguraTela height: alturaTela maximumWidth: larguraTela maximumHeight: alturaTela minimumWidth: larguraTela minimumHeight: alturaTela title: "OverStatusBar" Rectangle{ id: retangulo1 width: parent.width height: parent.height * 0.5 anchors.top: parent.top color: "grey" } Rectangle{ id: retangulo2 width: parent.width height: parent.height * 0.5 anchors.top: retangulo1.bottom color: "lightgrey" TextField { id: campoTexto width: parent.width * 0.7 height: parent.height * 0.15 anchors.centerIn: parent inputMethodHints: Qt.ImhDigitsOnly } } }
Hi,
What version of Qt are you currently using ?
Since 5.6 beta is out, can you try with it to see if it's still happening ?
Any another ideas how to fix it?
Hello @SGaist . @Deis-K and I have tried with Qt 5.6 beta, but the problem is not solved. Any other suggestion about how this issue could be solved?
Which version of iOS and Android did you test on ?
Did you check the bug report system to see if it's something known ?
iOS 9.2
Android 19 and 22
No, I didn't check the bug report but @Deis-K sent it as a bug and it was accepted.
Can you share the link ? So other people finding this thread can easily find it.
Here is the link
Thanks ! | https://forum.qt.io/topic/61890/qml-elements-over-device-s-status-bar | CC-MAIN-2018-39 | refinedweb | 298 | 69.89 |
Tax
Have a Tax Question? Ask a Tax Expert
Hi and thanks for asking for me today.
In a strictly financial sense, the trade-off is a 4.25% rate for borrowing money (which can go up after you rfirst 5 years) versus what you can earn on your investments.
Keep in mind that interest paid is about $3400 a year currently, and may not be enough to make a difference in itemized deductions at tax time, so the interest is not offset by any (or much) tax savings.
With that in mind, can you get a "safe" return of 4.25% or better now? Probably not. CDs are lucky to be paying 0.5% Other investments may likely fare better, but right now it's a big question as to what risk you would need to undetake to get at least a 5% return (before taxes) to yield at least a 4.25% return.
On the other hand, if you feel you can use that inheritance to leverage an investment (for example, a rental property), then you may be better off investing as much as you can and using the income to help pay your mortgage.
In this case, I would say you have your choice based on your comfort of investing that $81K in something other than your mortgage, or getting rid of that montly obligation. My general advice is that a mortgage is fine as long as your income supports the monthly payments without being a burden. If you were to lose your job tomorrow, you still have enough cash to keep making payments as long as needed.
There are basically two good uses of debt: Use it to buy something that increases in value or to purchase and live in your home. Any other debt is dangerous and should be avoided. | http://www.justanswer.com/tax/76xnc-will-inheriting-400-000-soon-48-single.html | CC-MAIN-2016-26 | refinedweb | 305 | 76.66 |
#include <deal.II/grid/tria_accessor.h>
This class allows access to a cell: a line in one dimension, a quad in two dimension, etc.
The.
Definition at line 2667 of file tria_accessor.h.
Propagate the AccessorData type into the present class.
Definition at line 2673 of file tria_accessor.h.
Define the type of the container this is part of.
Definition at line 2678 of file tria_accessor.h.
Constructor.
Copy 3683 of file tria_accessor.h.
Another conversion operator between objects that don't make sense, just like the previous one.
Definition at line 3713.
Return a pointer to the
ith child. Overloaded version which returns a more reasonable iterator class.
Return an iterator to the
ith face of this cell.
Return the face number of
face on the current cell. This is the inverse function of TriaAccessor::face().
Return an array of iterators to all faces of this cell.
Return the (global) index of the
ith face of this cell..
Definition at line 2898 of file tria_accessor.cc.
Return a pointer to the
ith neighbor. If the neighbor does not exist, i.e., if the
ith face of the current object is at the boundary, then an invalid iterator is returned.
The neighbor of a cell has at most the same level as this cell. For example, consider the following situation:
Here, if you are on the top right cell and you ask for its left neighbor (which is, according to the conventions spelled out in the GeometryInfo class, its zeroth neighbor), then you will get the mother cell of the four small cells at the top left. In other words, the cell you get as neighbor has the same refinement level as the one you're on right now (the top right one) and it may have children.
On the other hand, if you were at the top right cell of the four small cells at the top left, and you asked for the right neighbor (which is associated with index
i=1), then you would get the large cell at the top right which in this case has a lower refinement level and no children of its own..
Definition at line 2341 of file tria_accessor.cc..
Definition at line 2355 of file tria_accessor.cc..
Definition at line 2366 of file tria_accessor.cc.
This function is a generalization of the
neighbor_of_neighbor and the
neighbor_of_coarser_neighbor functions. It checks whether the neighbor is coarser or not and calls the respective function. In both cases, only the face_no is returned.
Compatibility interface with DoFCellAccessor. Always returns
false.
If the cell has a periodic neighbor at its
ith face, this function returns true, otherwise, the returned value is false.
Definition at line 2542 of file tria_accessor.cc.
For a cell with its
ith face at a periodic boundary, see the entry for periodic boundaries, this function returns an iterator to the cell on the other side of the periodic boundary. If there is no periodic boundary at the
ith face, an exception will be thrown. In order to avoid running into an exception, check the result of has_periodic_neighbor() for the
ith face prior to using this function. The behavior of periodic_neighbor() is similar to neighbor(), in the sense that the returned cell has at most the same level of refinement as the current cell. On distributed meshes, by calling Triangulation::add_periodicity(), we can make sure that the element on the other side of the periodic boundary exists in this rank as a ghost cell or a locally owned cell.
Definition at line 2582 of file tria_accessor.cc.
For a cell whose
ith face is not at a boundary, this function returns the same result as neighbor(). If the
ith face is at a periodic boundary this function returns the same result as periodic_neighbor(). If neither of the aforementioned conditions are met, i.e. the
ith face is on a nonperiodic boundary, an exception will be thrown.
Definition at line 2611 of file tria_accessor.cc.
Return an iterator to the periodic neighbor of the cell at a given face and subface number. The general guidelines for using this function is similar to the function neighbor_child_on_subface(). The implementation of this function is consistent with periodic_neighbor_of_coarser_periodic_neighbor(). For instance, assume that we are sitting on a cell named
cell1, whose neighbor behind the
ith face is one level coarser. Let us name this coarser neighbor
cell2. Then, by calling periodic_neighbor_of_coarser_periodic_neighbor(), from
cell1, we get a
face_num and a
subface_num. Now, if we call periodic_neighbor_child_on_subface() from cell2, with the above face_num and subface_num, we get an iterator to
cell1.
Definition at line 2628 of file tria_accessor.cc.
This function is a generalization of periodic_neighbor_of_periodic_neighbor() for those cells which have a coarser periodic neighbor. The returned pair of numbers can be used in periodic_neighbor_child_on_subface() to get back to the current cell. In other words, the following assertion should be true, for a cell with coarser periodic neighbor: cell->periodic_neighbor(i)->periodic_neighbor_child_on_subface(face_no, subface_no)==cell
Definition at line 2682 of file tria_accessor.cc.
This function returns the index of the periodic neighbor at the
ith face of the current cell. If there is no periodic neighbor at the given face, the returned value is -1.
Definition at line 2747 of file tria_accessor.cc.
This function returns the level of the periodic neighbor at the
ith face of the current cell. If there is no periodic neighbor at the given face, the returned value is -1.
Definition at line 2757 of file tria_accessor.cc.
For a cell with a periodic neighbor at its
ith face, this function returns the face number of that periodic neighbor such that the current cell is the periodic neighbor of that neighbor. In other words the following assertion holds for those cells which have a periodic neighbor with the same or a higher level of refinement as the current cell:
{cell->periodic_neighbor(i)-> periodic_neighbor(cell->periodic_neighbor_of_periodic_neighbor(i))==cell} For the cells with a coarser periodic neighbor, one should use periodic_neighbor_of_coarser_periodic_neighbor() and periodic_neighbor_child_on_subface() to get back to the current cell.
Definition at line 2767 of file tria_accessor.cc.
If a cell has a periodic neighbor at its
ith face, this function returns the face number of the periodic neighbor, which is connected to the
ith face of this cell.
Definition at line 2777 of file tria_accessor.cc.
This function returns true if the element on the other side of the periodic boundary is coarser and returns false otherwise. The implementation allows this function to work in the case of anisotropic refinement.
Definition at line 2810 of file tria_accessor.cc.
Return whether the
ith vertex or face (depending on the dimension) is part of the boundary. This is true, if the
ith neighbor does not exist.
Definition at line 2868 of file tria_accessor.cc..
Definition at line 1997 of file tria_accessor.cc..
Definition at line 2880 of file tria_accessor.cc.
Return the
RefinementCase<dim> this cell was flagged to be refined with. The return value of this function can be compared to a bool to check if this cell is flagged for any kind of refinement. For example, if you have previously called cell->set_refine_flag() for a cell, then you will enter the 'if' block in the following snippet:
Flag the cell pointed to for refinement. This function is only allowed for active cells. Keeping the default value for
ref_case will mark this cell for isotropic refinement.
If you choose anisotropic refinement, for example by passing as argument..
Return the material id of this cell.
For a typical use of this function, see the step-28 tutorial program.
See the glossary for more information.
Definition at line 2019 of file tria_accessor.cc.
Set the material id of this cell.
For a typical use of this function, see the step-28 tutorial program.
See the glossary for more information.
Definition at line 2031 of file tria_accessor.cc.
Set the material id of this cell and all its children (and grand- children, and so on) to the given value.
See the glossary for more information.
Definition at line 2045 of file tria_accessor.cc.
Return the subdomain id of this cell.
See the glossary for more information.
Set the subdomain id of this cell.
See the glossary for more information. This function should not be called if you use a parallel::distributed::Triangulation object.
Definition at line 2059 of file tria_accessor.cc.
Get the level subdomain id of this cell. This is used for parallel multigrid where not only the global mesh (consisting of the active cells) is partitioned among processors, but also the individual levels of the hierarchy of recursively refined cells that make up the mesh. In other words, the level subdomain id is a property that is also defined for non-active cells if a multigrid hierarchy is used.
Definition at line 2073 of file tria_accessor.cc.
Set the level subdomain id of this cell. This is used for parallel multigrid.
Definition at line 2084 of file tria_accessor.cc.
Set the subdomain id of this cell (if it is active) or all its terminal children (and grand-children, and so on, as long as they have no children of their own) to the given value. Since the subdomain id is a concept that is only defined for cells that are active (i.e., have no children of their own), this function only sets the subdomain ids for all children and grand children of this cell that are actually active, skipping intermediate child cells.
See the glossary for more information. This function should not be called if you use a parallel::distributed::Triangulation object since there the subdomain id is implicitly defined by which processor you're on.
Definition at line 2191 of file tria_accessor.cc.
Return the orientation of this cell.
For the meaning of this flag, see GlossDirectionFlag.
Definition at line 2095 of file tria_accessor.cc.
Return the how many-th active cell the current cell is (assuming the current cell is indeed active). This is useful, for example, if you are accessing the elements of a vector with as many entries as there are active cells. Such vectors are used for estimating the error on each cell of a triangulation, for specifying refinement criteria passed to the functions in GridRefinement, and for generating cell-wise output.
The function throws an exception if the current cell is not active.
Definition at line 2166 of file tria_accessor.cc.
Return the index of the parent of this cell within the level of the triangulation to which the parent cell belongs. The level of the parent is of course one lower than that of the present cell. If the parent does not exist (i.e., if the object is at the coarsest level of the mesh hierarchy), an exception is generated.
Definition at line 2151 of file tria_accessor.cc.
Return an iterator to the parent. If the parent does not exist (i.e., if the object is at the coarsest level of the mesh hierarchy), an exception is generated.
Definition at line 2177 of file tria_accessor.cc.
Return whether this cell is owned by the current processor or is owned by another processor. The function always returns true if applied to an object of type Triangulation, but may yield false if the triangulation is of type parallel::distributed::Triangulation.
See the glossary and the Parallel computing with multiple processors using distributed memory module for more information.
!is_ghost() && !is_artificial().
Return true if either the Triangulation is not distributed or if level_subdomain_id() is equal to the id of the current processor.
Return whether this cell exists in the global mesh but (i) is owned by another processor, i.e. has a subdomain_id different from the one the current processor owns and (ii) is adjacent to a cell owned by the current processor.
This function only makes sense if the triangulation used is of kind parallel::distributed::Triangulation. In all other cases, the returned value is always false.
See the glossary and the Parallel computing with multiple processors using distributed memory module for more information.
!is_locally_owned() && !is_artificial().
Return whether this cell is artificial, i.e. it isn't one of the cells owned by the current processor, and it also doesn't border on one. As a consequence, it exists in the mesh to ensure that each processor has all coarse mesh cells and that the 2:1 ratio of neighboring cells is maintained, but it is not one of the cells we should work on on the current processor. In particular, there is no guarantee that this cell isn't, in fact, further refined on one of the other processors.
This function only makes sense if the triangulation used is of kind parallel::distributed::Triangulation. In all other cases, the returned value is always false.
See the glossary and the Parallel computing with multiple processors using distributed memory module for more information.
!is_ghost() && !is_locally_owned()..
In case of codim>0, the point is first projected to the manifold where the cell is embedded and then check if this projection is inside the cell.
Set the neighbor
i of this cell to the cell pointed to by
pointer.
This function shouldn't really be public (but needs to for various reasons in order not to make a long list of functions friends): it modifies internal data structures and may leave things. Do not use it from application codes.
Definition at line 2205 of file tria_accessor.cc.
Return a unique ID for the current cell. This ID is constructed from the path in the hierarchy from the coarse father cell and works correctly in parallel computations using objects of type parallel::distributed::Triangulation. This function is therefore useful in providing a unique identifier for cells (active or not) that also works for parallel triangulations. See the documentation of the CellId class for more information.
Definition at line 2235 of file tria_accessor.cc.-coarser neighbors.
Definition at line 2276 of file tria_accessor.cc.
As for any codim>0 we can use a similar code and c++ does not allow partial templates. we use this auxiliary function that is then called from point_inside.
Definition at line 1958 of file tria_accessor.cc.
Set the active cell index of a cell. This is done at the end of refinement.
Definition at line 2126 of file tria_accessor.cc.
Set the parent of a cell.
Definition at line 2139 of file tria_accessor.cc.
Set the orientation of this cell.
For the meaning of this flag, see GlossDirectionFlag.
Definition at line 2109 of file tria_accessor.cc.
Definition at line 1824 of file tria_accessor.cc.
Definition at line 1837 of file tria_accessor.cc.
Definition at line 1899 of file tria_accessor.cc.
Definition at line 1972 of file tria_accessor.cc.
Definition at line 1980 of file tria_accessor.cc.
Definition at line 1988 of file tria_accessor.cc.
Using directive for backwards-compatibility.
Definition at line 3641 of file tria_accessor.h.
Definition at line 3643 of file tria_accessor.h. | https://dealii.org/current/doxygen/deal.II/classCellAccessor.html | CC-MAIN-2021-25 | refinedweb | 2,482 | 57.67 |
NAME
fclose - close a stream
SYNOPSIS
#include <stdio.h> int fclose(FILE *fp);
DESCRIPTION
The fclose() function will flush the stream pointed to by fp (writing any buffered output data using fflush(3)) and close the underlying file descriptor. The behaviour of fclose() is undefined if the stream parameter is an illegal pointer, or is a descriptor already passed to a previous invocation of fclose().
RETURN VALUE
Upon successful completion 0 is returned. Otherwise, EOF is returned and the global variable
C89, C99.
NOTES
Note that fclose() only flushes the user space buffers provided by the C library. To ensure that the data is physically stored on disk the kernel buffers must be flushed too, for example, with sync(2) or fsync(2).
SEE ALSO
close(2), fcloseall(3), fflush(3), fopen(3), setbuf(3)
COLOPHON
This page is part of release 3.01 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at. | http://manpages.ubuntu.com/manpages/intrepid/man3/fclose.3.html | CC-MAIN-2014-15 | refinedweb | 164 | 64.51 |
note demerphq <p> Sorry [ovid], but the code you posted as an example did not make that very clear*. You basically cannot get rid of namespace pollution in perl. It is impossible. Any piece of code can declare objects in any namespace at any time. </p> <p> As far as /useful/ advice, :-), take a look at the top of Benchmark.pm and see how Jarkko did it. </p> <p> * Update: i mean it didnt make your question clear. I know you arent a newbie. Remember we drank a fair amount of whiskey together in vienna? ;-) </p> <div class="pmsig"><div class="pmsig-108447"> ---<br /> $world=~s/war/peace/g<br /> <br /> </div></div> 771388 771557 | http://www.perlmonks.org/index.pl?displaytype=xml;node_id=771641 | CC-MAIN-2016-22 | refinedweb | 115 | 77.84 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.