Example #1
0
    def plot_convergence(self, i, fig_conv):
        """
        Plots the convergence curve
        
        This method plots the convergence of the best fitness and average 
        fitness of the population over each generation. 
        
        Parameters: 
            i: current iteration
            fig_conv: figure that refers to the convergence plot
            
        """

        if i == 1:
            plt.semilogy([i - 1, i],
                         [self.fitness_best[i - 1], self.fitness_best[i]],
                         'b',
                         label='Best merit function')
            plt.semilogy([i - 1, i],
                         [self.fitness_avg[i - 1], self.fitness_avg[i]],
                         'r--',
                         label='Average merit function')
            plt.legend(loc='upper right')
            fig_conv.show()
            plt.pause(0.05)

        elif i > 1:
            plt.semilogy([i - 1, i],
                         [self.fitness_best[i - 1], self.fitness_best[i]], 'b')
            plt.semilogy([i - 1, i],
                         [self.fitness_avg[i - 1], self.fitness_avg[i]], 'r--')
            fig_conv.show()
            plt.pause(0.05)

        return
Example #2
0
def episode_finished_train(r):
    print("Trained mother: " + str(r.episode_rewards[-1]))

    train_reward.append(r.episode_rewards[-1])
    plt.plot(train_reward, 'r+')
    plt.pause(0.01)
    return True
Example #3
0
def live_plotter(x_vec, y1_data, line1, identifier='', pause_time=0.1):
    if line1 == []:
        # this is the call to matplotlib that allows dynamic plotting
        plt.ion()
        fig = plt.figure(figsize=(13, 6))
        ax = fig.add_subplot(111)
        # create a variable for the line so we can later update it
        line1, = ax.plot(x_vec, y1_data, '-o', alpha=0.8)
        #update plot label/title
        plt.ylabel('Y Label')
        plt.title('Title: {}'.format(identifier))
        plt.show()

    # after the figure, axis, and line are created, we only need to update the y-data
    line1.set_ydata(y1_data)
    # adjust limits if new data goes beyond bounds
    if np.min(y1_data) <= line1.axes.get_ylim()[0] or np.max(
            y1_data) >= line1.axes.get_ylim()[1]:
        plt.ylim([
            np.min(y1_data) - np.std(y1_data),
            np.max(y1_data) + np.std(y1_data)
        ])
    # this pauses the data so the figure/axis can catch up - the amount of pause can be altered above
    plt.pause(pause_time)

    # return line so we can update it again in the next iteration
    return line1
Example #4
0
def episode_finished(r):
    print(
        "Finished episode {ep} after {ts} timesteps (reward: {reward})".format(
            ep=r.episode, ts=r.episode_timestep, reward=r.episode_rewards[-1]))
    plt.plot(r.episode_rewards, 'r+')
    plt.pause(0.01)
    agent.save_model('forex_agent_sma_1week_train/')
    return True
Example #5
0
            def plottrace(self, point):
                # 使用matplotlib之pyplot绘制船舶轨迹
                # point = 38
                def initial(ax):
                    ax.axis("equal")  #设置图像显示的时候XY轴比例
                    ax.set_xlabel('Horizontal Position')
                    ax.set_ylabel('Vertical Position')
                    ax.set_title('Vessel trajectory')
                    plt.grid(True)  #添加网格
                    return ax

                es_time = np.zeros([point])
                fig = plt.figure()
                ax = fig.add_subplot(1, 1, 1)
                ax = initial(ax)

                # test
                ax2 = fig.add_subplot(1, 1, 1)
                ax2 = initial(ax2)

                plt.ion()  #interactive mode on 动态绘制

                # IniObsX=0000
                # IniObsY=4000
                # IniObsAngle=135
                # IniObsSpeed=10*math.sqrt(2)   #米/秒
                # print('开始仿真')
                obsX = []
                obsX2 = []
                # obsY = [4000,]
                obsY = []
                obsY2 = []
                for t in range(point):
                    # t0 = time.time()
                    #障碍物船只轨迹
                    # obsX.append(IniObsX+IniObsSpeed*math.sin(IniObsAngle/180*math.pi)*t)
                    obsX.append(sim_res.SHIP1POS[t][0])
                    obsX2.append(sim_res.SHIP2POS[t][0])
                    # obsY.append(IniObsY+IniObsSpeed*math.cos(IniObsAngle/180*math.pi)*t)
                    obsY.append(sim_res.SHIP1POS[t][1])
                    obsY2.append(sim_res.SHIP2POS[t][1])
                    plt.cla()
                    ax = initial(ax)
                    ax.plot(obsX, obsY, '-g', marker='*')  #散点图

                    # test
                    ax2 = initial(ax2)
                    ax2.plot(obsX2, obsY2, '-r', marker='o')
                    risk_value_text = 'Risk value: ' + str(
                        sim_res.RISKVALUE[t])
                    plt.text(0, 7, risk_value_text)
                    plt.pause(0.5)
                    # es_time[t] = 1000*(time.time() - t0)
                plt.pause(0)
                # return es_time
                pass
 def plot(self,splt_num,x,y1,y2,y3):
     
     lhost=[self.host1,self.host2]
     lpar=[[self.par11,self.par12],[self.par21,self.par22]]
     self.p1,=lhost[splt_num-1].plot(x,y1,'C0')
     self.p2,=lpar[splt_num-1][0].plot(x,y2,'C1')
     self.p3,=lpar[splt_num-1][1].plot(x,y3,'C2')
     lhost[splt_num-1].axis["left"].label.set_color(self.p1.get_color())
     lpar[splt_num-1][0].axis["right"].label.set_color(self.p2.get_color())
     lpar[splt_num-1][1].axis["right"].label.set_color(self.p3.get_color())
     plt.pause(0.000001)
