Exemplo n.º 1
0
    def __init__(self):
        self.Kp = 6.0  #7.0
        self.Ki = 0.5  #2.0
        self.Kd = 3.0  #3.0
        self.mode = 0
        self.errorL_1 = 0.0
        self.UiL_1 = 0.0
        self.errorR_1 = 0.0
        self.UiR_1 = 0.0
        self.ref_WL = 0.0
        self.ref_WR = 0.0
        self.wr = 0.0
        self.wl = 0.
        self.il = 0.0
        self.ir = 0.0
        self.encl = 0.0
        self.encr = 0.0
        self.a = np.arry([0, 0, 0])
        self.av = np.arry([0, 0, 0])

        topics_list = [
            '/UL', '/UR', '/WL', '/WL_ref', '/WR', '/WR_ref', '/enc_L',
            '/enc_R', '/iL', '/iR', '/voltage', '/um7', '/imu/data'
        ]
        self.topic2save = ' '.join(topics_list)

        (self.options, self.args) = parser.parse_args()

        rospy.init_node("Ident_model")
Exemplo n.º 2
0
    def train(self,inputs_list,target_list):
        #将输入列表转化为二阶矩阵
        inputs = numpy.array(input_list,ndmin = 2).T
        targets = numpy.arry(target_list,ndmin = 2).T
        #如何进行隐藏层计算,同query函数中的一样
        hidden_inputs = numpy.dot(self,wih,inputs)
        hidden_inputs = self.activation_function(hidden_inputs)

        #如何计算最终层,同上
        final_inputs = numpy.dot(self.who,hidden_inputs)
        final_outputs = self.activation_function(final_inputs)
        
        #计算误差,误差 = 目标值target - 最终值final_outputs
        output_errors = targets - final_outputs

        #将输出时得到的误差根据权重反向分配到隐藏层,将误差进行重组
        hidden_error = numpy.dot(self.who.T , output_errors)

        #更新隐藏层和输出层之间的分配权重
        self.who+= self.lr*numpy.dot((output_errors * final_outputs * (1.0 - final_outputs)),numpy.tranpose(hidden_outputs
            ))
        
        #更新输入层和隐藏层之间的分配权重,方法同上
        self.wih+= self.lr*numpy.dot((hidden_errors * hidden_outputs * (1.0 - hidden_outputs)),numpy.tranpose(inputs))
        pass
Exemplo n.º 3
0
def get_mean_std_dataset(root_dir):
    """
	Function to compute mean and std of image dataset.
	Move batch_size param according to memory resources.
	retrieved from: https://forums.fast.ai/t/image-normalization-in-pytorch/7534/7
	"""

    # data_domain = "amazon"
    # path_dataset = "datasets/office/%s/images" % data_domain

    transform = transforms.Compose([
        transforms.Resize((224, 224)),  # original image size 300x300 pixels
        transforms.ToTensor()
    ])

    dataset = datasets.ImageFolder(root=root_dir, transform=transform)

    # set large batch size to get good approximate of mean, std of full dataset
    # batch_size: 4096, 2048
    data_loader = DataLoader(dataset,
                             batch_size=2048,
                             shuffle=False,
                             num_workers=0)

    mean = []
    std = []

    for i, data in enumerate(data_loader, 0):
        # shape is (batch_size, channels, height, width)
        npy_image = data[0].numpy()

        # compute mean, std per batch shape (3,) three channels
        batch_mean = np.mean(npy_image, axis=(0, 2, 3))
        batch_std = np.std(npy_image, axis=(0, 2, 3))

        mean.append(batch_mean)
        std.append(batch_std)

    # shape (num_iterations, 3) -> (mean across 0th axis) -> shape (3,)
    mean = np.array(mean).mean(axis=0)  # average over batch averages
    std = np.arry(std).mean(axis=0)  # average over batch stds

    values = {"mean": mean, "std": std}

    return values
