here are my two vectors-:
y1=[2,3,4,5,6,7]
y2=[1,5,3,6,7,8]
when i solve it with pen and paper!
it gives me an ans -: y1= 1.117y2
when i do that in python
import numpy as np
from numpy import linalg as LA
A = np.array([y1,y2])
w, v = LA.eig(A)
print(w)
print(v)
this error occurs LinAlgError: Last 2 dimensions of the array must be square
how can i solve this problem!
please help me , how can i do that!!
The issue here is that eigenvalues can only exist for square matrices, therefore Numpy expects to see an n x n dimensional matrix and not an n x m dimensional matrix such as the 2 x 6 matrix A in your example.
Related
Given two vectors X and Y, where the number of elements in each is 5. Find a V vector that satisfies :
||X-V||=||Y-V||=||X-Y||
(X,Y,V) are the vertices of an equilateral triangle.
I have tried the following:
To get a vector V that is perpendicular to A and B :
import NumPy as np
# Example vectors
x = [ 0.93937874, 0.05568767, -2.05847484, -1.15965884, -0.34035054]
y = [-0.45921145, -0.55653187, 0.6027685, 0.13113272, -1.2176953 ]
# convert those vectors to a matrix to apply SVD (sure there is a shorter code to do so)
A_list=[]
A_list.append(x)
A_list.append(y)
A=np.array(A_list) # A is a Numpy matrix
u,s,vh=np.linalg.svd(A)
v=vh[-1:1]
From here, what should I do? assuming that what I have done so far is correct
import pandas as pd
import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
df = pd.read_csv('homeprices.csv')
plt.xlabel('area')
plt.ylabel('price')
plt.scatter(df.area,df.price,color='red',marker='.')
reg = linear_model.LinearRegression()
reg.fit(df.area,df.price)
Error Message:
ValueError: Expected 2D array, got 1D array instead:
array=[2600 3000 3200 3600 4000].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
It works fine if I write it as :
reg.fit(df[['area']],df.price)
I would like to know the reason behind it because The second argument is passed as df.price.
My csv file:
area,price
2600,550000
3000,565000
3200,610000
3600,680000
4000,725000
From the documentation, variable x should be declared as
X{array-like, sparse matrix} of shape (n_samples, n_features)
When you declare:
x = df.area or x = df['area'] the x will become Series type with the size (n,). The size should be (n, z), where z can be any positive integer.
x = df[['area']] the x will become DataFrame type with the size (5, 1) which makes an x an acceptable input.
y = df.price the y will become Series type with the size (5,) which s acceptable input.
y: array-like of shape (n_samples,)
But if I were you I declare x and y as:
x = [[i] for i in df['area']]
y = [i for i in df['price']]
which makes both x and y as the list structure and set the size to the (5, 1), so in the future if you want to run in any ML library (tensorflow, pytorch, keras, ...) you won't have any difficulties.
It's all about the input shape, the error was raised because its shape was (N,) while the correct one should be (N,1). That's why the error message suggests you to reshape.
I need to find zero-crossings in a 1D array of a roughly periodic function. It will be the points where an orbiting satellite crosses the Earth's equator going north.
I've worked out a simple solution based on finding points where one value is zero or negative and the next is positive, then using a quadratic or cubic interpolator with scipy.optimize.brentq to find the nearby zeros.
The interpolator does not go beyond cubic, and before I learn to use a better interpolator I'd first like to check if there already exists a fast method in numpy or scipy to find all of the zero crossings in a large array (n = 1E+06 to 1E+09).
Question: So I'm asking does there already exist a faster method in numpy or scipy to find all of the zero crossings in a large array (n = 1E+06 to 1E+09) than the way I've done it here?
The plot shows the errors between the interpolated zeros and the actual value of the function, the smaller line is the cubic interpolation, the larger is quadratic.
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy.optimize import brentq
def f(x):
return np.sin(x + np.sin(x*e)/e) # roughly periodic function
halfpi, pi, twopi = [f*np.pi for f in (0.5, 1, 2)]
e = np.exp(1)
x = np.arange(0, 10000, 0.1)
y = np.sin(x + np.sin(x*e)/e)
crossings = np.where((y[1:] > 0) * (y[:-1] <= 0))[0]
Qd = interp1d(x, y, kind='quadratic', assume_sorted=True)
Cu = interp1d(x, y, kind='cubic', assume_sorted=True)
x0sQd = [brentq(Qd, x[i-1], x[i+1]) for i in crossings[1:-1]]
x0sCu = [brentq(Cu, x[i-1], x[i+1]) for i in crossings[1:-1]]
y0sQd = [f(x0) for x0 in x0sQd]
y0sCu = [f(x0) for x0 in x0sCu]
if True:
plt.figure()
plt.plot(x0sQd, y0sQd)
plt.plot(x0sCu, y0sCu)
plt.show()
Hi so basically my question is I have a matrix which I've SVD decomposed and have it in the variables u, s, and v. I've made some alterations to the s matrix to make it diagonal, as well as altered some of the numbers. Now I'm basically trying to reconstruct it into a regular matrix from the 3 matrices back into the original matrix. Does anyone know of any functions that do this? I can't seem to find any examples of this within numpy.
The only mildly tricky bit would be "expanding" s If you have scipy installed it has scipy.linalg.diagsvd which can do that for you:
>>> import numpy as np
>>> import scipy.linalg as la
>>>
>>> rng = np.random.default_rng()
>>> A = rng.uniform(-1,1,(4,3))
>>> u,s,v = np.linalg.svd(A)
>>>
>>> B = u#la.diagsvd(s,*A.shape)#v
>>>
>>> np.allclose(A,B)
True
I figured it out, just using the np.matmul() function and then just multiplying the 3 matrices of u s and v together was enough to get them back into an original matrix.
I have a numpy 2D array self.sub
and i want to use it in rpy2 kmeans.
k = robjects.r.kmeans(self.sub,2,20)
i always get the following error:
valueError: nothing can be done for the type at the moment!
what can i do?
From the rpy2 docs, R matrices are just vectors with their dim attribute set. So for a numpy two-dimensional array x
import rpy2.robjects as robj
nr, nc = x.shape
xvec = robj.FloatVector(x.transpose().reshape((x.size))
xr = robj.r.matrix(xvec, nrow=nr, ncol=nc)
You have to transpose the numpy array because R fills matrices by columns.
Edit: Actually, you could just set byrow=True in the R matrix function, and then you wouldn't need to transpose.