Example #7
0
def imshow(tensor, title=None):
    # To reconvert the tensor back to an image at the end
    unloader = transforms.ToPILImage()

    # clones the tensor so it doesn't make changes on the original image
    image = tensor.cpu().clone()
    image = image.squeeze(0)
    image = unloader(image)
    plt.imshow(image)
    if title is not None:
        plt.title(title)
    plt.pause(0.0001)
Example #8
0
 def draw(self):
     if self.plot_h['axis'] is None:
         #self.plot_h['fig'] = plt.figure()
         plt.figure()
         self.grid.drawGrid()
         self.plot_h['axis'] = plt.gca()
         self.plot_h['axis'].set_aspect(1)
     else:
         plt.sca(self.plot_h['axis'])
     for vox in self.voxels:
         vox.draw()
     if Par.liveDrawing:
         plt.pause(1e-6)
def main():

    #DEFINITON OF THE PATHS TO THE FILES WITH THE CONTENT
    path_to_train_accuracy = 'accuracy_train_data.csv'
    path_to_train_loss = 'loss_train_data.csv'
    path_to_validation_accuracy = 'accuracy_validation_data.csv'
    path_to_validation_loss = '"loss_validation_data.csv"'

    # CREATE LIST OF NUMBER OF EPOCHS COMPUTED
    eval_indices = range(1, EPOCHS + 1)

    #LOADS THE DATA FROM THE FILES
    accuracy_train, loss_train, accuracy_validation, loss_validation = read_data(path_to_train_accuracy,path_to_train_loss,
                                                                                 path_to_validation_accuracy,path_to_validation_loss)

    #SHOW THE INFORMATION FOR CONTROL OF QUALITY
    print(eval_indices)
    print("Accuracy Train: ",accuracy_train)
    print("Loss Train: " ,loss_train)
    print("Accuracy Validation: ", accuracy_validation)
    print("Loss validation: ", loss_validation)

    # DRAW THE ACCURACY GRAPH FOR VALIDATION AND TRAIN
    plt.clf()
    plt.subplot(211)
    plt.plot(eval_indices, accuracy_train, 'k--', label='TREINO')
    plt.plot(eval_indices, accuracy_validation, 'g-x', label='VALIDAÇÃO')
    plt.legend(loc='upper right')
    plt.xlabel('Épocas')
    plt.ylabel('ACERTO')
    plt.grid(which='major', axis='both')

    # DRAW THE LOSS GRAPH FOR VALIDATION AND TRAIN
    plt.subplot(212)
    # plt.plot(eval_indices, train, 'g-x', label='Train Set Accuracy')
    plt.plot(eval_indices, loss_train, 'r-x', label='TREINO')
    # plt.plot(eval_indices, np.ones(len(eval_indices))/TOT_CLASSES, 'k--')
    plt.plot(eval_indices, loss_validation, 'k--', label='VALIDAÇÃO')
    plt.legend(loc="upper right")
    plt.xlabel('Épocas')
    plt.ylabel('ERRO')
    plt.ylim(0, 1)
    plt.grid(which='both', axis='y')

    plt.subplots_adjust(left=0.2, wspace=0.2, hspace=0.3)

    plt.show()
    plt.pause(0.01)

    #SAVES BOTH OF THE GRAPHICS IN ONE FILE NAMED "Learning.png"
    plt.savefig('Learning.png')
