cyw
cyw

Reputation: 63

How to fix shapes not aligned when reading from CSV file in python

I'm trying to import a dataset from CSV file in Python, but it showed an error of "shapes not aligned". I wonder if anyone knows how to solve this.

here is my code

import numpy as np
from numpy import genfromtxt

x = genfromtxt('problem1.csv', delimiter=',')

def model(x,w):
    a = w[0] + np.dot(x.T,w[1:])
    return a.T

#define sigmoid function
def sigmoid(t):
    return 1/(1 + np.exp(-t))

#the convex cross-entropy cost function
def cross_entrypy(w):

    #compute sigmoid of model
    a = sigmoid(model (x,w))

    #compute cost of label 0 points
    ind = np.argwhere (y == 0) [:,1]
    cost = -np.sum(np.log(1 - a[:,ind]))

    #add cost on label 1 points
    ind = np.argwhere(y==1)[:,1]
    cost -= np.sum(np.log(a[:,ind]))

    #compute cross-entropy
    return cost/y.size

print(cross_entrypy([3,3]))

here is my dataset looks like

enter image description here

This is the error message I received enter image description here

--update--

enter image description here

This is the practice question where the dataset is use for

Upvotes: 0

Views: 254

Answers (1)

Ka Wa Yip
Ka Wa Yip

Reputation: 3009

Array dimension

I am not sure what the meaning of your dataset is, but x has shape (11,2), w has shape of (1,).

Source of error

From your screenshot, the error is in np.dot(x.T,w[1:]). You cannot do dot product on x.T and w[1:], because of the dimensionality mismatch.

Possible solutions

  1. Simply add the line of x=x[0] or x=x[1], right after x = genfromtxt('problem1.csv', delimiter=',').
  2. An alternative solution would be: change np.dot(x.T,w[1:]) to np.dot(x[0].T,w[1:]), or np.dot(x[1].T,w[1:]).

Upvotes: 1

Related Questions