def load_dataset(path, file_ext=".jpg"):
    '''
    resize the image
    assuming row*col = 720*1080
    '''

    images = []
    print ('------------------------------------------')
    print ('loading data_set')
    print ('path :' , path)
    print ('file_ext : ', file_ext)
    print ('------------------------------------------')

    # images_list -> stores a list of names
    # of images in the form of a strig
    images_list = glob.glob(path + "*" + file_ext)
    for i in images_list:
        img = cv2.imread(i)
        img = cv2.resize(img, (storage_class.resize_col, storage_class.resize_row), interpolation=cv2.INTER_LINEAR)
        img = img.astype(np.float32)
        images.append(img)
    images = np.arry(images)
    return images
Exemplo n.º 5
0
def plot_return_risk():
    ret, vol = return_risk(stocks)
    color = np.arry([0.18, 0.96, 0.75, 0.3, 0.9, 0.5])
    plt.scatter(ret,
                vol,
                marker='o',
                c=color,
                s=500,
                camp=plt.get_cmap('Spectral'))
    plt.xlable("日收益率均值%")
    plt.ylable("标准差%")
    for lable, x, y in zip(stocks.keys(), ret, vol):
        plt.annotate(lable,
                     xy=(x, y),
                     xytext=(20, 20),
                     textcoords="offset points",
                     ha="right",
                     va="bottom",
                     bbox=dict(boxstyle='round,pad=0.5',
                               fc='yellow',
                               alpha=0.5),
                     arrowprops=dict(arrowstyle="->",
                                     connetionstyle="arc3,rad=0"))
NameError: name 'x' is not defined
>>> X.shape
(26048, 72)
>>> X.describe
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    X.describe
AttributeError: 'numpy.ndarray' object has no attribute 'describe'
>>> X.describe()
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    X.describe()
AttributeError: 'numpy.ndarray' object has no attribute 'describe'
>>> X.dtype
dtype('float64')
>>> X = np.arry (df.iloc[:, column != 'netgain'])
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    X = np.arry (df.iloc[:, column != 'netgain'])
AttributeError: module 'numpy' has no attribute 'arry'
>>> X = np.array (df.iloc[:, column != 'netgain'])
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    X = np.array (df.iloc[:, column != 'netgain'])
NameError: name 'column' is not defined
>>> X = np.array (df.iloc[:, columns != 'netgain'])
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    X = np.array (df.iloc[:, columns != 'netgain'])
NameError: name 'columns' is not defined
>>> X = np.array(df.iloc[:,df.columns !='netgain'])
Exemplo n.º 7
0
arr = randn(4,4)
np.where(arr>0,2,-2)# if arr is greater than 0, insert 2, otherwise, insert -2
# consider Excel's if function: if(boolean_testing, value_if_true, value_if_false)
# both np.where and Excel's if function can be nested, e.g.
cond1 = randn(1,100)>0
cond2 = randn(1,100)<0
result = np.where(cond1 & cond2,0, np.where(cond1,1,np.where(cond2,2,3)))
#alternatively, use boolean expression
result = 1*cond1 + 2*cond2 + 3* -(cond1 | cond2) #but more difficult to come to first thought

# statistical:
np.mean(arr,axis=0)
np.std(arr,ddof=1)#denominator: N - ddof, default 0

# boolean arrays
bools = np.arry([True,False,False,True,False])
bools.all
bools.any

# sorting
arr = randn(8)
arr.sort() # will return a copy of the sorted array
# unique
arr.unique() # applies to both numerics and strings

