I'm getting a matmul: input operand 1 has a mismatch...error...full error in body

Viewed 1050

The error: ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 1 is different from 2)

I'm doing linear regression with a csv dataframe. After reshaping and fitting the x and y values i run into this error, highlighting the model.predict part.

My code:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import requests
import io 
import csv

url = "https://raw.githubusercontent.com/DairyProducts/misc/main/cadeath.csv"
download = requests.get(url).content

df = pd.read_csv(io.StringIO(download.decode('utf-8')))

x = df['x'].to_numpy()
y = df['y'].to_numpy()

model = LinearRegression()
x = x.reshape(-1, 1)
y = y.reshape(-1, 1)
model.fit(x, y)
r_sq = model.score(x, y)
y_pred = model.intercept_ + np.sum(model.coef_ * x, axis=1)
x_new = np.arange(10).reshape((-1, 2))
y_new = model.predict(x_new)
plt.plot(x_new, y_new)
plt.show()
1 Answers

The x shape you fit the model in model.fit(x, y) is (361, 1). The x shape you predict in model.predict(x_new) is (5, 2). Their second dimension doesn't match. You may need to change x_new shape like

x_new = np.arange(10).reshape((-1, 1))
Related