Example #10
0
def plot_data(tmp_temp):
    global cnt

    temp_c.append(tmp_temp)  # Append temp readings
    drawnow(makeFig)  # Update graph
    plt.pause(.000001)  # To keep drawnow from crashing
    cnt = cnt + 1
    if (cnt > 50):  # Show 50 pts and then erase from left
        temp_c.pop(0)
    if tcp_mode == True:
        # Convert string to byte
        s = tmp_temp + '\r'  # add CR
        b = s.encode('ascii')
        read(conn, b)
Example #11
0
def episode_finished(r):
    print(
        "Finished episode {ep} after {ts} timesteps (reward: {reward})".format(
            ep=r.episode, ts=r.episode_timestep, reward=r.episode_rewards[-1]))
    plt.plot(r.episode_rewards, 'r+')
    global iter
    global modelSaves
    plt.pause(0.01)

    if (iter == 50):
        iter = 0
        agent.save_model('traning/forex_agent_sma_lstm_15week_train_')
        modelSaves = modelSaves + 1
    else:
        iter = iter + 1

    return True
Example #12
0
def episode_finished(r):
    print("Finished episode {ep} after {ts} timesteps (reward: {reward})".format(ep=r.episode, ts=r.episode_timestep,
                                                                             reward=r.episode_rewards[-1]))
    plt.plot(r.episode_rewards, 'r+')
    global iter
    global modelSaves
    plt.pause(0.01)


    if(iter == 51):
        iter = 0
        agent.save_model('gradBig/dense_mix')
        modelSaves = modelSaves + 1
    else:
        iter = iter + 1

    return True
 def plot_rewards(self):
     plt.figure(1)
     plt.clf()
     plt.title('Training...')
     plt.xlabel('Time')
     plt.ylabel('Reward')
     cumulative = []
     for i in range(len(self.rewards[self.n_training])):
         if i == 0:
             cumulative.append(self.rewards[self.n_training][i])
         else:
             cumulative.append(self.rewards[self.n_training][i] +
                               cumulative[-1])
     x = np.linspace(2.0,
                     len(self.rewards[self.n_training]),
                     num=len(self.rewards[self.n_training]))
     plt.plot(x, cumulative)
     plt.show()
     plt.pause(0.001)  # pause a bit so that plots are updated
Example #14
0
    def recieve(self):
        plt.ion()
        while 1:
            if self.stat:
                addr = self.lineEdit.text()
                port = self.lineEdit_2.text()
                response = requests.get('http://' + addr + ':' + port +
                                        '/get_data')
                if response.status_code == 200:
                    self.df = pd.DataFrame.from_dict(response.json())
                    self.label_3.setText('Подключенных устройств: ' +
                                         str(len(self.df.index)))
                    print('\n')
                    print(
                        str(datetime.datetime.now().strftime(
                            '%Y/%m/%d %H:%M:%S')))
                    print(self.df)
                    if self.tableWidget.rowCount() < self.df.shape[0]:
                        self.tableWidget.setRowCount(self.df.shape[0])
                    for i in range(0, self.df.shape[0]):
                        for i2 in range(0, 4):
                            self.tableWidget.setItem(
                                i, i2,
                                QTableWidgetItem(str(self.df.iloc[i, i2])))
                    self.tableWidget.reset()
                    self.textBrowser_2.append(
                        str(datetime.datetime.now().strftime(
                            '%Y/%m/%d %H:%M:%S')) + '\n' +
                        self.df.to_string() + '\n')

                    self.d1.append(int(self.df.iloc[0][3]))
                    self.d2.append(int(self.df.iloc[1][3]))
                    drawnow(self.makeFig, stop_on_close=True)
                    plt.pause(.000001)
                    self.counter += 1
                    if self.counter > 50:
                        self.d1.pop(0)
                        self.d2.pop(0)
            else:
                return 0
            time.sleep(0.4)