# save binary data
arr = np.arrange(10)
np.save('some_array.npy',arr) # save on the disk, if name not appended .npy, will append automatically
np.load('som_array.npy') # load array
np.savez('array_archive.npz',a=arr,b=arr) # save as a zip archive of arrays
#when loading an archive, the result will be a dictionary like object
Exemplo n.º 8
0
    ids = []
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
    #print(imagePaths)

    face_engine = cv.CascadeClassifier(
        '/home/pi/Downloads/opencv-3.4.0/data/haarcascades/haarcascade_frontalface_default.xml'
    )

    for imagePath in imagePaths:
        PIL_img = Image.open(imagePath).convert('L')
        img_numpy = np.array(PIL_img, 'uint8')
        faces = face_engine.detectMultiScale(img_numpy,
                                             scaleFactor=1.1,
                                             minNeighbors=5)
        #print(os.path.split(imagePath))
        id = int(os.path.split(imagePath)[1].split('.')[0])
        #id = int(os.path.split(imagePath)[-1].split('.')[0])
        for x, y, w, h in faces:
            facesSamples.append(img_numpy[y:y + h, x:x + w])
            ids.append(id)

    return faceSamples, ids


if __name__ == '__main__':
    #tu pian lu jing
    path = './data/da/'
    faces, ids = getImageAndLabels(path)
    recognizer = cv.face.LBPHFaceRecognizer_create()
    recognizer.train(faces, np.arry(ids))
    recognizer.write('tr/tr.yml/')
Exemplo n.º 9
0
 def trnsFnc(self, entrada, zm1):
     self.preintval = -arry(sgn(self.integral - entrada) * self.gain) * arry(
         power(abs(self.integral - entrada), potencia(self.orden))) + zm1
Exemplo n.º 10
0
    def callback(self, irvalue):
        frontIRvalueCaptured = 0
        sideIRvalueCaptured = 0
        for i in irvalue.motor_states:
            if i.name == "Side_IR":
                self.ir_samples[1].append(i.pulse)
                #print self.ir_sample_count," side ir : ",i.pulse
                sideIRvalueCaptured = 1
            if i.name == "Front_IR":
                self.ir_samples[0].append(i.pulse)
                #print self.ir_sample_count," front ir : ",i.pulse
                frontIRvalueCaptured = 1
            if sideIRvalueCaptured and frontIRvalueCaptured:
                self.ir_sample_count += 1
                break

        if not sideIRvalueCaptured and not frontIRvalueCaptured:
            print "No IR sensor data received"
            return

        if self.ir_sample_count > 10:
            self.ir_samples[1][self.ir_sample_count - 1] = np.median(
                np.array(self.ir_samples[1])[-10:])  #For Front IR sensor
            self.ir_samples[0][self.ir_sample_count - 1] = np.median(
                np.array(self.ir_samples[0])[-10:])  #For Side IR sensor
            #self.plotlist.append(self.side_ir_pulse)

        frontDistance = computeDistance(
            self.ir_samples[0][self.ir_sample_count - 1], True)
        sideDistance = computeDistance(
            self.ir_samples[1][self.ir_sample_count - 1], False)

        self.CalculateDeltaPulse()
        goal = pololu_trajectoryGoal()
        traj = goal.joint_trajectory
        traj.header.stamp = rospy.Time.now()
        traj.joint_names.append(names[0])
        pts = JointTrajectoryPoint()
        pts.time_from_start = rospy.Duration(1.0)

        if frontDistance > 300:  # No wall in front
            if self.turningRight:  #Now there is no wall in front. So, set "turningRight" to False.
                self.turningRight = False
            if sideDistance == 50:  # Too close to the wall
                moveMotorLeft(
                    Max_left_limit, pts
                )  # stear with max left angle (should be changed with function)
            elif sideDistance > 250:  # Too far from the wall
                moveMotorRight(
                    Max_right_limit, pts
                )  # stear with max left angle (should be changed with function)
            elif sideDistance > 160:
                moveMotorRight(self.side_ir_delta_pulse, pts)
            elif sideDistance < 150:
                moveMotorLeft(self.side_ir_delta_pulse, pts)
            else:
                moveMotorCenter(pts)
        else:
            if frontDistance < 200:
                if self.turningRight:
                    moveMotorRight(Max_right_limit, pts)
                else:
                    moveMotorLeft(Max_left_limit, pts)
            elif sideDistance == 50:  # Too close to the wall
                moveMotorLeft(
                    Max_left_limit, pts
                )  # stear with max left angle (should be changed with function)
            elif sideDistance > 300:  #If no wall is detected by right side sensor, then take right turn
                self.turningRight = True
                moveMotorRight(Max_right_limit, pts)
            elif sideDistance > 160:
                moveMotorRight(self.side_ir_delta_pulse, pts)
            elif sideDistance < 150:
                moveMotorLeft(self.side_ir_delta_pulse, pts)
            else:
                moveMotorCenter(pts)

        pts.velocities.append(1.0)
        traj.points.append(pts)
        client.send_goal(goal)

        #if self.ir_sample_count == 1000:
        #	print len(self.plotlist)
        #	fig, ax =plt.subplots()
        #	plt.subplot(1,2,1),plt.plot(range(1,self.ir_sample_count+1),self.ir_samples[1],label="raw")
        #	plt.subplot(1,2,2),plt.plot(range(1,len(self.plotlist)+1),self.plotlist,label="median")
        #	ax.set_axisbelow(True)
        #	ax.set_ylim(80,200)
        #	plt.legend(loc="center right")
        #	plt.show()

        if ir_sample_count > 100:
            temp = np.arry(self.ir_samples[1])[-11:]
            del ir_samples[1][:]
            self.ir_samples[1] = temp
            temp = np.arry(self.ir_samples[0])[-11:]
            del ir_samples[0][:]
            self.ir_samples[0] = temp
            self.ir_sample_count = 10

        client.wait_for_result(rospy.Duration.from_sec(0.005))
