Автор: ignat99
То есть аноним считает что ИИ - буквально персептрон Розенблата или классификатор какой то. А вот Заде в 1965 году считал что ИИ это ряд технологий связанных вместе (я список приводил - распознавание естественных языков, эвристики, логические выводы, поиск минимум целевой функции, нейро-сети но для самых простых случаев - не один метод сам по себе не считался панацеей, скорее наоборот на каждый случай нужен специальный рецепт составленный программистом).
Есть книга Коллективный Разум - там все классификаторы разобраны. Примеры приведены. Я их запускал и смотрел результаты, лет 5 назад. Не впечатлили меня эти результаты.
А я говорю строго по теме...
Вот например если вы сделаете генетическую модификацию мозга человека это будет СИИ?
Вот об этом в деталях я всегда и говорю... Вот уже почти код привел генетический. Как правильно все это делать есть в старых тибетских книгах, переведенных на санскрит, затем на монгольский в списках и затем частично переведенных на русский.
Просто я шире тему освещаю :-) чем частный случай нелинейной логики или мягкого программирования или персептрон Розенблата или классификатор какой то. |
|
Вот весь Ваш "ИИ" с https://github.com/Ignat99/RaNet/tree/master/Python менее 50 строк если убрать коменты, всегото парсер примитивненький import rdflib
rdflib.plugin.register('sparql', rdflib.query.Processor, 'rdfextras.sparql.processor', 'Processor') rdflib.plugin.register('sparql', rdflib.query.Result, 'rdfextras.sparql.query', 'SPARQLQueryResult')
from rdflib import Graph g = Graph() g.parse("http://bigasterisk.com/foaf.rdf") g.parse("http://www.w3.org/People/Berners-Lee/card.rdf")
from rdflib import Namespace FOAF = Namespace("http://xmlns.com/foaf/0.1/") g.parse("http://danbri.livejournal.com/data/foaf") [g.add((s, FOAF['name'], n)) for s,_,n in g.triples((None, FOAF['member_name'], None))]
for row in g.query('SELECT ?aname ?bname WHERE { ?a foaf:knows ?b . ?a foaf:name ?aname . ?b foaf:name ?bname . }', initNs=dict(foaf=Namespace("http://xmlns.com/foaf/0.1/"))): print "%s knows %s" % tuple(row)
import urllib # URL encoding import simplejson # JSON serialization and parsing import urllib2 # URL content fetching import cookielib # HTTP Cookie handling
# Metaweb read services READ = '/api/service/mqlread' # Path to mqlread service SEARCH = '/api/service/search' # Path to search service DOWNLOAD = '/api/trans/raw' # Path to download service BLURB = '/api/trans/blurb' # Path to document blurb service THUMB = '/api/trans/image_thumb' # Path to image thumbnail service
# Metaweb write services LOGIN = '/api/account/login' # Path to login service WRITE = '/api/service/mqlwrite' # Path to mqlwrite service UPLOAD = '/api/service/upload' # Path to upload service TOUCH = '/api/service/touch' # Path to touch service
# Metaweb services return this code on success OK = '/api/status/ok'
class Session(object):
def __init__(self, host="sandbox-freebase.com", cookiejar=None, **options): """Session constructor method""" self.host = host self.cookiejar = cookiejar or cookielib.FileCookieJar() self.options = options
def read(self, *queries, **options): # How many queries are we handling? n = len(queries)
# Gather options that apply to these queries opts = self._getopts("lang", "as_of_time", "escape", "uniqueness_failure", **options)
# Create an outer envelope object outer = {}
# Build the inner envelope for each query and put it in the outer. for i in range(0, n): inner = {'query': queries[i]} # Inner envelope holds a query. inner.update(opts) # Add envelope options. outer['q%d' % i] = inner # Put inner in outer with name q(n).
# Convert outer envelope to a string json = self._dumpjson(outer)
# Encode the query string as a URL parameter and create a url urlparam = urllib.urlencode({'queries': json}) url = 'http://%s%s?%s' % (self.host, READ, urlparam) # Fetch the URL contents, parse to a JSON object and check for errors. # From here on outer and inner refer to response, not query, envelopes. outer = self._check(self._fetch(url))
# Extract results from the response envelope and return in an array. # If any individual query returned an error, raise a ServiceError. results = [] for i in range(0, n): inner = outer["q%d" % i] # Get inner envelope from outer self._check(inner) # Check inner for errors results.append(inner['result']) # Get query result from inner
# If there was just one query, return its results. Otherwise # return the array of results if n == 1: return results[0] else: return results
def results(self, query, **options):
# Gather options that apply to this query opts = self._getopts("lang", "as_of_time", "escape", "uniqueness_failure", **options)
# Build the query envelope envelope = {'query': query} envelope.update(opts)
# Start with cursor set to true cursor = True
# Loop until cursor is no longer true while cursor: # Use the cursor as an envelope parameter envelope['cursor'] = cursor
# JSON-encode the envelope and convert it to a URL parameter params=urllib.urlencode({'query': self._dumpjson(envelope)}) # Build the URL url = 'http://%s%s?%s' % (self.host, READ, params)
# Fetch and parse the URL contents, raising ServiceError on errors response = self._check(self._fetch(url)) # Get the results array and yield one result at a time results = response['result'] for r in results: yield r
# Get the new value of the cursor for the next iteration cursor = response['cursor']
def search(self, query, **options): opts = self._getopts("domain", "type", # Build a dict of search options "type_strict", # from these session options "limit", "start", "escape", "mql_output", **options) # plus any passed to this method
if query.endswith('*'): # If search string ends with * opts["prefix"] = query[0:-1] # then this is a prefix search else: # Otherwise... opts["query"] = query # It is a regular query
params = urllib.urlencode(opts) # Encode options url = "http://%s%s?%s" % (self.host,SEARCH,params) # Build URL envelope = self._fetch(url) # Fetch response self._check(envelope) # Check that its OK return envelope["result"] # Return result
def download(self, id): return self._trans(self.contentURL(id))
def blurb(self, id, **options): """ Return the content and type of a document blurb. See blurbURL(). """ return self._trans(self.blurbURL(id, **options))
def thumbnail(self, id, **options): """ Return the content (as a binary string) and type of an image thumbnail. See thumbnailURL(). """ return self._trans(self.thumbnailURL(id, **options))
def contentURL(self, id): """ Return the /api/trans URL of the /type/content, /common/image, or /common/document content identified by the id argument. """ return self._transURL(id, DOWNLOAD)
def blurbURL(self, id, **options): return self._transURL(id, BLURB, ["maxlength", "break_paragraphs"], options)
def thumbnailURL(self, id, **options): return self._transURL(id, THUMBNAIL, ["maxwidth","maxheight"], options)
def _getopts(self, *keys, **local_options): o = {} for k in keys: if k in self.options: o[k] = self.options[k] o.update(local_options) return o
def _http(self, url, headers={}, body=None): # Store the url in case we need it later for error reporting. # Note that this is not safe if multiple threads use the same Session. self.lasturl = url;
# Build the request. Will use POST if a body is supplied request = urllib2.Request(url, body, headers)
# Add any cookies in the cookiejar to this request self.cookiejar.add_cookie_header(request)
try: stream = urllib2.urlopen(request) # Try to open the URL, get stream self.cookiejar.extract_cookies(stream, request) # Remember cookies headers = stream.info() body = stream.read() return (stream.code, headers, body) except urllib2.HTTPError, e: # If we get an HTTP error code return (e.code, e.info(), e.read()) # But return values as above
def _parsejson(self, s): try: return simplejson.loads(s) except: raise InternalServiceError(self.lasturl, s)
def _dumpjson(self, o, pretty=False): if pretty: return simplejson.dumps(o, indent=4) else: return simplejson.dumps(o)
def _fetch(self, url, headers={}, body=None): # Fetch the URL contents (status, headers, body) = self._http(url, headers, body); # Parse the response body as JSON, and return the resulting object. return self._parsejson(body)
def _trans(self, url): (status,headers,body) = self._http(url) # Fetch url content if (status == 200): # If successful return body,headers['content-type'] # Return content and type else: # HTTP status other than 200 errobj = self._parsejson(body) # Parse the body raise ServiceError(url, errobj) # And raise ServiceError
def _check(self, response): code = response['code'] if code != OK: raise ServiceError(self.lasturl, response) else: return response
# This utility method returns a URL for the trans service def _transURL(self, id, service, option_keys=[], options={}): url = "http://" + self.host + service + id # Base URL. opts = self._getopts(*option_keys, **options) # Get request options. if len(opts) > 0: # If there are options... url += "?" + urllib.urlencode(opts) # encode and add to url. return url
class ServiceError(Exception):
# This constructor expects the URL requested and the parsed response. def __init__(self, url, details): self.url = url self.details = details
# Convert to a string by printing url + the first error code and message def __str__(self): prefix = self.url.partition('?')[0] msg = self.details['messages'][0] return prefix + ": " + msg['code'] + ": " + msg['message']
class InternalServiceError(ServiceError): def __init__(self, url, body): ServiceError.__init__(self, url, {'code':'Internal service error', 'messages':[{'code':'Unparseable response', 'message':body}] })
|