def Transit(lc, PGpoints, intrans, starpos):
    #Takes in shape. Draws it as array. Moves it across the Star. Draws lightcurve. Compares with known ligthcurve
    movie=0
    #Drawing star
    star = DrawStar(starpos)
    #Normalising total flux to 1.0
    star/=np.sum(star)
    #Turning the polygon into an array
    from PIL import Image, ImageDraw
    img = Image.new('L', (800, 800), 0)
    ImageDraw.Draw(img).polygon(PGpoints, outline=1, fill=1)
    objbox=np.array(img)
    objbox=1-objbox
    #Setting animation to step 4 pixels at a time
    step=4.0
    lc=lc[lc[:, 0].argsort(), :]
    timearr=np.linspace(lc[0,0],lc[-1,0],1600)
    print timearr
    print lc[:, 0]
    lightcurvemodel=[]
    #Drawing initial plots
    fig=plt.figure(figsize=(6,  12))
    ax1=fig.add_subplot(211)
    ax1.imshow(star[:, :800],cmap='hot');
    ax2=fig.add_subplot(212)
    ax2.plot(lc[:,0],lc[:,1],'--k')
    ax2.plot(timearr, np.tile(1.0, 1600),'--', color='#CCCCCC')
    plt.pause(0.002)
    #Sweep across the star, keeping the object fixed
    for pix in range(400,2000, step):
        #Draw an 800x800 box from the star
        starbox=star[:,(pix-400):(pix+400)]
        total=objbox*starbox
        #if np.sum(starbox)!=0:#skipping to where there is some of the star on the screen
        ax1.cla()
        ax1.imshow(total,cmap='hot');
        #plotting lightcurve
        rest=np.sum(star[:,:(pix-400)])+np.sum(star[:, (pix+400):])
        lightcurvemodel+=[np.sum(total)+np.sum(rest)]
        ax2.plot(timearr[pix-400],np.array(lightcurvemodel)[-1],'.r')
        plt.pause(0.002)
        movie=1 #Setting to record pngs as movie
        if movie==1:
            plt.savefig('TransitMovie/Movie'+str(pix)+'.png')
    plt.pause(1)
    np.savetxt('OutLightcurve.txt',np.column_stack((timearr[0:len(lightcurvemodel)],np.array(lightcurvemodel))))
 def plot_simple(self,x,y):
     
     self.p1,=self.host2.plot(x,y,'C0')
     self.host2.axis["left"].label.set_color(self.p1.get_color())
     plt.pause(0.000001)
    m = Basemap(
        llcrnrlon=dPar['xmin'],
        urcrnrlon=dPar['xmax'],
        llcrnrlat=dPar['ymin'],
        urcrnrlat=dPar['ymax'],
        lon_0=lon_0,
        lat_0=lat_0,
        resolution='l',
        projection=dPar['projection'],
    )

m.drawcoastlines()
aX_we, aY_we = m(injection_wells[2][sel_we], injection_wells[3][sel_we])
m.plot(aX_we, aY_we, 'go', ms=2)
aX_eq, aY_eq = m(seismic_activity[1][sel_eq], seismic_activity[2][sel_eq])
m.plot(aX_eq, aY_eq, 'ro', ms=2)
m.drawparallels(np.arange(33, 38, 1), fmt='%i', labels=[1, 0, 0, 0])
m.drawmeridians(np.arange(-100, -92, 2), fmt='%i', labels=[0, 0, 0, 1])

matplotlib.pause(.5)
matplotlib.clf()
"""
Part E
"""
"""
Based on my analysis of earthquake rates and locations, seismicity rates 
started to significanty exceed historic values in the year 2010. In 
2017, earthquake rates started to decrease. This is beacause 
man-made earthquakes were no longer happening.
"""
Example #18
0
        initialCon.append(-0.01 / 300.0 * x)

# Ensuring boundary conditions
#initialCon[0] = 0
#initialCon[-1] = 0


yPrev = initialCon
yCurrent = initialCon
sample = []
 
for n in range(0,10):
    for i in range(0,len(x)):
        if i !=0 and i != 649:
           yNew = ((2 - 2*r**2 - 6 * eps * r**2 * N**2)*yCurrent[i] 
                   - yPrev[i] + r**2*(1 + 4*eps*N**2)*(yCurrent[i+1] 
                    + yCurrent[i-1]) - eps*r**2*N**2 *(yCurrent[i+2] 
                    + yCurrent[i-2]))
                   
        yPrev = copy(yCurrent)
        yCurrent = copy(yNew)
        plt.scatter(yNew)
        plt.draw()
        plt.pause()
        plt.clf()
                    
                   
                   
        
    
Example #19
0
import numpy as np
import matplotlib as plt
import time
plt.axis([0, 10, 0, 1])
plt.ion()

for i in range(10):
    y = np.random.random()
    plt.scatter(i, y)
    plt.pause(0.05)
    time.sleep(1)


    
            y = np.array([pose_3d[i[0]][1], pose_3d[i[1]][1]])
            z = np.array([pose_3d[i[0]][2], pose_3d[i[1]][2]])
            ax.plot3D(x, y, z, 'red')

