- 1
Given a 2D array, feature matrix X and a vector y, return the coefficient vector, see the formula.
Task Given a 2D array, feature matrix X and a vector y, return the coefficient vector, see the formula. Input Format First line: two integers separated by spaces, the first indicates the rows of matrix X (n) and the second indicates the columns of X (p) Next n lines: values of the row in the feature matrix Last line: p values of target y Output Format An numpy 1d array of values rounded to the second decimal. 2 2 1 0 0 2 Sample Output [2. 1.5]
5 Respuestas
+ 1
import numpy as np
from numpy.linalg import inv
n, p = [int(x) for x in input().split()]
X = []
for i in range(n):
X.append([float(x) for x in input().split()])
y = [float(x) for x in input().split()]
arX = np.array(X)
ary = np.array(y)
# Gram Matrix = X.T * X or <Transpose of matrix regressor variable X>*<matrix regressor variable X>
gramInverse = inv(np.dot(arX.T, arX))
# Moment Matrix = X.T * y or <Transpose of matrix regressor variable X> * <vector of the value of the response variable>
moment = np.dot(arX.T, ary)
# beta = inverse of (Gram Matrix) * Moment Matrix
beta = np.dot(gramInverse, moment)
print(np.around(beta, decimals = 2))
+ 1
# I found this code works
import numpy as np
n, p = [int(x) for x in input().split()]
X = []
for i in range(n):
X.append([float(x) for x in input().split()])
y = [float(x) for x in input().split()]
X=np.linalg.lstsq(X, y, rcond = -1)
print (X[0].round(2))
0
I've written a code which is as follows
import numpy as np
n, p = [int(x) for x in input().split()]
lista = []
for i in range(n):
lista.append(input().split())
print(np.array(lista).astype(np.float16).mean(axis=1).round(2))
[input]
2 2
1 0
0 2
[output]
[0.5 1. ]
required output
[2., 1.5]
0
n, p = [int(x) for x in input().split()]
X = []
for i in range(n):
X.append([float(x) for x in input().split()])
y = [float(x) for x in input().split()]
import numpy as np
coef_mat = np.linalg.lstsq(X ,y, rcond= None)[0].round(2)
print(coef_mat)
0
import numpy as np
X = np.array(X)
y = np.array(y)
solucion = np.linalg.lstsq(X, y, rcond=-1)
print (solucion[0].round(2))