def predict(): f = glob.glob('*.d')#.d Es el diccionario que toma un clima y le asigna un número Se genera en #cuanto procesas los datos if 'states.d' not in f: raise "No data has been processed, cannot express any prediction." with open('states.d', 'rb') as fp: states = cPickle.load(fp) with open('test_set.csv', 'rb') as fp: lines = fp.readlines() lines = lines[1:] #retorna lista data = [line[0:line.find('\n')].split(',') for line in lines] dates = map(lambda x: x[0], data) data = [f[1:] for f in data] inputs = np.zeros((len(data[0]), len(data))) for i,input in enumerate(data): #retorna lista l = map(lambda x: float(x), input[0:-1]) l.append(states[input[-1]]) inp = np.array([l]) inputs[:, i] = inp values = linear.predict(inputs) #guarda los datos de prediccion en el formato esperado with open('output.csv', 'wb') as fp: fp.write('"fecha", "conteo_ordenes"\n') for i in range(0, len(dates)): line = '"'+dates[i]+'"'+','+str(int(np.round(values[i][0])))+'\n' fp.write(line)
def perceptron_update(bow, label, weights, labels): update = defaultdict(lambda: defaultdict(float)) prediction, _ = predict(bow, weights, labels) if prediction == label: # no changes need to be made to the weights return update # for mean squared error, `w(t+1) = w(t) + learn_rate * (y - y_pred) * x` # Here, we are computing `(y - y_pred) * x` as `y * x - y_pred * x` for word in bow: update[label][word] += bow[word] update[prediction][word] -= bow[word] return update
while True: test_data, test_events, stopevents = bufhelp.gatherdata( "stimulus.hybrid", trlen_ms, "stimulus.hybrid", milliseconds=True) # if isinstance(stopevents, list): # if any(["stimulus.feedback" in x.type for x in stopevents]): # break # else: # if "stimulus.sequence" in stopevents.type: # break test_data = preproc.detrend(test_data) test_data, badch = preproc.badchannelremoval(test_data) test_data = preproc.spatialfilter(test_data) test_data = preproc.spectralfilter(test_data, (1, 10, 15, 25), bufhelp.fSample) test_data, test_events, badtrials = preproc.badtrailremoval( test_data, test_events) predictions = linear.predict(test_data, classifier) prediction = str(int(predictions[0])) bufhelp.sendEvent("classifier.prediction", prediction) elif e.value == "exit": run = False print("Waiting for startPhase.cmd event.")
import preproc import linear import pickle dname ='training_data' cname ='clsfr' trlen_ms = 3000 #load the trained classifier if os.path.exists(cname+'.pk'): f =pickle.load(open(cname+'.pk','rb')) classifier = f['classifier'] # connect to the buffer, if no-header wait until valid connection ftc,hdr=bufhelp.connect() while True: # wait for data after a trigger event data, events, stopevents, state = bufhelp.gatherdata(["stimulus.target"],trlen_ms,[("stimulus.feedback","end")], milliseconds=True) # YOUR CODE HERE # # apply classifier, default is a linear-least-squares-classifier predictions = linear.predict(data) # send the prediction events for pred in predictions: bufhelp.sendEvent("classifier.prediction",pred)
import pickle dname = 'training_data' cname = 'clsfr' trlen_ms = 3000 #load the trained classifier if os.path.exists(cname + '.pk'): f = pickle.load(open(cname + '.pk', 'rb')) classifier = f['classifier'] # connect to the buffer, if no-header wait until valid connection ftc, hdr = bufhelp.connect() while True: # wait for data after a trigger event data, events, stopevents, state = bufhelp.gatherdata( ["stimulus.target"], trlen_ms, [("stimulus.feedback", "end")], milliseconds=True) # YOUR CODE HERE # # apply classifier, default is a linear-least-squares-classifier predictions = linear.predict(data) # send the prediction events for pred in predictions: bufhelp.sendEvent("classifier.prediction", pred)
# Example prediction: # Service was bad. (negative) # First, we clean up the sentence and get a bag of words representation. instance = bag_of_words(sanitize('Service was bad.')) # Then, we set up our prediction weights. # The weights below assume that 'service' and 'was' are not very relevant # to a positive classification, but the word 'bad' is very non-positive positive_weights = {'service': 0.2, 'was': 0.0, 'bad': -1} # The weights below assume that 'service' and 'was' are pretty neutral neutral_weights = {'service': 0.5, 'was': 0.5, 'bad': 0.1} # The weights below assume that 'bad' is very negative. negative_weights = {'service': 0.1, 'was': 0.3, 'bad': 0.9} # Put all the weights together so we can index into them by their labels all_weights = { 'positive': positive_weights, 'neutral': neutral_weights, 'negative': negative_weights } # Get a list of labels from all of the unique keys (indexes) in the weights labels = list(set(all_weights.keys())) # Predict the label of the instance using the weights above and the list of # possible labels prediction = predict(instance, all_weights, labels) print('Predicted label:', prediction[0]) print('Score:', prediction[1])