toy
toy

Reputation: 12141

How do I create matrix in numpy to be called like this?

I'm trying to learn Gradient descend from the internet and in the code it has something like this.

for i in range(len(points)):
   x = points[i].x
   y = points[i].y

However, I generate my dataset my self by

x = np.random.randint(10000, size=100000000)
y = x * 0.10

How do I create points with x and y to be able to fit into the code?

Upvotes: 0

Views: 42

Answers (2)

sinhayash
sinhayash

Reputation: 2803

Use this:

x = np.random.randint(10000, size=100000000)
y = x * 0.10
np.column_stack((x,y))

This will use numpy optimisations for speed. More here

and change code to this

for i in range(len(points)):
   x = points[i][0]
   y = points[i][1]

If you want .x, .y to work: Use a class:

class point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
#[OR]

import collections
Point = collections.namedtuple('Point', ['x', 'y'])


#and then

for i in range(len(x)):
    points.append(point(x[i],y[i]))

This would perform slower

Upvotes: 3

Akshat Harit
Akshat Harit

Reputation: 824

I am guessing its a class. You can make a dummy class as follows

import numpy as np
class p:
    def __init__(self,x,y):
        self.x=x
        self.y=y


points = []
x = np.random.randint(10000, size=100000000)
y = x * 0.10
for i in range(len(x)):
    points.append(p(x[i],y[i]))

for i in range(len(points)):
   x = points[i].x
   y = points[i].y

This is probably quite inefficient though. But if you want the same interface to work, this should be good enough.

Upvotes: 0

Related Questions