Exemplo n.º 11
0
import caffe
import numpy as np
import sys

if len(sys.argv) != 3:
    print "Usage: python convert_protomean.py proto.mean out.npy"
    sys.exit()

blob = caffe.proto.caffe_pb2.BlobProto()
data = open(sys.argv[1], 'rb').read()
blob.ParseFromString(data)
arr = np.arry(caffe.io.blobproto_to_array(blob))
out = arr[0]
np.save(sys.argv[2], out)
Exemplo n.º 12
0
NameError: name 'arr' is not defined



import numpy as np

lst=[1,2,3]

for i in lst:
    print(i**2)

arr = np.array(lst)
arr
arr**2 

arr = np.arry([1,'two',3])
arr
1
4
9
Traceback (most recent call last):

  File "<ipython-input-8-b3566ca72dc1>", line 12, in <module>
    arr = np.arry([1,'two',3])

  File "C:\Users\user\anaconda3\lib\site-packages\numpy\__init__.py", line 220, in __getattr__
    "{!r}".format(__name__, attr))

AttributeError: module 'numpy' has no attribute 'arry'

Exemplo n.º 13
0
def moving_average(vals, n):
    out = []
    for i in range(len(val) - n - 1):
        out[i] = vals[i:i + n].mean()
    return np.arry(vals)
Exemplo n.º 14
0
	def trnsFnc(self,entrada,zm1):
		self.preintval=-arry(sgn(self.integral-entrada)*self.gain)*arry(power(abs(self.integral-entrada),potencia(self.orden)))+zm1
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 08:45:53 2015

@author: ABerner
"""

# Code snippet from pg 200

import numpy as np
from quantecon import mc_sample_path
P = np.array([[.4,.6],[.2,.8]])
s = mc_sample_path(P, init=(0.5, 0.5), sample_size=100000)
print((s ==0).mean())

# Example: Powers of a Markov Matrix on page 201

P = np.array([[.971,.029,0],[.145,.778,0.077],[0,0.508,0.492]])
psi = np.arry([0.80,0.19,0.01]) #hypothetical state probability estimate vector
np.inner(np.dot(psi,np.linalg.matrix_power(P,6)),np.array([0,1,1])) #6m forward forecast of recession probability given the current state estimates