def add_point(pose_3d, ax):
    x, y, z = pose_3d[:, 0], pose_3d[:, 1], pose_3d[:, 2]
    ax.scatter3D(x, y, z, cmap='Greens')

import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
plt.ion()
i = 0
for pose_3d in pose_3d_all:

    add_line(pose_3d, ax)

    add_point(pose_3d, ax)

    square_x = np.array([-2000, 1000])
    square_y = np.array([-1000, 2000])
    square_z = np.array([500, 3500])
    ax.scatter3D(square_x, square_y, square_z, color='whitesmoke')

    plt.draw()

    plt.pause(0.01)
    if i == 0:
        plt.pause(2)
    i += 1
    plt.cla()
Example #21
0
prediction = add_layer(l1, 10, 1, activation_function=None)
#计算预测值prediction和真实值的误差,对二者差的平方求和再取平均
loss = tf.reduce_mean(
    tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

#生成图片框
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(x_data, y_data)
plt.show()

for i in range(1000):
    #training
    sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
    if (i % 50 == 0):
        # to visualize the result and improvement
        try:
            ax.lines.remove(lines[0])
        except Exception:
            pass
        prediction_value = sess.run(prediction, feed_dict={xs: x_data})
        # plot the prediction
        lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
        plt.pause(0.1)
        #print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
Example #22
0
def process(path):
	msev=[]
	maev=[]
	rsqv=[]
	rmsev=[]
	acyv=[]

	df = pd.read_csv(path,encoding="latin-1")

	x1=np.array(df['Lyrics'].values.astype('U'))
	y1=np.array(df['MoodValue'])
	print(x1)
	print(y1)

	print(x1)
	print(y1)
	X_train, X_test, y_train, y_test = train_test_split(x1, y1,test_size=0.20)
	
	count_vectorizer = CountVectorizer(stop_words='english')
	count_train = count_vectorizer.fit_transform(X_train)                  # Learn the vocabulary dictionary and return term-document matrix.
	count_test = count_vectorizer.transform(X_test)

	tfidf_vectorizer = TfidfVectorizer(stop_words='english', max_df=0.7)    # This removes words which appear in more than 70% of the articles
	tfidf_train = tfidf_vectorizer.fit_transform(X_train) 
	tfidf_test = tfidf_vectorizer.transform(X_test)
	


	model2=RandomForestClassifier()
	model2.fit(count_train, y_train)
	y_pred = model2.predict(count_test)
	print("predicted")
	print(y_pred)
	print("test")
	print(y_test)

	result2=open("results/resultCOUNTRF.csv","w")
	result2.write("ID,Predicted Value" + "\n")
	for j in range(len(y_pred)):
	    result2.write(str(j+1) + "," + str(y_pred[j]) + "\n")
	result2.close()
	
	mse=mean_squared_error(y_test, y_pred)
	mae=mean_absolute_error(y_test, y_pred)
	r2=abs(r2_score(y_test, y_pred))
	
	
	print("---------------------------------------------------------")
	print("MSE VALUE FOR RandomForest COUNT IS %f "  % mse)
	print("MAE VALUE FOR RandomForest COUNT IS %f "  % mae)
	print("R-SQUARED VALUE FOR RandomForest COUNT IS %f "  % r2)
	rms = np.sqrt(mean_squared_error(y_test, y_pred))
	print("RMSE VALUE FOR RandomForest COUNT IS %f "  % rms)
	ac=accuracy_score(y_test,y_pred)
	print ("ACCURACY VALUE RandomForest COUNT IS %f" % ac)
	print("---------------------------------------------------------")
	
	msev.append(mse)
	maev.append(mae)
	rsqv.append(r2)
	rmsev.append(rms)
	acyv.append(ac*100)

	result2=open('results/COUNTRFMetrics.csv', 'w')
	result2.write("Parameter,Value" + "\n")
	result2.write("MSE" + "," +str(mse) + "\n")
	result2.write("MAE" + "," +str(mae) + "\n")
	result2.write("R-SQUARED" + "," +str(r2) + "\n")
	result2.write("RMSE" + "," +str(rms) + "\n")
	result2.write("ACCURACY" + "," +str(ac) + "\n")
	result2.close()
	
	
	df =  pd.read_csv('results/COUNTRFMetrics.csv')
	acc = df["Value"]
	alc = df["Parameter"]
	colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b"]
	explode = (0.1, 0, 0, 0, 0)  
	
	fig = plt.figure()
	plt.bar(alc,acc,color=colors)
	plt.xlabel('Parameter')
	plt.ylabel('Value')
	plt.title(' COUNT Random Forest Metrics Value')
	fig.savefig('results/COUNTRFMetricsValue.png') 
	plt.pause(5)
	plt.show(block=False)
	plt.close()

	model2=RandomForestClassifier(max_depth=50, random_state=0,n_estimators=25)
	model2.fit(tfidf_train, y_train)
	y_pred = model2.predict(tfidf_test)
	print("predicted")
	print(y_pred)
	print("test")
	print(y_test)

	result2=open("results/resultTFIDFRF.csv","w")
	result2.write("ID,Predicted Value" + "\n")
	for j in range(len(y_pred)):
	    result2.write(str(j+1) + "," + str(y_pred[j]) + "\n")
	result2.close()
	
	mse=mean_squared_error(y_test, y_pred)
	mae=mean_absolute_error(y_test, y_pred)
	r2=abs(r2_score(y_test, y_pred))
	
	
	print("---------------------------------------------------------")
	print("MSE VALUE FOR RandomForest TFIDF IS %f "  % mse)
	print("MAE VALUE FOR RandomForest TFIDF IS %f "  % mae)
	print("R-SQUARED VALUE FOR RandomForest TFIDF IS %f "  % r2)
	rms = np.sqrt(mean_squared_error(y_test, y_pred))
	print("RMSE VALUE FOR RandomForest TFIDF IS %f "  % rms)
	ac=accuracy_score(y_test,y_pred)
	print ("ACCURACY VALUE RandomForest TFIDF IS %f" % ac)
	print("---------------------------------------------------------")

	msev.append(mse)
	maev.append(mae)
	rsqv.append(r2)
	rmsev.append(rms)
	acyv.append(ac*100)
	

	result2=open('results/TFIDFRFMetrics.csv', 'w')
	result2.write("Parameter,Value" + "\n")
	result2.write("MSE" + "," +str(mse) + "\n")
	result2.write("MAE" + "," +str(mae) + "\n")
	result2.write("R-SQUARED" + "," +str(r2) + "\n")
	result2.write("RMSE" + "," +str(rms) + "\n")
	result2.write("ACCURACY" + "," +str(ac) + "\n")
	result2.close()
	
	
	df =  pd.read_csv('results/TFIDFRFMetrics.csv')
	acc = df["Value"]
	alc = df["Parameter"]
	colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#8c564b"]
	explode = (0.1, 0, 0, 0, 0)  
	
	fig = plt.figure()
	plt.bar(alc,acc,color=colors)
	plt.xlabel('Parameter')
	plt.ylabel('Value')
	plt.title(' TFIDF Random Forest Metrics Value')
	fig.savefig('results/TFIDFCOUNTRFMetricsValue.png') 
	plt.pause(5)
	plt.show(block=False)
	plt.close()


	al = ['COUNT','TFIDF']
    
    
	result2=open('results/RFMSE.csv', 'w')
	result2.write("Vectorization,MSE" + "\n")
	for i in range(0,len(msev)):
	    result2.write(al[i] + "," +str(msev[i]) + "\n")
	result2.close()
    
	colors = ["#1f77b4", "#ff7f0e", "#2ca02c"]
	explode = (0.1, 0, 0, 0, 0)  
       
    
	#Barplot for the dependent variable
	fig = plt.figure(0)
	df =  pd.read_csv('results/RFMSE.csv')
	acc = df["MSE"]
	alc = df["Vectorization"]
	plt.bar(alc,acc,color=colors)
	plt.xlabel('Vectorization')
	plt.ylabel('MSE')
	plt.title("Random Forest MSE Value");
	fig.savefig('results/RFMSE.png')
	plt.pause(5)
	plt.show(block=False)
	plt.close()
	    
    
    
	result2=open('results/RFMAE.csv', 'w')
	result2.write("Vectorization,MAE" + "\n")
	for i in range(0,len(maev)):
	    result2.write(al[i] + "," +str(maev[i]) + "\n")
	result2.close()
                
	fig = plt.figure(0)            
	df =  pd.read_csv('results/RFMAE.csv')
	acc = df["MAE"]
	alc = df["Vectorization"]
	plt.bar(alc,acc,color=colors)
	plt.xlabel('Vectorization')
	plt.ylabel('MAE')
	plt.title('Random Forest MAE Value')
	fig.savefig('results/RFMAE.png')
	plt.pause(5)
	plt.show(block=False)
	plt.close()
    
	result2=open('results/RFR-SQUARED.csv', 'w')
	result2.write("Vectorization,R-SQUARED" + "\n")
	for i in range(0,len(rsqv)):
	    result2.write(al[i] + "," +str(rsqv[i]) + "\n")
	result2.close()
            
	fig = plt.figure(0)        
	df =  pd.read_csv('results/RFR-SQUARED.csv')
	acc = df["R-SQUARED"]
	alc = df["Vectorization"]


	plt.bar(alc,acc,color=colors)
	plt.xlabel('Vectorization')
	plt.ylabel('R-SQUARED')
	plt.title('Random Forest R-SQUARED Value')
	fig.savefig('results/RFR-SQUARED.png')
	plt.pause(5)
	plt.show(block=False)
	plt.close()
	    
	result2=open('results/RFRMSE.csv', 'w')
	result2.write("Vectorization,RMSE" + "\n")
	for i in range(0,len(rmsev)):
	    result2.write(al[i] + "," +str(rmsev[i]) + "\n")
	result2.close()
      
	fig = plt.figure(0)    
	df =  pd.read_csv('results/RFRMSE.csv')
	acc = df["RMSE"]
	alc = df["Vectorization"]
	plt.bar(alc,acc,color=colors)
	plt.xlabel('Vectorization')
	plt.ylabel('RMSE')
	plt.title('Random Forest RMSE Value')
	fig.savefig('results/RFRMSE.png')
	plt.pause(5)
	plt.show(block=False)
	plt.close()
    
	result2=open('results/RFAccuracy.csv', 'w')
	result2.write("Vectorization,Accuracy" + "\n")
	for i in range(0,len(acyv)):
	    result2.write(al[i] + "," +str(acyv[i]) + "\n")
	result2.close()
    
	fig = plt.figure(0)
	df =  pd.read_csv('results/RFAccuracy.csv')
	acc = df["Accuracy"]
	alc = df["Vectorization"]
	plt.bar(alc,acc,color=colors)
	plt.xlabel('Vectorization')
	plt.ylabel('Accuracy')
	plt.title('Random Forest Accuracy Value')
	fig.savefig('results/RFAccuracy.png')
	plt.pause(5)
	plt.show(block=False)
	plt.close()
Example #23
0
def main():

    print("Waiting for camera Initialization...")
    cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    if cam.isOpened():
        print("Camera Initialized!")

    # Initialize NN forward prop.
    vgg = models.vgg16(pretrained=True)
    data_transform = transforms.Compose([
        transforms.CenterCrop(154),
        transforms.ToTensor(),
        transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
    ])
    avgpool = nn.AdaptiveAvgPool2d((7, 7))
    lstm_model = lstmModel(1024 * 7 * 7, 2048, 7)
    lstm_model_path = 'state.pt'
    lstm_model.load_state_dict(torch.load(lstm_model_path,
                                          torch.device('cpu')))
    classes = [
        'No Pancake', 'Raw', 'Ready to Flip', 'Bottom Up', 'Ready to Remove',
        'Burnt', 'Obstruction'
    ]

    # ite = 0
    rgb_img, tmp_dat = read_cameras(cam)
    # ite += 1

    rgb_dim, rgb_minmax = sample_img_dim(rgb_img)
    tmp_dim, tmp_minmax = sample_img_dim(tmp_dat)
    plt.close('all')
    plt.pause(0.1)

    feature_queue = []

    # Display Image
    fig, axs = plt.subplots(1, 2)

    axs[0].set_title("RGB Image")
    ax0 = axs[0].imshow(np.zeros((154, 154, 3)))

    axs[1].set_title("Temperature Image")
    ax1 = axs[1].imshow(np.zeros((154, 154, 3)))
    fig.suptitle("Undefined")

    plt.ion()

    while True:
        # Capture Image
        rgb_img, tmp_dat = read_cameras(cam)
        # ite += 1

        # Crop Image
        rgb_cropped = crop_and_resize_image(rgb_img, rgb_minmax, rgb_dim, RES)
        #print(rgb_cropped.shape)
        tmp_cropped = crop_and_resize_data(tmp_dat, tmp_minmax)
        #print(tmp_cropped.shape)
        # print(rgb_cropped)
        # print(tmp_cropped)

        # Feed Forward
        # Transform images
        rgb_cropped_show = Image.fromarray(rgb_cropped.astype(np.uint8))
        print(rgb_cropped_show)
        tmp_cropped_show = Image.fromarray(tmp_cropped.astype(
            np.uint8)).convert('RGB')
        print(tmp_cropped_show)
        rgb_cropped = data_transform(rgb_cropped_show)
        tmp_cropped = data_transform(tmp_cropped_show)

        # Add 4th dimension
        rgb_cropped = torch.Tensor(rgb_cropped).unsqueeze(0)
        tmp_cropped = torch.Tensor(tmp_cropped).unsqueeze(0)

        rgb_feature = vgg.features(rgb_cropped)
        tmp_feature = vgg.features(tmp_cropped)

        # Concatenate features
        rgb_feature_tensor = torch.from_numpy(rgb_feature.detach().numpy())
        tmp_feature_tensor = torch.from_numpy(tmp_feature.detach().numpy())
        rgb_tmp_combined_tensor = torch.cat(
            (rgb_feature_tensor, tmp_feature_tensor), dim=1)
        rgb_tmp_combined_tensor = avgpool(rgb_tmp_combined_tensor)
        rgb_tmp_combined_tensor = torch.flatten(rgb_tmp_combined_tensor)

        # Maintain Feature Queue
        feature_queue.append(rgb_tmp_combined_tensor.detach().numpy())
        if len(feature_queue) < 8:
            continue

        feature_input_tensor = torch.Tensor(np.array(feature_queue, ndmin=3))
        outputs = lstm_model(feature_input_tensor)
        # print(outputs)
        predicted_class = outputs.detach().numpy().argmax()
        print(classes[predicted_class])
        feature_queue.pop(0)

        #axs[0].set_title("RGB Image")
        ax0.set_data(rgb_cropped_show)

        #axs[1].set_title("Temperature Image")
        ax1.set_data(tmp_cropped_show)
        # plt.show()
        fig.suptitle(classes[predicted_class])
        plt.pause(0.01)

    plt.ioff()
    plt.show()
    cam.release()
    cv2.destroyAllWindows()
Example #24
0
    plt2 = plt.twinx()
    plt.ylim(0,100)
    plt2.plot(hum,"b^-",label="Ilmankosteus %")
    plt2.set_ylabel("Ilmankosteus %")
    plt2.ticklabel_format(useOffset= False)
    plt2.legend(loc = 'upper right')


while True:
    try:
        row= ser.readline()
        print(row)
        if(len(row)>3):
           sensor[0] = str(row[0:5])
           sensor[1] = str(row[5:10])
           sensor[0] = float(repr(sensor[0])[3:-2])
           sensor[1] = float(repr(sensor[1])[3:-2])
           print("Lampotila: ",sensor[1])
           print("Ilmankosteus: ",sensor[0])
           temp.append(sensor[1])
           hum.append(sensor[0])
           drawnow(makeFig)
           plt.pause(.000001)
           if(laskuri > 50):
               temp.pop(0)
               hum.pop(0)
    
    except IOError:
        print('Error tuli')
    time.sleep(tauko)
Example #25
0
# generates lstm model for s (takes about 1-2 minutes) :
src = lol.weather_station(df_t, dhist, dhoriz, n_years_2train, 'lstm')

start = src.data.index[src.year_train*365+src.dd_historic+src.dd_horizon] #first day after validation data
end =  df_t.index[-src.dd_horizon-1]
Harvest, Harvest_hat = start, start
for today in pd.date_range(start,end):
    ind_curr = pd.date_range(today-timedelta(dhist-1),today)
    x_input = df_t.loc[ind_curr]
    yhat = yhat = src.lstm_predict(x_input)

    plt.figure(1), plt.cla()
    x_input.plot(style='b-')
    df_t.loc[yhat.index].plot(style='g-')
    yhat.plot(style='r--')
    plt.pause(0.0001)

    ind_pred = yhat.index
    yhat = lol.gdd(df_t.loc[pd.date_range(today-timedelta(365),today)].append(yhat))

    ind_curr_year = df_aGDD_s[df_aGDD_s.index. year == today.year].index
    Harvest = df_aGDD_s[ind_curr_year][df_aGDD_s[ind_curr_year] <= 500].index[-1].date()

    ind_curr_year = yhat[yhat.index. year == today.year].index
    Harvest_hat = yhat[ind_curr_year][yhat[ind_curr_year] <= 500].index[-1].date()

    plt.figure(2), plt.cla()
    df_aGDD_s[ind_curr].plot(style='b-')
    df_aGDD_s.loc[ind_pred].plot(style='g-')
    yhat[ind_pred].plot(style='r--')
    plt.legend(['past temperatures', 'future temperatures', 'forecast'])